Instiq
Chapter 3 · Development / SQL·v1.0.0·Updated 7/12/2026·~15 min

What's changed: Initial version (topic S3)

3.2Data Definition and Database Objects (Data Types, Constraints, Indexes, Views, etc.)

Key points

Learn to design and alter tables with CREATE TABLE/ALTER TABLE/DROP TABLE, key data types (INTEGER/BIGINT/NUMERIC/VARCHAR/TEXT/BOOLEAN/DATE/TIMESTAMP/JSON/JSONB), integrity constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, NOT NULL), search-accelerating indexes, views/materialized views, triggers, sequences, schemas, tablespaces, partitioning, functions via PL/pgSQL, and the basics of streaming/logical replication.

To query data with SQL, you first need to design the container that holds the data correctly. Beyond the basic table unit, PostgreSQL offers a variety of database objects—views, triggers, sequences, and more—each serving a distinct role: preserving integrity, preventing duplication, or reusing common queries. This section surveys everything from basic design to more operational objects.

3.2.1Table definition, data types, and constraints

  • CREATE TABLE defines a new table (CREATE TABLE t (id INTEGER PRIMARY KEY, name VARCHAR(50))). ALTER TABLE adds columns, changes types, adds constraints, etc. (ALTER TABLE t ADD COLUMN email TEXT). DROP TABLE removes the entire table (a destructive operation removing both data and structure).
  • Key data types: integers INTEGER (4 bytes) and BIGINT (8 bytes, larger range); decimals NUMERIC (arbitrary precision, suited to monetary calculations); strings VARCHAR (variable-length, optionally capped) and TEXT (unlimited length); booleans BOOLEAN; date/time DATE (date only) and TIMESTAMP (date and time; timezone-aware form is TIMESTAMP WITH TIME ZONE).
  • JSON stores JSON data as plain text (preserving the input's exact appearance). JSONB stores it parsed, in binary form (duplicate keys removed, key order not preserved, but faster to search and index). JSONB is generally the recommended choice in practice.
  • Constraints: PRIMARY KEY (a primary key combining uniqueness with NOT NULL) / FOREIGN KEY (references another table's primary key, enforcing referential integrity) / UNIQUE (forbids duplicates but allows multiple NULLs) / CHECK (an arbitrary condition such as CHECK (age >= 0)) / NOT NULL (forbids NULL values).

3.2.2Indexes, views, and other database objects

  • An index is an auxiliary structure that speeds up lookups (CREATE INDEX idx_name ON t (col)), trading off against write-time update cost. A view saves a query result as a virtual table (CREATE VIEW v AS SELECT ...; it holds no actual data and re-executes on each reference). A materialized view stores the result physically, refreshed via REFRESH MATERIALIZED VIEW (fast to read, but freshness depends on when it was last refreshed).
  • A trigger automatically runs a function when a specific event (INSERT/UPDATE/DELETE) occurs (CREATE TRIGGER). A sequence is an object that generates auto-incrementing values (CREATE SEQUENCE; the underlying mechanism behind the SERIAL auto-numbering primary key type). A schema is a namespace grouping tables and other objects (qualified as schema.table; the default is public).
  • A tablespace (TABLESPACE) designates the physical storage directory for tables and indexes (CREATE TABLESPACE, used to spread data across disks). Partitioning divides one logical table into multiple physical tables (by range, list, etc.), aiding management and query efficiency for large volumes of data.
  • Functions/procedures: logic implemented inside the database using a procedural language such as PL/pgSQL (CREATE FUNCTION), also used as the body a trigger executes. Streaming/logical replication: at a basic conceptual level only, understand that changes are transferred via WAL to another server to maintain a copy (construction, monitoring, and failure recovery are Gold-level topics).
Exam point

The staples: PRIMARY KEY combines uniqueness with NOT NULL, while UNIQUE allows multiple NULLs; a view is virtual and re-executes each time, while a materialized view stores physical data and needs REFRESH; JSONB is parsed binary and faster to search, while JSON preserves the original text; FOREIGN KEY enforces referential integrity. Questions asking for a one-line description of each object's role—trigger, sequence, tablespace, partition—are also classic.

Consider designing a new e-commerce database and walk through how each object fits together. Creating CREATE TABLE products (id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, price NUMERIC(10,2) CHECK (price >= 0), attributes JSONB) auto-numbers the id column from an internally generated sequence (products_id_seq), applies a CHECK constraint requiring price >= 0, and stores flexible extra product info (color, size, etc.) in a JSONB column. The orders table adds product_id INTEGER REFERENCES products(id) as a FOREIGN KEY, preventing orders against nonexistent product IDs. Since orders.product_id is searched frequently, CREATE INDEX idx_orders_product ON orders (product_id) speeds up join lookups—balanced against the cost of updating the index on every write. A heavy aggregation like "monthly sales ranking by product" is expensive to recompute every time, so the standard design is a materialized view (CREATE MATERIALIZED VIEW monthly_sales AS SELECT ...), refreshed nightly via REFRESH MATERIALIZED VIEW monthly_sales (an ordinary view re-executes against the base tables on every SELECT, making it unsuitable for heavy aggregation). To automatically log a notification whenever stock hits zero, combine a trigger firing on UPDATE to products with a PL/pgSQL function holding the actual logic. As orders grows huge month over month, partitioning into per-month physical tables makes searching and deleting old data more efficient. For replication, it is enough at this level to understand the concept—changes on the primary are streamed via WAL to maintain a read-only replica; actual construction procedures and parameter tuning are outside this exam's scope.

ObjectRoleNote
ViewSaves a query as a virtual tableRe-executes on each reference; holds no data
Materialized viewStores the result physicallyUpdated via REFRESH; suited to heavy aggregation
TriggerAuto-runs a function on an eventBody implemented as a PL/pgSQL function
SequenceGenerates auto-incrementing valuesUnderlies the SERIAL type
Warning

Trap: "A view saves the query result, so it won't update when the base table changes" is wrong—an ordinary view re-executes the original SELECT on every reference, always returning fresh results; it is the materialized view that requires REFRESH to update. Also, "a UNIQUE-constrained column cannot contain any NULL" is wrong—UNIQUE forbids duplicates but allows multiple NULLs (NULLs are never considered equal to each other); combine it with NOT NULL if NULLs must also be forbidden.

Diagram of data types, table definition/constraints, DB objects, and PL/pgSQL.
A view is virtual; a materialized view stores results

3.2.3Section summary

  • Manage tables with CREATE/ALTER/DROP TABLE. PRIMARY KEY = unique + NOT NULL; UNIQUE allows multiple NULLs; FOREIGN KEY = referential integrity; CHECK = arbitrary condition
  • JSONB = parsed binary, fast to search; JSON preserves text. View = virtual, re-executes each time; materialized view = stored physically, needs REFRESH
  • Trigger = event-driven function execution; sequence = auto-numbering; partitioning = physical splitting. Replication is basic concepts only at the Silver level

Sign in to track progress — Log in.

Quick check

(just a quick review)

Q1. You want a column where duplicate values are forbidden, but multiple rows may still have no value (NULL). Which constraint is appropriate?

Q2. You want fast access to a "daily sales summary" that is expensive to recompute each time. Slightly stale data is acceptable, and you want the result stored physically, updated explicitly by a nightly batch job. Which object is appropriate?

Q3. You want to flexibly store part of a product's information (variable attributes like color and size), while also caring about search performance. Which data type is most suitable?

Check your understandingPractice questions for Chapter 3: Development / SQL