SQL Constraints
SQL constraints are rules that you can apply to your database tables to ensure data integrity and accuracy. They enforce restrictions on the data that can be stored, preventing invalid or inconsistent information.
Creating Constraints
Adding Constraints During Table Creation
Constraints are most commonly defined when you create a table using the CREATE TABLE
statement. This is the most efficient approach.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
);
Output
This creates a table named 'table_name' with specified columns, data types, and constraints. Each column can have its own constraints.
Adding Constraints After Table Creation
You can also add constraints to an existing table using the ALTER TABLE
statement.
(Specific syntax for adding constraints after creation will depend on the constraint type and the database system being used. Refer to the documentation for your specific database for detailed instructions.)
Types of SQL Constraints
Several types of constraints help maintain data quality:
Constraint | Description |
---|---|
NOT NULL |
Prevents NULL values in a column. |
UNIQUE |
Ensures all values in a column are unique. |
PRIMARY KEY |
Uniquely identifies each row in a table (combines NOT NULL and UNIQUE ). |
FOREIGN KEY |
Creates a link between tables, maintaining referential integrity. |
CHECK |
Enforces a condition on the values in a column. |
DEFAULT |
Specifies a default value for a column if no value is provided during insertion. |
CREATE INDEX |
Creates an index to speed up data retrieval. (While not strictly a constraint in the same sense as the others, it impacts data handling.) |
The use of constraints helps guarantee data accuracy and consistency within your database.