SQLite Default Constraint

Here we will learn SQLite Default Constraint with example and how to use SQLite Default Constraint to insert default values in a column in case if no value is specified.

SQLite Default Constraint

In SQLite, Default Constraint is used to define default values for a column. Generally, in SQLite default constraint will insert default value in a column in case if column value null or empty.

 

We can add default constraint on the column while creating a new table using Create Statement or modifying / altering table using ALTER statement.

Syntax of SQLite Default Constraint

Following is the syntax of adding default constraint on column using Create Statement.

 

CREATE TABLE tablename

(colum1 INTEGER PRIMARY KEY,

column2 TEXT NOT NULL,

column3 INTEGER DEFAULT defaultvalue);

If you observe the above syntax we defined a sample table with multiple columns and column3 is having Default property. Now we will see how to use SQLite Default Constraint with example.

Example of SQLite Default Constraint

Following is the example of using SQLite Default Constraint with Create Statement to define default constraint on column.

 

CREATE TABLE BOOK

(Book_id INTEGER PRIMARY KEY,

Book_name TEXT NOT NULL,

Price INTEGER DEFAULT 100);

In the above SQLite Default Constraint example, we created a table called BOOK with column Price as DEFAULT value 100. In case if we didn’t specify value for the Price column while inserting or updating the BOOK table automatically it will take 100 as default value.

 

sqlite> INSERT INTO BOOK (Book_id,Book_name) VALUES(1,'RAMAYANA');

 

sqlite> SELECT FROM BOOK;

 

Book_id     Book_name   Price

----------  ----------  ----------

1           RAMAYANA    100

This is how we can use SQLite Default Constraint on table columns based on our requirements.