Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop table in old version of SQLite where IF EXISTS is not supported

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.

like image 544
HyderA Avatar asked Sep 09 '10 08:09

HyderA


People also ask

What happens if you drop a table that doesn't exist?

The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.

Are there restrictions on dropping tables in SQLite?

Normally in SQL you drop foreign keys with the ALTER TABLE statement, but SQLite's ALTER TABLE implementation doesn't allow for dropping constraints. There is a way to deal with this situation though.

How would you drop a table in SQLite database?

To drop a table in SQLite, use the DROP TABLE statement. Running this statement removes the table from the database. It is completely removed from the database schema and the disk file. Therefore the table can not be recovered.

Can we use drop with where clause?

WHERE clause mainly used along with the DELETE command. No clause required along with DROP command. Actions performed by DELETE can be rolled back as it uses buffer. Actions performed by DROP can't be rolled back because it directly works on actual data.


2 Answers

You can use:

DROP TABLE IF EXISTS TABLE_NAME; 
like image 84
Amit Jatrana Avatar answered Sep 21 '22 02:09

Amit Jatrana


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.

like image 40
Donal Fellows Avatar answered Sep 18 '22 02:09

Donal Fellows