Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 7/ 160
01. SQL Foundations & Relational Concepts

Creating & Dropping Databases and Tables (CREATE, DROP, ALTER)

Create, alter, and drop databases and tables without locking yourself into bad schemas.

BeginnerCREATE TABLE · ALTER TABLE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

CREATE makes a table, ALTER changes it, DROP deletes it. Some changes are instant, and some make the database rewrite everything.

Think of it like…

Renovating a shop: adding a new shelf (ADD COLUMN) is quick; changing every price tag's format (ALTER TYPE) means touching every item while the shop stays shut; demolishing a section (DROP TABLE) can't be undone.

Where you’ve seen it

Adding a source text DEFAULT 'web' column to a 200-million-row orders table is instant in PostgreSQL 11+ because the default is stored once in the catalogue. Changing amount from integer to numeric rewrites the whole table under an exclusive lock, so it's scheduled carefully or done in stages.

Words you’ll hear

CREATE TABLE
Defines columns, types, defaults and constraints.
ALTER TABLE
Changes an existing table's structure.
Table rewrite
Some ALTERs copy every row into a new file, holding a strong lock.
Migration
A versioned, reviewed script that changes the schema.

Visual diagram

Loading interactive diagram

Theory & example queries

Creating and dropping

A CREATE TABLE statement lists each column with its type, nullability and default, plus primary key, unique, check and foreign key constraints. CREATE TABLE IF NOT EXISTS doesn't fail if the table already exists, which suits setup scripts but can hide the fact that an older, different table is already there.

DROP TABLE deletes the table, its data, indexes and constraints. DROP TABLE … CASCADE also drops dependent objects such as views and foreign keys from other tables, so check what depends on a table first. There's no undo except restoring from backup.

A complete table definitionQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE IF NOT EXISTS orders (2  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3  customer_id bigint NOT NULL REFERENCES customers (id),4  amount numeric(12, 2) NOT NULL CHECK (amount >= 0),5  status text NOT NULL DEFAULT 'pending',6  created_at timestamptz NOT NULL DEFAULT now()7);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE TABLE

Note: Representative PostgreSQL status; if orders already exists, IF NOT EXISTS may return a notice instead.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Define types and constraints up front; treat DROP as permanent.

Altering live tables safely

Every ALTER TABLE takes a lock that blocks other access to the table for at least an instant. If it has to wait behind a long-running query, every new query queues behind the ALTER, which can stall the app. SET lock_timeout = '5s' makes it fail fast so you can retry later.

Cheap in PostgreSQL 11+: adding a column with no default or a constant default, renaming, and dropping a column (the data is just hidden). Expensive: changing a column's type (usually a full rewrite), adding NOT NULL or a CHECK (a full scan; add CHECK … NOT VALID and validate later), and adding a column with a volatile default such as random(). MySQL 8.0 supports INSTANT for many ADD COLUMN cases. For risky changes, use expand-and-contract: add the new column, backfill in batches, switch the app over, then drop the old one.

Changing a type without a long lock

Add amount_new numeric(12,2), backfill it in batches of 10,000 rows, deploy code that writes both columns and reads the new one, then drop amount and rename amount_new.

Key takeaway: Know which ALTERs rewrite the table; use lock_timeout and expand-and-contract.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Process

Write the change as a migration

Put every schema change in a versioned migration file, reviewed like code, instead of running it by hand.

Focus at this step

migrations/2026_11_19_add_source_to_orders.sql

What to watch at this step
Source of truth
the repo
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

CREATE TABLE defines a table's columns, types and constraints. ALTER TABLE changes an existing table: add, drop or rename columns, change types, add constraints. DROP TABLE removes it entirely. IF NOT EXISTS and IF EXISTS make scripts safe to re-run, and in production these changes usually run as versioned migrations.

Why it matters: Schemas change constantly as products evolve, and a careless ALTER on a busy table can lock it for minutes or rewrite gigabytes of data. Knowing which changes are instant and which are dangerous is what separates a safe migration from an outage.

When to reach for it

  • Creating tables with full constraints from the start
  • Adding columns as features evolve
  • Planning risky changes on large tables

When to avoid or be careful

  • Running ALTERs by hand in production
  • Changing column types on large, busy tables in one step
  • DROP TABLE … CASCADE without checking dependencies

Ways to change a production schema

Direct ALTER
Best for: Metadata-only changes and small tables

Strengths: One statement, done.

Watch out: Rewrites or scans can lock big tables for a long time.

Expand and contract
Best for: Type changes, renames used by running code, big tables

Strengths: No long locks; can be rolled back at each step.

Watch out: Several deploys and a backfill job.

Online schema change tools (pg_repack, gh-ost, pt-osc)
Best for: Rewrites of very large MySQL or PostgreSQL tables

Strengths: Copy the table in the background with only brief locks.

Watch out: Extra tooling, disk space and operational care.

Interview signals & numbers to know

When this topic comes up

  • “How would you add a column to a huge table?”
  • “Our migration locked the table”
  • Schema migrations
  • Zero-downtime deploys
  • CREATE / ALTER / DROP

Benchmarks & rules of thumb

PostgreSQL 11 -
instant ADD COLUMN with a constant default
MySQL 8.0 -
INSTANT ADD COLUMN for many cases
0 -
undo for DROP TABLE without a backup

Common mistakes & follow-ups

Common interview mistakes

  • Running ALTER TABLE while a long report holds a lock, so every request queues behind the migration.
  • Changing a column type on a large table during peak traffic.
  • Using CREATE TABLE IF NOT EXISTS and not noticing an old table with different columns already existed.

Likely interviewer follow-ups

  • Which ALTER TABLE operations rewrite the whole table in PostgreSQL?
  • How would you rename a column without breaking the running application?
  • What does lock_timeout protect you from during migrations?
Interview tip: Whenever schema changes come up, mention table size, locks and expand-and-contract. That shows you think about production, not just syntax.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Creating & Dropping Databases and Tables (CREATE, DROP, ALTER) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Core Data Types (Numeric, String/Text, Boolean, Date/Time, UUID)
Next topic
Primary Keys & Auto-Increment / Serial / Identity Columns