← 返回课程: SQL and databases from scratch

CREATE TABLE and data types

视频即将上线

Until now you have read data with SELECT. From this week on you cross to the other side: you design and modify the database. SQL is divided into groups of statements. DDL (data definition language) creates and changes the structure: CREATE, ALTER, DROP. DML (data manipulation) changes the data: INSERT, UPDATE, DELETE. DQL is querying, the SELECT you already master. Today we start with DDL: creating tables and choosing the right type for each column.

Choosing the data type

The type defines which values the column accepts, how much space it takes and which operations it allows. A good type is the first line of defense against wrong data. These are the most used in PostgreSQL; almost all exist with the same name in other engines.

  • SMALLINT, INTEGER, BIGINT: integers of different size.
  • NUMERIC(p, s): exact decimal with p digits and s decimals; ideal for money.
  • REAL, DOUBLE PRECISION: approximate decimals (scientific calculations, never money).
  • TEXT, VARCHAR(n): text; in PostgreSQL TEXT has no limit and performs the same as VARCHAR.
  • BOOLEAN: true or false.
  • DATE, TIMESTAMP, TIMESTAMPTZ: date, date with time and date with time and time zone.
  • UUID, JSONB: universal identifiers and queryable JSON documents.

A golden rule: money is always stored in NUMERIC, never in REAL or DOUBLE. Floating-point types do not represent many decimals exactly (0.1 + 0.2 does not give exactly 0.3) and cents accumulate badly. Another rule: a date is stored in a date-type column, not in text; that way you can sort, subtract and filter by ranges correctly. And if you record precise moments (when a review was written), prefer TIMESTAMPTZ to avoid surprises with time zones.

Creating a new table

Let us extend the shop with product reviews. The syntax is CREATE TABLE name (column type options, ...). An identity column generates consecutive numbers by itself: GENERATED ALWAYS AS IDENTITY is the standard and recommended form in PostgreSQL 10 and later (the old SERIAL still works; MySQL uses AUTO_INCREMENT and SQLite, INTEGER PRIMARY KEY). NOT NULL forces a value to be given and DEFAULT defines the one used when none is given. We will add the foreign keys in lesson 3 with ALTER TABLE.

sql
CREATE TABLE reviews (
  review_id   INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  product_id  INTEGER NOT NULL,
  customer_id INTEGER NOT NULL,
  rating      SMALLINT NOT NULL,
  comment     TEXT,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Check the structure in psql:
-- \d reviews

-- The same information with SQL (works in any PostgreSQL client)
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'reviews'
ORDER BY ordinal_position;

Each engine stores its catalog in system tables; information_schema is the standard version you can query with a normal SELECT. To remove a table, the statement is DROP TABLE name. It is irreversible: the structure and all the data are lost. That is why it is advisable to write DROP TABLE IF EXISTS name in practice scripts, and never to run DROP against a production database without a backup and review.

sql
-- Why floats are a bad idea for money
SELECT 0.1::DOUBLE PRECISION + 0.2::DOUBLE PRECISION = 0.3::DOUBLE PRECISION AS float_equal,
       0.1::NUMERIC + 0.2::NUMERIC = 0.3::NUMERIC AS numeric_equal;

-- Types can be converted with CAST (standard) or :: (PostgreSQL shortcut)
SELECT CAST('2024-05-01' AS DATE) AS a_date, '42'::INTEGER + 1 AS a_number;

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →