Y23 Week3 (Constraints)
Y23 Week3 (Constraints)
• SQL constraints are used to specify rules for the data in a table.
• Constraints are used to limit the type of data that can go into a
table.
-- Ensures the accuracy and reliability of the data in the
table.
• If there is any violation between the constraint and the data
action, the action is aborted.
• Constraints can be column level or table level.
• Constrains can be named or unnamed
• Column level constraints apply to a column, and table level
constraints apply to the whole table.
The following constraints are commonly used in SQL:
1. NOT NULL - Ensures that a column cannot have a NULL value
2. UNIQUE - Ensures that all values in a column are different
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
4. FOREIGN KEY - Uniquely identifies a row/record in another
table
5. CHECK - Ensures that all values in a column satisfies a
specific condition
6. DEFAULT - Sets a default value for a column when no value is
specified
Not Null
1. By default, a column can hold NULL values.
2. The NOT NULL constraint enforces a column
to NOT accept NULL values.
3. This enforces a field to always contain a
value, which means that you cannot insert a
new record, or update a record without
adding a value to this field.
UniQue
1.The UNIQUE constraint ensures that all values in a column are different.
2. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
3. A PRIMARY KEY constraint automatically has a UNIQUE(and not null) constraint.
4. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.