DEV Community

Santhosh V
Santhosh V

Posted on

CA 40 - Alter Tables

Today I practiced ALTER TABLE in SQL.
This is used when we want to change an existing table.

1. Make Email NOT NULL (customers)

ALTER TABLE customers
MODIFY email VARCHAR(100) NOT NULL;
Enter fullscreen mode Exit fullscreen mode

Now email is required

2. Make Username UNIQUE (users)

ALTER TABLE users
ADD CONSTRAINT unique_username UNIQUE (username);
Enter fullscreen mode Exit fullscreen mode

No duplicate usernames

3. Add CHECK on Price (products)

ALTER TABLE products
ADD CONSTRAINT check_price CHECK (price > 0);
Enter fullscreen mode Exit fullscreen mode

price must be > 0

4. Default Status (orders)

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

Enter fullscreen mode Exit fullscreen mode

if not given → pending

5. Add Salary Column (employees)

ALTER TABLE employees
ADD salary INT NOT NULL CHECK (salary > 10000);
Enter fullscreen mode Exit fullscreen mode

salary required + > 10000

6. Auto Delete Employees (FK)

ALTER TABLE employees
DROP CONSTRAINT employees_department_id_fkey;
Enter fullscreen mode Exit fullscreen mode
ALTER TABLE employees
ADD CONSTRAINT employees_department_id_fkey
FOREIGN KEY (department_id)
REFERENCES departments(id)
ON DELETE CASCADE;

Enter fullscreen mode Exit fullscreen mode

delete department → employees also deleted

7. Remove CHECK (accounts)

ALTER TABLE accounts
DROP CONSTRAINT check_balance;
Enter fullscreen mode Exit fullscreen mode

removed balance rule

8. Unique Combination (payments)

ALTER TABLE payments
ADD CONSTRAINT unique_payment UNIQUE (user_id, transaction_id);
Enter fullscreen mode Exit fullscreen mode

same pair not allowed twice

Final Thought

ALTER TABLE = update your table rules
Very useful in real projects

Top comments (0)