Create table in SQLite only if it doesn't exist already

SqliteCreate TableDatabase Table

Sqlite Problem Overview


I want to create a table in a SQLite database only if doesn't exist already. Is there any way to do this? I don't want to drop the table if it exists, only create it if it doesn't.

Sqlite Solutions


Solution 1 - Sqlite

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

Solution 2 - Sqlite

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 
        
        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
        
        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser461112View Question on Stackoverflow
Solution 1 - SqliteDavid WoleverView Answer on Stackoverflow
Solution 2 - SqliteaaronlheView Answer on Stackoverflow