52

My version of SQLite does not support the IF EXISTS operator. How can I drop a table which may or may not exist without getting an error slapped at me?

I can't update the version on a live application right now, so I cannot use a SQLite version that supports IF EXISTS.

mit
  • 11,083
  • 11
  • 50
  • 74
HyderA
  • 20,651
  • 42
  • 112
  • 180

4 Answers4

129

You can use:

DROP TABLE IF EXISTS TABLE_NAME;
animuson
  • 53,861
  • 28
  • 137
  • 147
Amit Jatrana
  • 1,475
  • 2
  • 9
  • 2
33

The official documentation says to use IF EXISTS, so I suspect your best plan is to upgrade.

If you can't, you need to see whether you can do some trivial operation on the table that will succeed whether or not the table is empty; if it succeeds you should delete the table, if it fails the table is already gone. An example of the sort of operation to try might be:

SELECT COUNT(*) FROM theTable;

Note that you need to trap the possible error from this at the language level, and you might want to wrap the whole lot (probe, error-trap, drop table) in a transaction. Of course, the other approach if you're getting into error handling is to just drop the table and handle the error anyway.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
8

Just use this.

DROP TABLE TABLE_NAME;
Ben
  • 51,770
  • 36
  • 127
  • 149
Ahmad affandi
  • 81
  • 1
  • 1
  • This works but it gives and Error if the table already exists – patJnr Mar 18 '19 at 07:16
  • 1
    @patJnr: You mean, it gives an error if the table does **not** exist. True, but as `DROP TABLE IF EXISTS` is not supported as for the OP, this is the best bet. Just catch the error, analyze it and proceed. – tanius Apr 26 '20 at 20:26
3

You could somehow use the metadata table in your query to find out if the table exist:

SELECT count(*) > 0 FROM sqlite_master where tbl_name = "<table_name>" and type="table"
Marcus
  • 1,866
  • 1
  • 20
  • 33
  • Hmm... how would I use that when dropping the table? – HyderA Sep 09 '10 at 08:52
  • can't you write "if (SELECT count(*) FROM sqlite_master where tbl_name = "" and type="table") > 0 then drop table " Don't know if that's correct syntax for sqlite though. – Marcus Sep 09 '10 at 09:25