Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PG
PostgreSQL
0/11 completed
Beginner
Why PostgreSQL?psql and your first tablesData types that matter
Intermediate
Constraints and relationshipsPostgres-powered SQLJSONB, arrays and full-text search
Advanced
Views, functions and triggersIndexes and EXPLAINTransactions, MVCC and locking
Pro
Roles, privileges and row-level securityBackups, replication and production
Tracks / PostgreSQL / Advanced

Views, functions and triggers

So far, all logic has lived in your queries. PostgreSQL can also store logic inside the database: saved queries (views), reusable functions, and triggers that run automatically when data changes. Used well, they keep rules in one place for every app that touches the data.

Views: saved queries

A view is a named query that you can select from like a table. It stores no data; it runs its query each time.

PostgreSQL · editable

Views hide complex joins, give reports a stable interface, and can expose only some columns to certain users (see the security lesson).

Materialized views: cached results

A materialized view runs its query once and stores the result. Reads are instant, but the data is a snapshot until you refresh it:

PostgreSQL · editable

They're ideal for dashboards and expensive reports that can be a few minutes stale. Refresh them on a schedule (for example with the pg_cron extension or a job in your app).

SQL functions

A function packages a query with parameters:

PostgreSQL · editable

$$ … $$ is dollar quoting: a way to write a string containing quotes without escaping them. STABLE tells the planner the function doesn't modify data and returns the same result within a query, which lets it optimise.

Functions can also return whole tables:

PostgreSQL · editable

PL/pgSQL: procedural code

When you need variables, IF, loops and error handling, use PL/pgSQL, Postgres's built-in programming language:

PostgreSQL · editable

Because a function runs inside one transaction, the stock check, the stock update and the insert succeed or fail together.

💬 How much logic belongs in the database is a team choice. A good rule: put data-integrity logic (constraints, audit trails, "these two changes must happen together") in the database, and business workflows (emails, payments, API calls) in the app.

Triggers: run code on every change

A trigger calls a function automatically when rows are inserted, updated or deleted. Classic use #1: keep an updated_at column correct, no matter which app does the update:

PostgreSQL · editable

Classic use #2: an audit log recording who changed what:

PostgreSQL · editable
Trigger timing Use for
BEFORE Changing or validating the row before it's written (NEW.x := …)
AFTER Side effects once the change is final (audit logs, counters)
FOR EACH ROW Runs once per affected row
FOR EACH STATEMENT Runs once per statement, however many rows

⚠️ Triggers are invisible when reading app code, so a teammate may not know they exist. Name them clearly, keep them small, and document them. \d tablename lists a table's triggers.

Procedures

A procedure is like a function that returns nothing, is run with CALL, and can COMMIT partway through, which is useful for big batch jobs:

PostgreSQL · editable

Practice

  1. Create a view customer_summary with each customer's name, number of orders and total quantity.
  2. Write a PL/pgSQL function discount(price numeric, percent integer) that raises an exception if percent is above 50.
  3. Add a trigger that prevents deleting products that still have stock (hint: BEFORE DELETE, RAISE EXCEPTION, and RETURN OLD to allow the delete).
PostgreSQL · editable
✎ Check your understanding

1.What's the difference between a view and a materialized view?

2.In a row-level trigger function, what is NEW?

3.Which trigger timing lets you modify the row before it's saved?

← JSONB, arrays and full-text search