Skip to content
Back to 50 Concepts
Topic 4 of 50foundationsBeginner

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

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

CREATE Statements Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for CREATE Statements
SQL Input

Initiating CREATE Statements

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Architect Blueprint: Drawing the boundaries, room sizes, and specifications before construction begins.

4. Real-World Example

Creating an audit logging table with timestamp defaults, identity columns, and JSON payloads.

audit_logs schema
ColumnTypeConstraint / Default
idBIGINTGENERATED ALWAYS AS IDENTITY (PK)
actionVARCHAR(50)NOT NULL
payloadJSONBNOT NULL DEFAULT '{}'
created_atTIMESTAMPTZNOT NULL DEFAULT NOW()
Relational walkthrough: The table guarantees that every log entry receives a strictly incrementing ID and a UTC timestamp.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Create table with identity and defaults
CREATE 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
);
GENERATED ALWAYS AS IDENTITY is the standard ANSI replacement for legacy SERIAL.
Step 2: Create Table with IF NOT EXISTS
CREATE TABLE IF NOT EXISTS system_settings (
  key VARCHAR(100) PRIMARY KEY,
  value TEXT NOT NULL
);
Prevents runtime deployment errors if the table is already present.

6. Important Rules & Behaviors

RuleBehavioral Explanation
IF NOT EXISTSPrevents SQL execution errors if an entity with the specified name already exists.
Identity vs SerialGENERATED ALWAYS AS IDENTITY conforms to SQL:2003 standards and prevents accidental manual ID overrides.
Storage limitsTables cannot exceed physical engine limits (e.g., 1600 columns in PostgreSQL).
Column default evaluation timeDefault expressions like CURRENT_TIMESTAMP or gen_random_uuid() are evaluated at row insert time, not at schema creation time.
Unlogged table persistenceUNLOGGED 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
);
Caution: Stored generated columns consume disk space but can be indexed directly with B-Trees for fast lookups.

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

Scenario Question:

Which clause prevents a migration script from crashing if a table is already present?

Select your answer: