Leanpub Header

Skip to main content

The PostgreSQL Handbook

From First Query to Production

The PostgreSQL Handbook

Learn PostgreSQL the way you will actually use it — from your first SELECT to indexes, query plans, row-level security, backups, partitioning, replication, and pgvector. 501 pages, 23 chapters, one support-ticketing database that grows with you, and every listing verified against a live PostgreSQL 18.4 before it went to print.

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
EPUB
About

About

About the Book

The PostgreSQL Handbook is the complete guide to PostgreSQL for developers who write SQL for a living — from your first SELECT to running a database in production with confidence.

Most SQL material stops at the query. This book keeps going: through the capabilities that are the actual reason to choose PostgreSQL, and out the far side into indexes, query plans, security, backups, partitioning, and replication. Across five parts, twenty-three chapters and 501 pages, you build one system — Lumina Helpdesk, a support-ticketing database that grows chapter by chapter from an empty schema into something with real data, real constraints, real indexes, and real operational concerns.

No prior PostgreSQL expertise is assumed. Comfort with basic SQL is enough to start; everything past SELECT, WHERE, and JOIN is built on the page, in order, against that one running example.

You'll learn to:

•      Design a schema that holds up: tables, keys, data types chosen on purpose, and constraints that make bad data impossible

•      Think relationally — joins, aggregation, subqueries and CTEs, and window functions that keep complex logic inside SQL instead of spilling into application code

•      Use what makes PostgreSQL PostgreSQL: JSONB living beside relational columns, full-text search, server-side functions, triggers and procedures, and MVCC concurrency explained without hand-waving

•      Operate it: pick the right index for the shape of the question, read an EXPLAIN plan and act on it, set up roles and row-level security, take backups that restore, partition a table that outgrew itself, and stand up streaming replication with connection pooling

•      Connect it to your application — Npgsql from raw ADO.NET, EF Core over PostgreSQL, and pgvector for semantic and hybrid search in the database you already run

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

Every SQL listing is real, executable SQL, verified against a live PostgreSQL 18.4 database by an automated harness before it was allowed into print. The output printed under a listing was captured from an actual run, never hand-typed. The database is deterministic by design — a fixed random seed and a fixed timestamp anchor — so when you run a listing you get the book's printed output exactly, on your machine, not "output may vary."

One script rebuilds the database to the exact state any chapter expects, so you can start reading anywhere, experiment freely, and reset when an experiment goes sideways.

Five appendices round it out: a native installation guide, a psql survival guide, the SQL style guide every listing in the book obeys, worked solutions to all 69 exercises, and a reference for what changed between PostgreSQL 16 and 18. A page-numbered index closes the book.

If you can write a SELECT, you can run PostgreSQL in production. This book is the path between the two.

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
    • 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
    • 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
    • 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 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
    • 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
    • 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 without rewriting them
    • Documents back to rows
    • 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
    • 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
    • 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
    • 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
  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
    • 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
    • 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
  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
    • 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
    • Migrations: schema as version control
  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
    • 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, honestly 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 18 Natively
  • Appendix B — The psql Survival Guide
  • Appendix C — SQL Style Guide
  • Appendix D — Worked Solutions
  • Appendix E — What Changed: PostgreSQL 16 → 18
  • 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.)

In fact, authors have earned over $15 million writing, publishing and selling 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