SQL · Module 2 · Lesson 41 min read

CREATE TABLE & Primary Keys

Syntax

CSS
CREATE TABLE table_name (
  column_name  data_type  [constraints],
  ...
  [table-level constraints]
);

Primary key

  • Uniquely identifies every row; it can never be NULL or duplicated
  • Every table should have one
  • Usually an auto-generated surrogate key: id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY or id UUID DEFAULT gen_random_uuid() PRIMARY KEY

IDENTITY options

  • GENERATED ALWAYS AS IDENTITY – the database always creates the id; you can't insert your own by accident ✅
  • GENERATED BY DEFAULT AS IDENTITY – generated unless you provide a value (handy for imports)
  • SERIAL – the older PostgreSQL shortcut

Composite primary key

Two columns together are unique, e.g. a junction table: PRIMARY KEY (student_id, course_id)

DEFAULT values

Used when an INSERT doesn't provide the column: DEFAULT now(), DEFAULT 0, DEFAULT 'pending', DEFAULT gen_random_uuid()

Useful options

  • CREATE TABLE IF NOT EXISTS … – no error if it already exists
  • CREATE TABLE new_table AS SELECT … – create a table from a query result (copies data, not constraints)
  • CREATE TABLE copy (LIKE original INCLUDING ALL) – copy the structure

Naming conventions

  • snake_case, lowercase: savings_goals, due_date
  • Plural table names (users) or singular (user) — pick one style and stay consistent
  • Foreign keys as <thing>_id: user_id, category_id
  • Booleans as is_…/has_…; timestamps as …_at; dates as …_on/…_date
  • Avoid reserved words like order, user, group as names

Inspect a table

psql: \d savings_goals | SQL: query information_schema.columns

Example

SQL
CREATE TABLE IF NOT EXISTS savings_goals (
  id          INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id     INT NOT NULL REFERENCES users(id),
  title       TEXT NOT NULL,
  target      NUMERIC(10,2) NOT NULL,
  saved       NUMERIC(10,2) NOT NULL DEFAULT 0,
  deadline    DATE,
  is_achieved BOOLEAN NOT NULL DEFAULT false,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Only provide what's needed; defaults fill the rest
INSERT INTO savings_goals (user_id, title, target, deadline)
VALUES (1, 'Emergency fund', 100000, '2027-06-30'),
       (2, 'New laptop', 120000, NULL);

SELECT id, title, target, saved, is_achieved FROM savings_goals;
--  id |     title      |  target   | saved | is_achieved
--   1 | Emergency fund | 100000.00 |  0.00 | f
--   2 | New laptop     | 120000.00 |  0.00 | f

-- ❌ GENERATED ALWAYS blocks manual ids:
-- INSERT INTO savings_goals (id, user_id, title, target) VALUES (99, 1, 'x', 1);

-- Composite primary key (junction table)
CREATE TABLE expense_shares (
  expense_id BIGINT REFERENCES expenses(id),
  user_id    INT REFERENCES users(id),
  share      NUMERIC(10,2) NOT NULL,
  PRIMARY KEY (expense_id, user_id)
);

-- Create a table from a query
CREATE TABLE big_expenses AS
SELECT id, title, amount FROM expenses WHERE amount > 5000;
SELECT count(*) FROM big_expenses;   -- 4

-- Look at the columns of a table
SELECT column_name, data_type, column_default
FROM information_schema.columns
WHERE table_name = 'savings_goals'
ORDER BY ordinal_position;

DROP TABLE big_expenses, expense_shares, savings_goals;