Unique and Default Constraints
SQL allows you to define constraints on your columns to enforce rules. Two common constraints are:
UNIQUE
: ensures all values in a column are differentDEFAULT
: provides an automatic value if none is specified
UNIQUE Constraint
The UNIQUE
constraint ensures no two rows in a column have the same value.
CREATE TABLE clients ( id INT PRIMARY KEY, email TEXT UNIQUE, name TEXT, status TEXT DEFAULT 'active' );
In this table, the email
column is UNIQUE
, meaning only one client can use alex@example.com
.
DEFAULT Constraint
The DEFAULT
constraint sets a value automatically when none is given.
CREATE TABLE clients ( id INT PRIMARY KEY, email TEXT UNIQUE, name TEXT, status TEXT DEFAULT 'active' );
Here, status
will default to 'active'
unless you provide something else.
INSERT INTO Example
The query below inserts a new client named Laura Adams.
INSERT INTO clients (id, email, name) VALUES (6, 'laura.adams@newdomain.com', 'Laura Adams');
If you don't specify a status
, the default value 'active'
will be used.
Why It Matters
Constraints help prevent duplicate records (such as duplicate emails), automatically fill in missing values, and keep your data clean and reliable.
What does the UNIQUE
constraint do in SQL?
Automatically fills in missing values
Allows NULLs in all rows
Ensures each value in the column is different
Hides duplicate rows from output
What does the DEFAULT
constraint do in SQL?
Prevents values from being NULL
Rejects any missing values
Fills in a predefined value if no input is given
Sorts data by default order
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Tables
Execution Result