How to set a default value to a TEXT column in Sqlite?

26,350

Solution 1

You can specify a default value for the column when you create the table. (It doesn't appear as though you can add a default using an ALTER statement, so you'll have to recreate your table.)

CREATE TABLE your_table_name
(MainContactName TEXT NOT NULL DEFAULT '')

For Example,

CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT,book TEXT DEFAULT "abc");

now see that , default value is set to "abc"

Check sqllite documentation.

Solution 2

To alter table,

sqlitedbInstance.execSQL("alter table myTable add column Address TEXT DEFAULT 'ABC' ");
Share:
26,350
Abir Hasan Shawon
Author by

Abir Hasan Shawon

Updated on April 10, 2020

Comments

  • Abir Hasan Shawon
    Abir Hasan Shawon about 4 years

    I have a simple table. I'm trying to put a default value to a TEXT column. Here is the table query:

    "CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT '0', book_name TEXT NOT NULL);"   
    

    It creates the table but the problem occurs when i try to insert a data. I was only trying with giving a book name to book_name, as i expected that the book_id would have a default value 0 to the column. But it doesn't and it adds the null value, so the row doesn't get inserted. I have also tried with this query:

    "CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT \'0\', book_name TEXT NOT NULL);"     
    

    But the problem remains the same. I have searched the stack overflow, and got some answers but they are old and not working for me right now. So has something changed on how to set the default value to a TEXT column in sqlite. Thanks in advance :)

    EDIT
    Here is the insert statement:

    database.insert("book", null, cv);    
    

    Here cv is the object of ContentValues which contains only the value for the column book_name.

  • Abir Hasan Shawon
    Abir Hasan Shawon over 8 years
    If i create the column without NOT NULL then it doesn't take the empty string as default or the 'abc' as you given. it takes null. I have seen most of the previous answers but none of them are working.
  • Amit Vaghela
    Amit Vaghela over 8 years
    you want to set column value to 'something' right by default ? right ? then this works @AbirHasan
  • Amit Vaghela
    Amit Vaghela over 8 years
    CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT,book TEXT DEFAULT "abc"); i have tried this solution and it is working @AbirHasan