Black Friday Deals For Authors Are On Now!

Leanpub Header

Skip to main content

The PostgreSQL Handbook

From First Query to Production Database

The PostgreSQL Handbook
This book is 100% completeLast updated on 2026-11-29
+100% in the last 30 days

Learn PostgreSQL 19 the way you will actually use it: from your first SELECT to upsert, query plans, row-level security, point-in-time recovery, failover, upgrades and pgvector. 23 chapters, 7 appendices, one support-ticketing database that grows with you, and every SQL listing checked against a live PostgreSQL 19 server.

Minimum price

$24.99

$32.99

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

Buying multiple copies for your team? See below for a discount!

PDF
About

About

About the Book

Writing SQL that works is the easy part. The trouble starts when the database is yours to keep alive. An index that helped last month is now making every insert slower. A schema change you shipped at noon froze every query behind one lock. Someone asks when the last backup was actually restored, and nobody knows. None of that is in a SELECT tutorial, and all of it is in this book.

The PostgreSQL Handbook, Second Edition takes you from your first query to running a production database. It is rebuilt for PostgreSQL 19: twenty-three chapters in five parts, seven appendices and 675 pages. You build one system the whole way through. Lumina Helpdesk is a support-ticketing database that grows from an empty schema into something with real data, real constraints, real indexes, real roles and a real replica.

Comfort with basic SQL is enough to start. Everything after SELECT, WHERE and JOIN is built on the page, in order, against that one running example.

You will learn how to:

·         Choose data types and constraints that make bad data impossible, and write inserts that handle the row already there with upsert and MERGE

·         Think relationally with joins, aggregation, percentiles, CTEs and window functions, so the logic stays in SQL instead of leaking into application code

·         Use what makes PostgreSQL different: JSONB beside relational columns, JSON_TABLE, full-text search you can tune, and functions that tell the planner the truth about their volatility

·         Reason about MVCC, isolation levels, row locks and timeouts, so a schema change on a live table fails fast instead of freezing everything behind it

·         Pick the right index for the shape of a question, read an EXPLAIN plan from the bottom up, and tune with evidence instead of folklore

·         Secure the database with roles, row-level security and TLS, including the pitfall that leaks one tenant's rows to another under a connection pooler

·         Take backups that restore, rehearse a point-in-time recovery to the second before the mistake, and read the server log as a monitoring tool

·         Partition a table that outgrew itself, fail over to a replica by hand, put PgBouncer in front of the server, and upgrade to the next major version with pg_upgrade

·         Run the same database on a managed service or on Kubernetes with CloudNativePG, and know which of your own steps the platform takes over

·         Reach PostgreSQL from C# with Npgsql and EF Core 10, and build semantic and hybrid search with pgvector in the database you already run

The last three chapters use C#, but this is not a C# book. The first twenty chapters contain none, and a reader who never opens Visual Studio loses nothing before Chapter 21.

What makes this book different is that you can check it. An automated harness ran 364 of the book's 373 SQL listings against a live PostgreSQL 19 server, each at the chapter state it assumes. A listing meant to succeed had to succeed, and a listing meant to fail had to fail with the error code the text names. The other nine are environment commands, such as promoting a standby. Most printed results come straight from a captured run instead of being typed in. The seed data is deterministic, and one script resets your database to the state any chapter expects, so the grid on the page is the grid you should see. The 69 exercise solutions went through the same harness.

The companion setup is one Docker image, pinned by digest, that serves every chapter from the first query to pgvector. Optional profiles add a replica and a connection pooler for the replication drills. Appendix A covers a native install if you would rather not use Docker.

Written for developers who already write some SQL and want to understand PostgreSQL itself, and for the accidental owner: the person who inherited a production database and now has to secure it, back it up, tune it, replicate it and upgrade it.

Read the first edition? This one targets PostgreSQL 19 instead of 18, adds two appendices on upgrades and on managed and Kubernetes deployments, and widens almost every chapter. The release notes list what changed.

Buying for a team? Volume licenses are available from 3 copies, with team pricing up to 40% off for larger groups: one purchase, one invoice, a copy for everyone.

The companion code lives at https://github.com/RachidD68/the-postgresql-handbook. It holds the schema, the seeds, every SQL listing as a runnable file, all 69 exercise solutions, the C# projects for Part V and the Kubernetes lab. It is MIT-licensed, separately from the book text, so you can use it in commercial work without restriction.

Share this book

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $58.00
    Suggested price
    $76.00
  • Up to 5 members

    Minimum price
    $91.00
    Suggested price
    $120
  • Up to 10 members

    Minimum price
    $174
    Suggested price
    $230
  • Up to 15 members

    Minimum price
    $249
    Suggested price
    $329
  • Up to 25 members

    Minimum price
    $374
    Suggested price
    $494

Bundle

Bundles that include this book

Author

About the Author

Rachid DAHIR

I design systems for the long haul.

As a software architect, technical author, and educator based in Morocco, I've spent more than a decade building enterprise-grade .NET solutions in financial services, healthcare, and large-scale enterprise environments — where reliability, performance, and clean architecture are not optional.

I write for developers who are ready to move past tutorials. My books share a deliberate standard: production-grade code only — no toy examples, no shortcuts that would never survive a code review; every concept explained, demonstrated, then practiced; every advanced topic taught with the same patience as an introductory one — because complexity is never an excuse for a poor explanation.

Whether you're a mid-career developer leveling up, a solution architect consolidating best practices, or an enterprise team standardizing modern .NET, my goal stays the same: clarity without compromise.

When I'm not writing code or prose, I explore mathematics, AI research, and natural health.

Contents

Table of Contents

Front Matter

  • Preface
  • Introduction
  • About the Author

Part I — Foundations

  1. Why PostgreSQL, and Getting It Running
    • The filing cabinet with a librarian
    • Where PostgreSQL came from, and why it won
    • An honest comparison
    • Setting up: one command, whole environment
    • First contact with psql
    • The meta-commands you'll use daily
    • A tour of the companion repository
  2. Designing Lumina Helpdesk: Databases, Schemas, and Tables
    • Lumina has a problem
    • Why not one big spreadsheet
    • Databases, schemas, and tables
    • From entities to tables
    • The ticket and its conversation
    • Tags: when both sides can have many
    • The rest of the cast
    • What we deliberately left out
  3. CRUD: Inserting, Reading, Updating, Deleting
    • INSERT: making rows exist
    • Seeding Lumina: the cast takes the stage
    • SELECT: asking questions
    • UPDATE: changing what is already there
    • The statement with no WHERE clause
    • DELETE: making rows not exist
    • RETURNING: the answer rides home with the statement
    • Upsert: insert the row, or deal with the one already there
    • MERGE: reconciling a table with a list
    • TRUNCATE vs DELETE: emptying a table
  4. Filtering, Sorting, and Shaping Results
    • WHERE in earnest
    • A first taste of patterns
    • NULL and the logic of the unknown
    • ORDER BY without surprises
    • LIMIT, OFFSET, and the pagination debt
    • DISTINCT, and PostgreSQL's better idea
    • CASE: computing your own columns
    • COALESCE and NULLIF: two CASEs with names
    • The everyday function toolkit
  5. Data Types Done Right
    • Numbers: exact, or fast
    • Text: the shortest section, on purpose
    • Time: always timestamptz, and here is the reasoning
    • boolean, briefly
    • uuid: identity that travels
    • Closed value sets: enum, lookup table, or CHECK
    • Arrays and ranges: containers with judgment attached
    • Primary keys: a decision framework, not a dogma

Part II — Relational Thinking

  1. Constraints: Making Bad Data Impossible
    • The last line of defense
    • NOT NULL, revisited on live data
    • Foreign keys: the arrows become real
    • UNIQUE: no two rows may share this
    • Exclusion constraints: no two rows may overlap
    • CHECK: rules in the row's own words
    • Generated columns: facts the database computes
    • Deferrable constraints: for the rare mid-flight contradiction
  2. Joins: Reading Across Tables
    • The question that needs two tables
    • LEFT JOIN and the manufactured NULL row
    • Self-joins: the org chart was in there all along
    • The supporting cast: CROSS JOIN, USING, NATURAL
    • Chains: the whole schema in one query
    • How to read a join you didn't write
  3. Aggregation: From Rows to Answers
    • Aggregates: many rows in, one answer out
    • GROUP BY: the mental leap
    • Grouping over joins, and the fan-out bill arrives
    • HAVING: a WHERE for the buckets
    • FILTER: several aggregates, several row-sets, one pass
    • Aggregating into text and arrays
    • Buckets made of time
    • Several groupings in one query: SETS, ROLLUP, CUBE
    • The typical ticket: medians, percentiles, and mode
    • The morning dashboard, built honestly
  4. Subqueries and CTEs: Composing Queries
    • Scalar subqueries: a value with a query inside
    • Sets to test against: IN and EXISTS
    • The NOT IN betrayal
    • Tables you invent mid-query
    • WITH: composition you can read aloud
    • CTEs that write
    • WITH RECURSIVE: walking the trees you planted
    • LATERAL: the per-row subquery, promoted
  5. Window Functions: Analytics Without Leaving SQL
    • The problem aggregates can't solve
    • The rank family: three philosophies of order
    • LAG and LEAD: this row, meeting its neighbors
    • Frames: the window inside the window
    • NTILE, and naming your windows
    • Top of each group: ranking inside a partition
    • Set operations: the toolkit's closing bracket
    • Capstone: the leaderboard, three ways

Part III — The PostgreSQL Difference

  1. JSONB: Relational and Document, Together
    • The false choice
    • Two types, one winner
    • Reading documents: two arrows, one trap
    • A document column of our own
    • Filtering on documents: containment does the heavy lifting
    • Building documents: the API shape, straight from SQL
    • Editing documents by describing the new one
    • Documents back to rows
    • The standard spelling: JSON_VALUE and JSON_TABLE
    • Column or key? The framework
  2. Search: Pattern Matching and Full-Text
    • Where LIKE runs out
    • pg_trgm: similarity for the fat-fingered
    • tsvector: text distilled to lexemes
    • tsquery: asking in the same language
    • The searchable column that maintains itself
    • Ranking: from matching to ordering
    • Tuning the language
    • Where PostgreSQL search stops
  3. Server-Side Code: Views, Functions, Procedures, Triggers
    • Views: a query with a name
    • Materialized views: the report, precomputed
    • Functions, part one: a named expression
    • Functions, part two: PL/pgSQL, when SQL needs a spine
    • Volatility: what you promise the planner
    • Procedures: transaction control for batch work
    • Triggers: code that fires itself
    • The discipline: facts about data, never decisions about business
  4. Transactions and Concurrency: MVCC Without Tears
    • ACID, with Lumina's money on the table
    • The boundary: BEGIN, COMMIT, ROLLBACK
    • MVCC: nobody edits a row, ever
    • Isolation levels: choosing your anomalies
    • FOR UPDATE: when reading means claiming
    • SKIP LOCKED: the job queue that cannot double-send
    • Advisory locks: mutexes on ideas
    • Deadlocks: the mutual ambush
    • Timeouts: deciding how long to wait
    • Optimistic or pessimistic: who pays for the conflict?

Part IV — Performance & Operations

  1. Indexes: The Right Tool for Each Shape of Question
    • Life without an index
    • Inside the default: B-tree mechanics
    • What you have already, and the classic gap
    • Multi-column indexes: order is the design
    • Covering indexes: never touching the table at all
    • Partial indexes: index the 8% that matters
    • Expression indexes: indexing a computation
    • The specialist family
    • The bill: write amplification
    • Hygiene: auditing the bets
  2. Reading the Planner's Mind: EXPLAIN and Query Tuning
    • The planner: a cost accountant, not an oracle
    • Reading a plan: bottom-up, one node at a time
    • EXPLAIN ANALYZE: estimates meet reality
    • The scan bestiary
    • Three ways to join, chosen for you
    • When estimates lie
    • The workflow
    • Keyset pagination: the flagship promise
    • Four more slow queries, same loop
    • The dials behind the costs
    • Generic plans: what a prepared statement gets
  3. Security: Roles, Privileges, and Row-Level Security
    • Roles: one concept for users and groups
    • Privileges: deny by default, grant by name
    • The application account: exactly enough
    • Views as the reporting surface
    • Row-Level Security: the WHERE clause nobody can forget
    • SECURITY DEFINER: controlled escalation, one pitfall
    • Predefined roles, and removing a role
    • The front door: pg_hba, SCRAM, TLS
  4. Backups, Maintenance, and Monitoring
    • Logical backups: pg_dump and the restore drill
    • Physical backups and the time machine
    • The PITR drill: back to the second before
    • VACUUM: MVCC's bill, collected
    • autovacuum: the daemon you tune, never disable
    • Bloat: finding the invisible weight
    • pg_stat_statements: the first thing you install
    • The Monday morning gauges
    • The log is a monitoring tool
  5. Partitioning: When One Table Isn't Enough
    • What partitioning solves — and what it doesn't
    • The migration: copy and swap
    • Pruning: the trick Chapter 16's plans couldn't do
    • The retention conveyor
    • Indexes and constraints across the pieces
    • When not to partition
  6. Replication and Connection Pooling
    • Why replicate — and the boundary that isn't
    • Streaming replication: the diary, shipped
    • Lag, and reading your own writes
    • Failover, by hand
    • Logical replication: rows, not bytes — live
    • Connections are expensive — measurably
    • PgBouncer: many clients, few connections
    • Conversant, not a DBA: the going-deeper map

Part V — PostgreSQL in the Real World

  1. Talking to PostgreSQL from Code
    • The driver's job, and the socket it speaks over
    • Connecting: the data source, the string, and the secret
    • First queries: a reader, typed columns, and NULL
    • Parameterized queries: the non-negotiable
    • RETURNING, from the application
    • Transactions, and the retry Chapter 14 promised
    • N+1: the same disease in every language
    • Fewer round trips: array parameters and batches
    • Migrations: schema as version control
    • Testing against a real database
  2. Gateway: PostgreSQL with EF Core
    • What an ORM buys — and what it costs
    • Mapping Lumina: the database we already have
    • LINQ to SQL: watch it happen
    • The provider that actually likes PostgreSQL
    • EF migrations, meeting ours
    • Where hand-written SQL still wins
    • The concurrency token you already had
    • Set-based writes: ExecuteUpdate and ExecuteDelete
    • Retries: the execution strategy
    • Onward
  3. Gateway: PostgreSQL as an AI Database with pgvector
    • Why vectors, and why in your relational database
    • The vector type: an embedding is just a column
    • Distance operators, and the canonical query shape
    • HNSW: approximate neighbors, knowingly traded
    • Semantic search end to end: has anyone solved this before?
    • From C#: Lumina.Search
    • Hybrid search: the Chapter 12 promise, discharged
    • Onward

Appendices

  • Appendix A — Installing PostgreSQL 19 Natively
  • Appendix B — The psql Survival Guide
  • Appendix C — SQL Style Guide
  • Appendix D — Worked Solutions
  • Appendix E — What Changed: PostgreSQL 17 → 19
  • Appendix F — Upgrading and Configuring a Production Server
  • Appendix G — PostgreSQL Managed and on Kubernetes
  • Other Books You’ll Enjoy
  • Index

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub