Professional Documents
Culture Documents
Constraints: NOT NULL Constraint
Constraints: NOT NULL Constraint
Constraints: NOT NULL Constraint
Constraints
Constraints are placed on columns. They limit the data, that can be inserted into tables.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
The first SELECT statement is executed OK, the second one fails. The SQL error says, the LastName
The UNIQUE constraint ensures, that all data are unique in a column.
Here we create a table Brands. The BrandName column is set to be UNIQUE. There cannot be two
We get an SQL error 'column BrandName is not unique'. There can only be one Pepsi.
Note that a PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Primary key
The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more
UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the
database tables. Primary keys are unique ids. We use them to refer to table rows. Primary keys become
foreign keys in other tables, when creating relations among tables. Due to to a 'long-standing coding
oversight', primary keys can be NULL in SQLite. This is not the case with other databases.
Id BrandName
---------- ----------
1 Coca Cola
2 Pepsi
3 Sun
4 Oracle
Foreign key
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. It is a referential constraint
between two tables. The foreign key identifies a column or a set of columns in one (referencing) table
CREATE TABLE Books(BookId integer PRIMARY KEY, title text, AuthorId integer,
We create the Books table. Here we have an AuthorId column name, which acts as a foreign key. It
In SQLite, foreign keys are not enforced by default. To enforce the foreign key, the library must be
compiled with proper flags, it must be at least version 3.6.19 and the pragma key for foreign keys must
be set.
What would foreign key enforcement mean in our example? We could not insert a row into the Books
Check constraint
A CHECK constraint is a condition that defines valid data of a relational database. The check is
Customer text);
We look at the definition of the Orders table. We see a CHECK constraint imposed on the OrderPrice
Default constraint
The DEFAULT constraint inserts a default value into the column, if no value is available.
To demonstrate the DEFAULT constraint, we create a Hotels table. The City column has a default 'not
available' value.
Id Name City
1 Kyjev Bratislava
In the first statement, we provide both hotel name and city name. In the second statement, we provide
only the hotel name. SQLite puts the default value there, the 'not available' text.
In this part of the SQLite tutorial, we have worked with views, triggers and transactions in SQLite.