Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add default value in SQLite?

I had a table modified to add status column to it in this fashion

ALTER TABLE ITEM ADD COLUMN STATUS VARCHAR DEFAULT 'N'; 

However SQLite doesnt seem to add N to the column for any new ITEM created. Is the syntax wrong or is there any issue with SQLite and its support for defaults.

I am using SQLite 3.6.22

like image 421
Azlam Avatar asked Feb 12 '10 19:02

Azlam


People also ask

How do I add a default value?

Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

How do you set a PRIMARY KEY in SQLite?

Syntax. The syntax to add a primary key to a table in SQLite is: PRAGMA foreign_keys=off; BEGIN TRANSACTION; ALTER TABLE table_name RENAME TO old_table; CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL | NOT NULL ], ... CONSTRAINT constraint_name PRIMARY KEY (pk_col1, pk_col2, ...

What is a default value example?

For instance, if a bank's interest rate for the current financial year is 8 percent, this may be set as the default value. This relieves the user from having to enter it repeatedly into the database.

Which is a default value?

Returns a default value when the specified value is null or empty. When there are multiple default parameters, each parameter is evaluated in order and the first non-null and non-empty default will be returned. Null , "" , and {} are all considered null or empty values.


1 Answers

Looks good to me. Here are the Docs.

sqlite> create table t1 (id INTEGER PRIMARY KEY, name TEXT, created DATE); sqlite> .table t1 sqlite> .dump PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE t1 (id INTEGER PRIMARY KEY, name TEXT, created DATE); COMMIT;  sqlite> alter table t1 add column status varchar default 'N'; sqlite> .dump PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE t1 (id INTEGER PRIMARY KEY, name TEXT, created DATE, status varchar default 'N'); COMMIT;  sqlite> insert into t1 (name) values ("test"); sqlite> select * from t1; 1|test||N 

Dump your schema and verify that your table structure is there after calling ALTER TABLE but before the INSERT. If it's in a transaction, make sure to COMMIT the transaction before the insert.

$ sqlite3 test.db ".dump" 
like image 165
databyte Avatar answered Sep 21 '22 15:09

databyte