SQL constraints are used to enforce rules on the data stored in a database. Some common constraints are:
- NOT NULL: This constraint specifies that a column cannot contain a
NULL
value. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type NOT NULL, ... ); |
Example:
1 2 3 4 5 6 |
CREATE TABLE cars ( id INT NOT NULL, model VARCHAR(255) NOT NULL, ... ); |
- UNIQUE: This constraint specifies that the values in a column must be unique. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type UNIQUE, ... ); |
Example:
1 2 3 4 5 6 |
CREATE TABLE cars ( id INT NOT NULL UNIQUE, model VARCHAR(255) NOT NULL, ... ); |
- PRIMARY KEY: This constraint specifies that a column is a primary key. A primary key is a unique identifier for a row in a table. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type PRIMARY KEY, ... ); |
Example:
1 2 3 4 5 6 |
CREATE TABLE cars ( id INT NOT NULL PRIMARY KEY, model VARCHAR(255) NOT NULL, ... ); |
- FOREIGN KEY: This constraint specifies that a column references the primary key of another table. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type REFERENCES reference_table(reference_column), ... ); |
Example:
1 2 3 4 5 6 7 8 |
CREATE TABLE cars ( id INT NOT NULL PRIMARY KEY, model VARCHAR(255) NOT NULL, manufacturer_id INT NOT NULL, ..., FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id) ); |
- CHECK: This constraint specifies a condition that a column must meet. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type CHECK (condition), ... ); |
Example:
1 2 3 4 5 6 7 |
CREATE TABLE cars ( id INT NOT NULL, model VARCHAR(255) NOT NULL, price INT CHECK (price >= 0), ... ); |
- DEFAULT: This constraint specifies a default value for a column. Syntax:
1 2 3 4 5 |
CREATE TABLE table_name ( column_name data_type DEFAULT default_value, ... ); |
Example:
1 2 3 4 5 6 7 |
CREATE TABLE cars ( id INT NOT NULL, model VARCHAR(255) NOT NULL, price INT DEFAULT 0, ... ); |
- CREATE INDEX: This statement creates an index on a column or set of columns. An index is used to improve the performance of queries by allowing the database to quickly find the rows that match a query. Syntax:
1 |
CREATE INDEX index_name ON table_name (column_name); |
Example:
1 |
CREATE INDEX idx_cars_model ON cars (model); |