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.
UNIQUE constraint on email
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 with DEFAULT constraint
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 using default value
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.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.