# Topic 4: CREATE Statements
CREATE DATABASE, CREATE SCHEMA, CREATE TABLE, generated columns, column types, and schema options.
1. Definition
The CREATE statement is a DDL command used to instantiate new databases, schemas, tables, indexes, and views within the RDBMS catalog.
2. Explain Like I'm 5
CREATE is like drafting an empty blueprint for a new house or building. You define the room sizes, door names, and rules before anyone moves in.
3. Animation & Visual Simulation
Interactive Engine TraceCREATE Statements Visual Simulator
CREATE TABLE IF NOT EXISTS products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku VARCHAR(30) UNIQUE NOT NULL,
price_cents INT CHECK (price_cents >= 0)
);Active InputStep 1: Input & Parsing Stage
Initiating CREATE Statements
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Creating an audit logging table with timestamp defaults, identity columns, and JSON payloads.
| Column | Type | Constraint / Default |
|---|---|---|
| id | BIGINT | GENERATED ALWAYS AS IDENTITY (PK) |
| action | VARCHAR(50) | NOT NULL |
| payload | JSONB | NOT NULL DEFAULT '{}' |
| created_at | TIMESTAMPTZ | NOT NULL DEFAULT NOW() |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE TABLE audit_logs (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
action VARCHAR(50) NOT NULL,
user_id INT REFERENCES users(id),
payload JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);CREATE TABLE IF NOT EXISTS system_settings ( key VARCHAR(100) PRIMARY KEY, value TEXT NOT NULL );
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| IF NOT EXISTS | Prevents SQL execution errors if an entity with the specified name already exists. |
| Identity vs Serial | GENERATED ALWAYS AS IDENTITY conforms to SQL:2003 standards and prevents accidental manual ID overrides. |
| Storage limits | Tables cannot exceed physical engine limits (e.g., 1600 columns in PostgreSQL). |
| Column default evaluation time | Default expressions like CURRENT_TIMESTAMP or gen_random_uuid() are evaluated at row insert time, not at schema creation time. |
| Unlogged table persistence | UNLOGGED tables bypass WAL logging, increasing write speed by 3x at the cost of being truncated on an engine crash. |
7. Deep Dive: Generated (Computed) Columns
Modern SQL allows generated columns that automatically calculate their value from other columns, either stored on disk or virtual.
CREATE TABLE invoices ( id INT PRIMARY KEY, subtotal NUMERIC(10, 2) NOT NULL, tax_rate NUMERIC(4, 2) NOT NULL DEFAULT 0.08, total NUMERIC(10, 2) GENERATED ALWAYS AS (subtotal * (1 + tax_rate)) STORED );
8. Advantages & Disadvantages
Advantages
- •Guarantees data shape and schema constraints upfront.
- •Supports identity sequencing without race conditions.
- •Enables database engine optimizations based on known data widths.
Disadvantages & Trade-offs
- •Schema alterations on massive tables require table locks or background migrations.
9. Common Interview Questions
Q1.What is the physical storage difference between CHAR(n), VARCHAR(n), and TEXT in PostgreSQL?
In PostgreSQL, CHAR(n), VARCHAR(n), and TEXT all use the exact same underlying varlena structure on disk (a 1 or 4-byte length header followed by the string bytes). CHAR(n) is padded with trailing spaces up to length n, wasting disk space. VARCHAR(n) adds a length check constraint. TEXT has no arbitrary length limit. Under the hood, performance between VARCHAR and TEXT is identical.
Q2.What are Generated Columns (STORED vs VIRTUAL) and when should you use them?
A generated column computes its value from other columns. VIRTUAL generated columns are calculated on-the-fly when read, consuming zero disk space but adding CPU cost. STORED generated columns are calculated during INSERT/UPDATE and persisted on disk, allowing direct B-Tree indexing for ultra-fast point lookups.
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
price NUMERIC(10,2),
tax_rate NUMERIC(4,2),
total NUMERIC(10,2) GENERATED ALWAYS AS (price * (1 + tax_rate)) STORED
);
CREATE INDEX idx_orders_total ON orders(total);Q3.How does CREATE TABLE AS SELECT (CTAS) differ from standard CREATE TABLE followed by INSERT?
CTAS copies column names and data types from the source query and populates the table in a single operation. However, CTAS does NOT copy primary keys, foreign keys, unique constraints, check constraints, default expressions, or indexes from the source table. All indexes and constraints must be added manually afterwards.
Q4.What are UNLOGGED tables and when should you use them in production?
UNLOGGED tables (PostgreSQL) do not write changes to the Write-Ahead Log (WAL). Writes are dramatically faster (up to 3x) and do not cause WAL replication traffic. However, they are NOT crash-safe: if the database server crashes or loses power, all unlogged tables are automatically truncated upon recovery. They are ideal for cache tables, session stores, or transient ETL staging.
Q5.What is schema qualification and how does the search_path setting affect security?
When a query references "users", the database searches schemas in the order defined by search_path (e.g. "$user", public). If an attacker creates a malicious function or table in a schema that appears earlier in the search_path, applications executing unqualified queries can execute unintended code (SQL Trojan injection). Production queries should always explicitly schema-qualify tables (e.g. public.users).
10. Interview-Ready Answer
“The CREATE TABLE statement instantiates relational entities with typed columns, constraints, and identity defaults. Standard practice uses ANSI identity columns and appropriate storage types to optimize slotted page density.”
11. Quick Test
Which clause prevents a migration script from crashing if a table is already present?