Modifying Tables in SQL using ALTER

Published: (March 28, 2026 at 01:34 PM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Making a Column NOT NULL

ALTER TABLE customers
ALTER COLUMN email SET NOT NULL;

Adding a Unique Constraint

ALTER TABLE users
ADD CONSTRAINT unique_username UNIQUE (username);

Adding a Check Constraint

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

Setting a Default Value

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

Adding a Column with Constraints

ALTER TABLE employees
ADD COLUMN salary DECIMAL(10,2) NOT NULL CHECK (salary > 10000);

Managing Foreign Keys with ON DELETE CASCADE

-- Remove the existing foreign key constraint
ALTER TABLE employees
DROP CONSTRAINT employees_department_id_fkey;

-- Add a new foreign key with cascade delete
ALTER TABLE employees
ADD CONSTRAINT employees_department_id_fkey
FOREIGN KEY (department_id)
REFERENCES departments(id)
ON DELETE CASCADE;

Dropping a Check Constraint

ALTER TABLE accounts
DROP CONSTRAINT accounts_balance_check;

Viewing Table Definition

\d accounts;

Adding a Composite Unique Constraint

ALTER TABLE payments
ADD CONSTRAINT unique_user_transaction
UNIQUE (user_id, transaction_id);
0 views
Back to Blog

Related posts

Read more »

CA 40 – Alter Tables

Make email NOT NULL in customers table sql ALTER TABLE customers ALTER COLUMN email SET NOT NULL; Ensures that future rows must have an email value. Make usern...

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...

Alter Queries

In this assignment, I worked on modifying existing tables using ALTER TABLE. This helped me understand how to update constraints without recreating tables. Task...

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...