63

I need to check to see if a column exists and if it doesn't exist add it. From my research it looks like sqlite doesn't support IF statements and case statement should be used instead.

Here is what I have so far:

SELECT CASE WHEN exists(select * from qaqc.columns where Name = "arg" and Object_ID = Object_ID("QAQC_Tasks")) = 0 THEN ALTER TABLE QAQC_Tasks ADD arg INT DEFAULT(0);

But I get the error: Near "ALTER": Syntax error.

Any ideas?

Herrozerro
  • 1,601
  • 1
  • 22
  • 37
  • 2
    If you use C/C++ API, check the **[sqlite3_table_column_metadata()](http://www.sqlite.org/c3ref/table_column_metadata.html)** function. It returns SQLITE_OK if the column exists and SQLITE_ERROR if it doesn't. – Mar Jan 26 '18 at 08:21
  • See this answer also https://stackoverflow.com/a/39831952/676571 – clearpath May 25 '20 at 21:41

17 Answers17

67

You cannot use ALTER TABLE withcase.

You are looking for getting the column names for a table::-

PRAGMA table_info(table-name);

Check this tutorial on PRAGMA

This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 2
    can you do something like: PRAGMA table_info(QAQC_Tasks) WHERE name = "syncstatus"; ? – Herrozerro Sep 20 '13 at 15:26
  • 4
    It didn't work. "Near WHERE: 'Syntax Error'" I guess I meant to ask if something like that was possible. – Herrozerro Sep 20 '13 at 15:42
  • Well as per my knowledge you dont use where clause with PRAGMA as pragma returns one row for each column in the named table. – Rahul Tripathi Sep 20 '13 at 15:44
  • 3
    is there a way to use pragma? I just tried SELECT name FROM PRAGMA table_info(QAQC_Tasks) WHERE name = "BusinessUnit"; with no luck. – Herrozerro Sep 20 '13 at 15:45
  • 2
    @IulianOnofrei That methos returns you a `Cursor`. You can then check if `cursor.getColumnIndex("columnName") == -1` or not. – Joaquin Iurchuk Jan 14 '16 at 18:41
44

Althought this is an old question, I found at PRAGMA functions a simpler solution:

SELECT COUNT(*) AS CNTREC FROM pragma_table_info('tablename') WHERE name='column_name'

If the result is more than zero then the column exists. Simple and one line query

The trick is to use

pragma_table_info('tablename')

instead of

PRAGMA table_info(tablename)

Edit: Please note that, as reported in PRAGMA functions:

The table-valued functions for PRAGMA feature was added in SQLite version 3.16.0 (2017-01-02). Prior versions of SQLite cannot use this feature

Formentz
  • 1,083
  • 1
  • 14
  • 20
  • 2
    It should be mentioned that this feature is considered as experimental and is subject to change if there is need for it. Also the feature was added to version 3.16.0 (2017-01-02). – Smar Jul 03 '18 at 07:06
18
// This method will check if column exists in your table
public boolean isFieldExist(String tableName, String fieldName)
{
     boolean isExist = false;
     SQLiteDatabase db = this.getWritableDatabase();
     Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
    res.moveToFirst();
    do {
        String currentColumn = res.getString(1);
        if (currentColumn.equals(fieldName)) {
            isExist = true;
        }
    } while (res.moveToNext());
     return isExist;
}
Yury Lvov
  • 93
  • 1
  • 6
Pankaj Jangid
  • 283
  • 2
  • 7
  • 2
    not working exactly, needed to fix it, but the idea give me solution... thanks!! – andrey2ag Jan 27 '16 at 00:36
  • 1
    What language is this written in? – Thomas Apr 05 '16 at 17:58
  • 1
    @Thomas Java based on Android specific classes – MatPag Apr 15 '16 at 15:28
  • nice example. here is the iOS Objective-C translation using FMDatabaseQueue: ` FMDatabaseQueue *Zqueue = [FMDatabaseQueue databaseQueueWithPath:[AppConfiguration offlineDbPath]]; [Zqueue inDatabase:^(FMDatabase *db) { FMResultSet *res = [db executeQuery:@"PRAGMA table_info(my_table)”]; int colExistsIndex = [res columnIndexForName:@“my_col”]; if (colExistsIndex < 0) { // create column } }];` – eGanges Jun 29 '16 at 20:23
  • 1
    The question asks for a SQL query, not Java or C++ code. – Katie Jun 25 '19 at 20:17
  • Remember to close the cursor before returning the result. – jmart Apr 11 '21 at 16:44
  • Helped me because I was looking for an Android specific answer. However you're not closing the cursor which is bad and also when setting isExists = true, you might just return true altogether, otherwise you're iterating the rest of the table for nothing. – psydj1 Nov 29 '21 at 22:42
6

You did not specify a language, so assuming it's not pure sql, you can check for errors on column querying:

SELECT col FROM table;

if you get an error so you know the column is not there (assuming you know the table exists, anyway you have the "IF NOT EXISTS" for this), otherwise the column exists and then you can alter the table accordingly.

Niki Romagnoli
  • 1,406
  • 1
  • 21
  • 26
6

I have applied this solution:

public boolean isFieldExist(SQLiteDatabase db, String tableName, String fieldName)
    {
        boolean isExist = false;

        Cursor res = null;

        try {

            res = db.rawQuery("Select * from "+ tableName +" limit 1", null);

            int colIndex = res.getColumnIndex(fieldName);
            if (colIndex!=-1){
                isExist = true;
            }

        } catch (Exception e) {
        } finally {
            try { if (res !=null){ res.close(); } } catch (Exception e1) {}
        }

        return isExist;
    }

It is a variant of code by Pankaj Jangid.

Jason D
  • 8,023
  • 10
  • 33
  • 39
5

Use with a try, catch and finally for any rawQuery() executions for better practices. And the following code will give you the result.

public boolean isColumnExist(String tableName, String columnName)
{
    boolean isExist = false;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = null;
    try {
        cursor = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
        if (cursor.moveToFirst()) {
            do {
                String currentColumn = cursor.getString(cursor.getColumnIndex("name"));
                if (currentColumn.equals(columnName)) {
                    isExist = true;
                }
            } while (cursor.moveToNext());

        }
    }catch (Exception ex)
    {
        Log.e(TAG, "isColumnExist: "+ex.getMessage(),ex );
    }
    finally {
        if (cursor != null)
            cursor.close();
        db.close();
    }
    return isExist;
}
Guru raj
  • 806
  • 11
  • 10
5
SELECT EXISTS (SELECT * FROM sqlite_master WHERE tbl_name = 'TableName' AND sql LIKE '%ColumnName%');

..be aware of the LIKE condition which is imperfect, but it works for me as all my columns have very unique names..

Jaro B
  • 51
  • 1
  • 3
4

A weird way to check for existing column

public static bool SqliteColumnExists(this SQLiteCommand cmd, string table, string column)
{
    lock (cmd.Connection)
    {
        // make sure table exists
        cmd.CommandText = string.Format("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '{0}'", table);
        var reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            //does column exists?
            bool hascol = reader.GetString(0).Contains(String.Format("\"{0}\"", column));
            reader.Close();
            return hascol;
        }
        reader.Close();
        return false;
    }
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
3

To get column names for a table:

PRAGMA table_info (tableName);

To get indexed columns:

PRAGMA index_info (indexName);
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
3

I've used following SELECT statement with SQLite 3.13.0

SELECT INSTR(sql, '<column_name>') FROM sqlite_master WHERE type='table' AND name='<table_name>';

Returns 0 (zero) if column <column_name> does not exists in the table <table_name>.

JarTap
  • 31
  • 1
  • `INSTR(sql, '')`seems to do a substring match, so if your field is named `KEYDATA` searching for `YD` will match in SQLite 3.29.3. – U. Windl Mar 24 '23 at 09:29
2

I updated the function of a friend... tested and working now

    public boolean isFieldExist(String tableName, String fieldName)
{
    boolean isExist = false;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);


    if (res.moveToFirst()) {
        do {
            int value = res.getColumnIndex("name");
            if(value != -1 && res.getString(value).equals(fieldName))
            {
                isExist = true;
            }
            // Add book to books

        } while (res.moveToNext());
    }

    return isExist;
}
andrey2ag
  • 3,670
  • 1
  • 12
  • 12
2

Update the DATABASE_VERSION so onUpgrade function is called then if Column is already exists then nothing happen if not then it will add new column.

 private static class OpenHelper extends SQLiteOpenHelper {

OpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    if (!isColumnExists(db, "YourTableName", "YourColumnName")) {

        try {

            String sql = "ALTER TABLE " + "YourTableName" + " ADD COLUMN " + "YourColumnName" + "TEXT";
            db.execSQL(sql);

        } catch (Exception localException) {
            db.close();
        }

    }


}

}

 public static boolean isColumnExists(SQLiteDatabase sqliteDatabase,
                                     String tableName,
                                     String columnToFind) {
    Cursor cursor = null;

    try {
        cursor = sqliteDatabase.rawQuery(
                "PRAGMA table_info(" + tableName + ")",
                null
        );

        int nameColumnIndex = cursor.getColumnIndexOrThrow("name");

        while (cursor.moveToNext()) {
            String name = cursor.getString(nameColumnIndex);

            if (name.equals(columnToFind)) {
                return true;
            }
        }

        return false;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
jakir hussain
  • 316
  • 2
  • 18
1

Similar to IF in SQLite, CASE in SQLite is an expression. You can't use ALTER TABLE with it. See: http://www.sqlite.org/lang_expr.html

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
1

I am really sorry for posting it late. Posting in the intention of may be helpful in someone's case.

I tried fetching the column from the database. If it returns a row, it contains that column otherwise not...

-(BOOL)columnExists { 
 BOOL columnExists = NO;

//Retrieve the values of database
const char *dbpath = [[self DatabasePath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){

    NSString *querySQL = [NSString stringWithFormat:@"SELECT lol_10 FROM EmployeeInfo"];
    const char *query_stmt = [querySQL UTF8String];

    int rc = sqlite3_prepare_v2(database ,query_stmt , -1, &statement, NULL);
    if (rc  == SQLITE_OK){
        while (sqlite3_step(statement) == SQLITE_ROW){

            //Column exists
            columnExists = YES;
            break;

        }
        sqlite3_finalize(statement);

    }else{
        //Something went wrong.

    }
    sqlite3_close(database);
}

return columnExists; 
}
Abdul Yasin
  • 3,480
  • 1
  • 28
  • 42
0
  public static bool columExsist(string table, string column)
    {
        string dbPath = Path.Combine(Util.ApplicationDirectory, "LocalStorage.db");

        connection = new SqliteConnection("Data Source=" + dbPath);
        connection.Open();

        DataTable ColsTable = connection.GetSchema("Columns");

        connection.Close();

        var data = ColsTable.Select(string.Format("COLUMN_NAME='{1}' AND TABLE_NAME='{0}1'", table, column));

        return data.Length == 1;
    }
0

Some of these examples didn't worked for me. I'm trying to check whether my table already contains a column or not.

I'm using this snippet:

public boolean tableHasColumn(SQLiteDatabase db, String tableName, String columnName) {
    boolean isExist = false;
    Cursor cursor = db.rawQuery("PRAGMA table_info("+tableName+")",null);
    int cursorCount = cursor.getCount();
    for (int i = 1; i < cursorCount; i++ ) {
        cursor.moveToPosition(i);
        String storedSqlColumnName = cursor.getString(cursor.getColumnIndex("name"));
        if (columnName.equals(storedSqlColumnName)) {
            isExist = true;
        }
    }
    return isExist;
}

The examples above are querying the pragma table which is a metadata table and not the actual data, each column indicates the names, type and some other stuff about the table's columns. So the actual column names are within the rows.

Hope that this helps someone else.

4gus71n
  • 3,717
  • 3
  • 39
  • 66
0
SELECT INSTR(Lower(sql), " exceptionclass ") FROM sqlite_master WHERE type="table" AND Lower(name)="bugsgroup";
buddemat
  • 4,552
  • 14
  • 29
  • 49
  • Compare with https://stackoverflow.com/a/71576925/6607497; also your variant doesn't actually work. – U. Windl Mar 24 '23 at 09:34