Check table exist or not before create it in Oracle

As Rene also commented, it’s quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
  nCount number;
  v_sql clob;
begin
  select count(*) into nCount from dba_tables where table_name="EMPLOYEE";

  if ncount <= 0 then
    v_sql := '
      create table employee
      (
        id number,
        name varchar2(30) not null
      )';

    execute immediate v_sql;

  end if;
end;
/

But I’d rather go catch on the Exception, saves you some unnecessary lines of code:

declare
  v_sql clob;
begin
  v_sql := '
    create table employee
    (
      id number,
      name varchar2(30) not null
    )';

  execute immediate v_sql;
exception
  when others then
    if sqlcode = -955 then
      null; -- suppresses ora-00955 exception
    else
      raise;
  end if;
end; 
/

Since Oracle 23c, you can use the simpler IF NOT EXISTS syntax:

create table if not exists employee
(
  id number,
  name varchar2(30) not null
);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)