Full-stack Web Technologies

CHAPTER 4
Table Creation

Column Types

  • Numeric: INTEGER, REAL, ...
  • Time related: TIME, DATE, ...
  • Text: CHAR, TEXT, VARCHAR, ...
  • Other: Arrays, JSON, Geographic, Inet, ...
Numeric Types
TypeSizeDescription
SMALLINT2Small Integer
INTERGER4Typical Integer
BIGINT8Large Integer
REAL4Like C/C++ float
DOUBLE PRECISION8Like C double
DECIMALvaruser-specified precision, exact
NUMERICvarSame as DECIMAL
SMALLSERIAL2Small auto-incremented integer
SERIAL4Medium auto-incremented integer
BIGSERIAL8Large auto-incremented integer
Text-related types
TypeSizeDescription
CHAR1One character
CHAR(N)NFixed size string of length N (with padding)
TEXTvarVariable-size string (no limit)
VARCHARvarSame as TEXT
VARCHAR(N)NVARCHAR with a limit of N (no padding)
Time-related types
TypeSizeDescription
TIME8Time of day (no date)
DATE4Date (no time of day)
TIMESTAMP8Date + Time of Day
INTERVAL16Time interval

Creating a new table

The CREATE TABLE command creates a new table with the specified columns and types:

CREATE TABLE users (
  id SERIAL,
  first_name VARCHAR(100),
  last_name VARCHAR(100),
  email VARCHAR(255),
  birthday DATE,
  age SMALLINT,
  bio TEXT
);

Adding IF NOT EXISTS makes the command succeed even if the table already exists:

CREATE TABLE IF NOT EXISTS users ( /* ... */ );

Deleting a table

The DROP TABLE command removes an existing table:

DROP TABLE users;

Adding IF EXISTS makes the command succeed even if the table wasn't there:

DROP TABLE IF EXISTS users;

Constraints

Constraints make suer we never store incorrect data.

  • NOT NULL: an attribute is never empty.
  • UNIQUE: there are no repeated values.
  • CHECK (...): the value has to satisfy a certain condition.
CREATE TABLE products (
  id INTEGER UNIQUE NOT NULL,
  name TEXT NOT NULL,
  price NUMERIC NOT NULL CHECK (price > 0),
);