Thuta Learning
SQL
AdvancedData & DatabasesBeginner

CREATE TABLE

SQLLesson 2125 min

What you'll walk away with

  • Choose a suitable type for each column from integer, numeric, text/varchar, boolean, date and timestamptz
  • Predict which data NOT NULL, DEFAULT and PRIMARY KEY will reject or fill in
  • Let the database generate IDs with GENERATED ALWAYS AS IDENTITY
  • Avoid traps such as quoted identifiers and storing money in float types

Explain it simply

Explain it simply

CREATE TABLE is like designing a blank form. For each box, a column, you decide its name, what kind of value goes in it (the data type), whether it must be filled (NOT NULL), and what to write when it is left empty (DEFAULT). Only after that do you fill forms in with INSERT.

A well-designed form makes the database itself reject bad data: no text in a date box, no saving a row without a name. Even when the application's own checks are skipped, the table stands as the last line of defense.

Problem → Why → Solution

The problem: careless types make data lie

The table below was created in a hurry: every column is text and nothing is NOT NULL. Problems soon appear. MAX(hired_on) claims '2024-9-30' is later than 2024-10-05, salaries cannot be summed, and rows for employees with no name at all slip in.

employees_bad.sql
CREATE TABLE employees_bad (
    id       text,
    name     text,
    salary   text,
    hired_on text
);
INSERT INTO employees_bad VALUES
  ('1', 'Aye', '1200', '2024-10-05'),
  ('2', NULL,  'n/a',  '2024-9-30');     -- no name, salary is not a number

SELECT MAX(hired_on) FROM employees_bad;  -- '2024-9-30' (text comparison)
SELECT SUM(salary)   FROM employees_bad;  -- ERROR: function sum(text) does not exist

Why do types matter so much?

A data type not only limits what may enter a column, it also decides how values compare and calculate. A date stored as text is compared character by character, so '9' beats '1'. Declared as hired_on date NOT NULL, the value '2024-9-30' is converted into a real date and compared chronologically, while non-dates such as 'n/a' and missing values are rejected. Constraints stop incomplete rows right at the door.

Core concept: every column is a promise

Inside CREATE TABLE table_name (...), columns are separated by commas and each is written as name, type, then constraints. Every column definition is a promise the database will keep: hired_on date NOT NULL promises "this column always holds a real date". Any INSERT or UPDATE that would break the promise is rejected with an error, and nothing from that statement is saved.

Common PostgreSQL types: integer for IDs and counts, or bigint if a table may grow past two billion rows; numeric(10, 2) for exact decimals such as money; text or varchar(n) for strings; boolean for true/false; date for calendar dates; timestamptz for exact moments in time. In PostgreSQL, text and varchar(n) perform the same, and varchar(n) only adds a length check. The varchar(255) habit comes from MySQL; 255 is not a special number in PostgreSQL, so add a limit only when a business rule calls for one.

NOT NULL rejects rows without a value. DEFAULT supplies a value when an INSERT leaves the column out, as in is_active boolean NOT NULL DEFAULT true. A PRIMARY KEY identifies each row: it guarantees NOT NULL and UNIQUE together and automatically creates an index. integer GENERATED ALWAYS AS IDENTITY makes the database hand out numbers 1, 2, 3; it is standard SQL and available since PostgreSQL 10. The serial shorthand seen in older tutorials is PostgreSQL's older way of doing the same thing. MySQL writes AUTO_INCREMENT and SQL Server writes IDENTITY(1,1).

One last rule: PostgreSQL folds unquoted identifiers to lowercase. CREATE TABLE Employees (EmployeeID int) really creates a table called employees with a column called employeeid, and writing Employees or EMPLOYEES later still works. That is why snake_case names such as employee_id are the convention in PostgreSQL.

Mental model: a gate in front of the table
  1. INSERT sends a row
  2. DEFAULT fills omitted columns
  3. Each value converts to its type
  4. NOT NULL and PRIMARY KEY check it
  5. Saved only if everything passes

If any step fails, the whole statement is rejected and the table stays unchanged.

General pattern

sql
CREATE TABLE table_name (
    id_column   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    column_one  data_type NOT NULL,
    column_two  data_type DEFAULT default_value,
    column_three data_type
);

Each column is written as name, type, constraints, separated by commas, with no comma after the last one. A column with no constraints accepts NULL.

Example: creating an employees table and trying it out

This builds an Employees table in PostgreSQL style: snake_case names, an identity column so the database generates IDs, numeric for money, and a boolean with a default. After creating the table, the script inserts two rows and reads them back. The first two output lines are the command tags psql prints after each statement.

create_employees.sql
CREATE TABLE employees (
    employee_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    first_name  varchar(100) NOT NULL,
    last_name   varchar(100) NOT NULL,
    city        text,
    salary      numeric(10, 2) NOT NULL,
    is_active   boolean NOT NULL DEFAULT true,
    hired_on    date NOT NULL
);

INSERT INTO employees (first_name, last_name, city, salary, hired_on)
VALUES ('Aye', 'Chan', 'Yangon', 1200.00, '2024-03-01'),
       ('Min', 'Thu', NULL, 950.50, '2024-06-15');

SELECT employee_id, first_name, city, salary, is_active, hired_on
FROM employees;

Code breakdown

  1. Line 2employee_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,

    The database generates 1, 2, ... and PRIMARY KEY forbids duplicates and NULL. Because of ALWAYS, supplying your own ID in an INSERT is an error.

  2. Lines 3-4first_name varchar(100) NOT NULL,

    A name is required, and anything longer than 100 characters is rejected with "value too long".

  3. Line 5city text,

    No constraint, so it is optional: Min's city is stored as NULL and shows as a blank in psql.

  4. Line 6salary numeric(10, 2) NOT NULL,

    Up to 10 digits with 2 after the decimal point. 1200.00 and 950.50 are stored exactly, with no float rounding error.

  5. Line 7is_active boolean NOT NULL DEFAULT true,

    The INSERT leaves is_active out, so DEFAULT true applies; psql displays a true boolean as t.

  6. Lines 11-13INSERT INTO employees (first_name, last_name, city, salary, hired_on)

    employee_id and is_active are missing from the column list: the database generates one and fills the other from its default.

You should see
CREATE TABLE
INSERT 0 2
 employee_id | first_name |  city  | salary  | is_active |  hired_on
-------------+------------+--------+---------+-----------+------------
           1 | Aye        | Yangon | 1200.00 | t         | 2024-03-01
           2 | Min        |        |  950.50 | t         | 2024-06-15
(2 rows)

Watching the constraints say no

Run any of the statements below against the example table and each one is rejected. Learning to read these messages tells you immediately which promise of which column was broken.

StatementPostgreSQL's answer
INSERT ... (first_name, salary, hired_on) VALUES ('X', 1, '2024-01-01')null value in column "last_name" ... violates not-null constraint
INSERT ... (employee_id, ...) VALUES (10, ...)cannot insert a non-DEFAULT value into column "employee_id"
101 characters in first_namevalue too long for type character varying(100)
'n/a' in hired_oninvalid input syntax for type date: "n/a"

With IF NOT EXISTS, an existing table produces a notice instead of an error and the statement is skipped, which lets setup scripts run repeatedly. It does not check that the existing table's columns match what you wrote, though; changing a table is ALTER TABLE's job. UNIQUE, CHECK and REFERENCES (foreign key) constraints get their own detailed treatment in the Constraints lesson.

if_not_exists.sql
CREATE TABLE IF NOT EXISTS tags (
    tag_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label  text NOT NULL
);
-- running it again only raises a notice: relation "tags" already exists
CREATE TABLE IF NOT EXISTS tags (
    tag_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label  text NOT NULL
);

In real projects

Where this shows up in real projects

In real projects nobody types CREATE TABLE by hand on the production database. It goes into migration files kept in Git, and tools such as Flyway, Liquibase, Prisma Migrate or Django migrations apply them in order to every environment: developer laptops, staging and production. Every schema change can then be code-reviewed, and there is a history of what changed and when.

Type choices are hard to undo later, so think them through early. For a table that may reach millions of rows, bigint IDs are safer than integer. Times stored as timestamptz stay correct for users in different time zones. Changing a column's type on a large table later can rewrite the whole table and hold a lock for a long time, which can mean production downtime.

Common mistakes

Common mistakes

1. Quoting mixed-case table names

CREATE TABLE "Employees" (...) with quotes stores the name with a capital E exactly. Later, SELECT * FROM Employees; looks for employees in lowercase and fails with "relation employees does not exist", so you must write "Employees" with quotes forever. Some GUI tools add the quotes for you, so watch out, and stick to lowercase snake_case.

2. Storing money in real or double precision

Floating-point types store decimals only approximately: SELECT 0.1::float8 + 0.2::float8; returns 0.30000000000000004. Summed over thousands of invoices, cents start to drift. Use numeric(p, s) for money and other exact quantities, where 0.1 + 0.2 is exactly 0.3.

3. Storing dates and numbers as text

As the problem section showed, dates stored as text sort character by character and happily accept junk such as 'n/a'. With proper types such as date, timestamptz, integer and numeric, the database validates input and you gain date arithmetic like hired_on + 30.

Mini challenge

Mini challenge: design a courses table

Create a courses table for an online learning site. Then insert two courses, one relying on the defaults and one giving its own values, and finally read the rows back.

  • course_id: an identity primary key generated by the database
  • title: required text; level: varchar(20) NOT NULL DEFAULT 'beginner'
  • price: numeric(8, 2) NOT NULL DEFAULT 0; published_on: an optional date
  • is_active: boolean NOT NULL DEFAULT true
courses.sql
CREATE TABLE courses (
    -- TODO: course_id (identity primary key)
    -- TODO: title (required)
    -- TODO: level (default 'beginner')
    -- TODO: price (exact money, default 0)
    -- TODO: published_on (optional date)
    -- TODO: is_active (default true)
);

-- TODO: insert 'SQL Basics' (published 2024-01-10) using the defaults
-- TODO: insert 'Advanced Joins', level 'advanced', price 49.99, not yet published

-- TODO: select every column ordered by course_id

Expected: Two rows: course_id | title | level | price | published_on | is_active -----------+----------------+----------+-------+--------------+----------- 1 | SQL Basics | beginner | 0.00 | 2024-01-10 | t 2 | Advanced Joins | advanced | 49.99 | | t (2 rows)

Show hint

Leave a column out of the INSERT's column list when you want its default. Omitting published_on stores NULL. The default 0 for price displays as 0.00 because the column is numeric(8, 2).

Show solution
courses.sql
CREATE TABLE courses (
    course_id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title        text NOT NULL,
    level        varchar(20) NOT NULL DEFAULT 'beginner',
    price        numeric(8, 2) NOT NULL DEFAULT 0,
    published_on date,
    is_active    boolean NOT NULL DEFAULT true
);

INSERT INTO courses (title, published_on)
VALUES ('SQL Basics', '2024-01-10');

INSERT INTO courses (title, level, price)
VALUES ('Advanced Joins', 'advanced', 49.99);

SELECT * FROM courses ORDER BY course_id;

Quick quiz 1 / 3

After CREATE TABLE Products (ProductID int);, which query fails?

Quick quiz 2 / 3

Which type stores a price column exactly?

Quick quiz 3 / 3

A table has id integer GENERATED ALWAYS AS IDENTITY. What happens with INSERT INTO t (id, name) VALUES (5, 'x');?

What to remember

  • Each column is name, type and constraints: a promise the database enforces.
  • Use numeric for money, date/timestamptz for time and text or varchar(n) for strings; do not store everything as text.
  • NOT NULL rejects missing values, DEFAULT fills omitted columns, and PRIMARY KEY identifies each row.
  • Use GENERATED ALWAYS AS IDENTITY for IDs and unquoted snake_case names everywhere.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

CREATE TABLE | Thuta Learning