Oleksandr Gavenko's blog
2017-03-05 23:50 Create table if not exists in Oracle

We need to reset our Flyway history due to major DB refactoring. All changes would be squashed into a single that creates a base schema to be able to recreate database from scratch.

But we don't want conflicts with existing tables in production.

MySQL database has syntax to prevent error on create table if table already exists:

create table if not exist "TBL" (...);

Unfortunately Oracle database doesn't have such syntax. It can be mimicked with PL/SQL code block and exception handling. Because PL/SQL code doesn't allow DDL code dynamic queries are used:

  execute immediate 'create table "TBL" ("ID" number not null)';
  exception when others then null;

More safer implementation checks for error code:

ORA-00955: name is already used by an existing object

which same for create table, and create index, and create sequence, etc and report error otherwise. Final solution looks like:

  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
sql, oracle


all / emacs / java


adb(1), admin(1), android(1), anki(1), ansible(2), blog(2), c(1), css(2), cygwin(2), driver(1), emacs(3), fs(1), git(3), google(1), gradle(1), hardware(1), hg(2), html(1), interview(13), java(3), js(3), lang(2), lighttpd(1), markdown(1), mobile(1), naming(1), oracle(1), print(1), problem(5), python(1), quiz(6), rst(2), security(3), spring(1), sql(2), srs(1), style(1), tls(2), txt(1), unit(1), utils(1), vcs(3), web(2), win(2), windows(1)