Lecture

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 different
  • DEFAULT: 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.


Why It Matters

Constraints help prevent duplicate records (such as duplicate emails), automatically fill in missing values, and keep your data clean and reliable.

Quiz
0 / 2
1.

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

2.

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

Run
Generate

Tables

Execution Result