CA 40 – Alter Tables

Published: (March 29, 2026 at 09:37 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Make email NOT NULL in customers table

ALTER TABLE customers
ALTER COLUMN email SET NOT NULL;

Ensures that future rows must have an email value.

Make username unique in users table

ALTER TABLE users
ADD CONSTRAINT unique_username UNIQUE (username);

Prevents duplicate usernames.

Add check constraint price > 0 in products table

ALTER TABLE products
ADD CONSTRAINT price_check CHECK (price > 0);

Now the price cannot be zero or negative.

Set default status to 'pending' in orders table

ALTER TABLE orders
ALTER COLUMN status SET DEFAULT 'pending';

If status is not provided, it will automatically be set to 'pending'.

Add salary column in employees table with conditions

ALTER TABLE employees
ADD COLUMN salary INT NOT NULL;

ALTER TABLE employees
ADD CONSTRAINT salary_check CHECK (salary > 10000);

salary cannot be null and must be greater than 10,000.

Modify foreign key so deleting a department deletes its employees

ALTER TABLE employees
DROP CONSTRAINT employees_department_id_fkey;

ALTER TABLE employees
ADD CONSTRAINT employees_department_id_fkey
FOREIGN KEY (department_id)
REFERENCES departments(id)
ON DELETE CASCADE;

Now deleting a department automatically deletes its associated employees.

Remove check constraint balance >= 0 from accounts table

ALTER TABLE accounts
DROP CONSTRAINT accounts_balance_check;

Removes the check constraint on the balance column.

Make combination of user_id and transaction_id unique in payments table

ALTER TABLE payments
ADD CONSTRAINT unique_payment UNIQUE (user_id, transaction_id);

Prevents duplicate transactions for the same user.

From this exercise I learned that ALTER TABLE is used to modify a table’s structure without deleting the table, which is very useful when the database already contains data.

0 views
Back to Blog

Related posts

Read more »

Alter Tables

1. Make the email column NOT NULL in customers sql ALTER TABLE customers ALTER COLUMN email SET NOT NULL; 2. Ensure username is unique in users sql ALTER TABLE...

Modifying Tables in SQL using ALTER

Making a Column NOT NULL sql ALTER TABLE customers ALTER COLUMN email SET NOT NULL; Adding a Unique Constraint sql ALTER TABLE users ADD CONSTRAINT unique_user...

CA 40 - Alter Tables

Practice ALTER TABLE Statements 1. Make Email NOT NULL customers sql ALTER TABLE customers MODIFY email VARCHAR100 NOT NULL; Result: email becomes a required f...

ALTER TABLE

Making email compulsory in the customers table Suppose we already have a table called customers, and its email column currently allows NULL values. We now want...