144

I am creating an SQLite database.

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, " 
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER);");

Is it possible to set the default value of KEY_NOTE (which is an integer) for every row created to be 0 (zero)? If so, what should be the correct code?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Born Again
  • 2,139
  • 4
  • 25
  • 27

3 Answers3

273

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

Karakuri
  • 38,365
  • 12
  • 84
  • 104
12

A column with default value:

CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)

<DefaultValue> is a placeholder for a:

  • value literal
  • ( expression )

Examples:

Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))
frogatto
  • 28,539
  • 11
  • 83
  • 129
5

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);
Nader Belal
  • 157
  • 3
  • 10
  • It's the same logic used in MySQL; the default of a nullable column is already NULL, so to set a default otherwise would imply the column is non-nullable. If you specify a default on a nullable column without declaring it NOT NULL, it may confuse you when default NULL values are inserted. – ChoNuff Dec 28 '17 at 21:02
  • 1
    The UNIQUE statement is not needed and already implied by the PRIMARY KEY statement. – dani Jun 03 '18 at 11:12
  • @dani I agree with you, but it was the only way to bypass the errors that SQLiteStudio 3.1.1 was generating from lacking of "Unique" condition – Nader Belal Jun 04 '18 at 12:04