Vol. I · A Postgres HandbookTwelve chapters · · 756 queries

The Query & the Schema

A reading-room reference for writing PostgreSQL by hand — selects to window functions, with the schema in plain view.

FrontChaptersSchemaColophon
Chapters · Basic SELECT · Query 017 / 136
EasyBasic SELECT

Show total revenue from all orders

The query

SQL
SELECT
  SUM(total) AS total_revenue,
  COUNT(*) AS order_count,
  ROUND(AVG(total), 2) AS avg_order_value
FROM orders
WHERE status = 'completed';
Tested against PostgreSQL 16

Note

“Multiple aggregates can be computed in a single query pass.

Tables referenced

  • orders6 cols

← Previous

Select all orders with NULL shipped_at (not shipped)

Next →

List all unique countries from customers

The Query & the Schema

Set in Fraunces and Inter Tight. Printed on parchment, in oxblood and ink. No tracking, no accounts, no JavaScript on the answer pages beyond what your browser needs to copy a query.

Compiled for Postgres 16 · MMXXVI