USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksPostgreSQL Book
HomePostgreSQL BookSQL Fluency
PreviousINSERT, UPDATE, DELETE, RETURNING, and UPSERTNextJoins and Relationship Queries Without Duplicate Surprises
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

16 sections

Progress0%
1 / 16

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

SELECT, Filtering, Sorting, Pagination, and NULL

SELECT describes a result set; it does not promise row order unless ORDER BY makes that order complete. Filters use three-valued logic—true, false, and unknown—because NULL means missing or inapplicable, not zero or an empty string. Correct reading also requires explicit columns, tenant scope, and bounded pagination.

What will you be able to do?

  • Project, filter, sort, limit, and paginate rows.
  • Reason correctly about NULL and boolean conditions.
  • Use expressions, aliases, CASE, and safe pattern matching.
  • Build stable keyset pagination.

Prerequisites and mental model

A query is a pipeline that conceptually chooses source rows, filters them, forms groups, projects expressions, sorts, and limits. The planner may execute it differently while preserving SQL semantics.

How do you write an explicit read?

sql
SELECT id, subject, status, priority, created_at, CASE priority WHEN 'urgent' THEN 1 WHEN 'high' THEN 2 WHEN 'normal' THEN 3 ELSE 4 END AS priority_rank FROM signaldesk.tickets WHERE organization_id = $1 AND status = ANY ($2::text[]) AND created_at >= $3 ORDER BY created_at DESC, id DESC LIMIT $4;

The ID tie-breaker makes ordering deterministic when timestamps match. SELECT * is useful interactively but makes application contracts brittle and can fetch large/sensitive columns unnecessarily.

How does NULL change logic?

NULL = NULL is unknown, not true. Use:

sql
WHERE resolved_at IS NULL

For null-safe equality, PostgreSQL provides:

sql
WHERE old_value IS NOT DISTINCT FROM new_value

NOT IN can surprise when its set contains null. Prefer NOT EXISTS for anti-joins when nullability is possible.

How do you paginate without drift?

Offset pagination is simple but grows more expensive and shifts when rows are inserted. Keyset pagination continues after the last sort key:

sql
SELECT id, subject, created_at FROM signaldesk.tickets WHERE organization_id = $1 AND (created_at, id) < ($2, $3) ORDER BY created_at DESC, id DESC LIMIT 50;

The cursor contains the last created_at and id. Direction and null handling must match the ordering.

Why does this matter in AI-native systems?

Retrieval and model tools need bounded, deterministic context. An unbounded query can exceed token, latency, or privacy budgets. Explicit projections prevent hidden columns from entering prompts. Stable pagination and “as of” timestamps make evaluations reproducible; a changing result set otherwise makes model comparisons misleading.

Prove it worked

Insert two rollbackable tickets with the same created_at. Prove ordering is unstable in meaning without a tie-breaker, then add id. Create rows with null and non-null optional fields and produce a truth table for =, <>, IS NULL, and IS DISTINCT FROM.

Production judgment

  • Bound user-controlled limits and pattern searches.
  • ILIKE '%term%' may require specialized indexing and still needs measurement.
  • Collation determines ordering and equality behavior for text.
  • Read replicas can lag; “read your write” may require the primary or consistency coordination.
  • Pagination cursors should be opaque, signed if tampering matters, and scoped to query filters.

Common mistakes

  • Rows change order: no complete ORDER BY → add stable tie-breakers.
  • Missing null rows: = NULL → use IS NULL.
  • Slow deep pages: large OFFSET → use keyset pagination where the UX permits.
  • Sensitive prompt leakage: SELECT * → project only authorized fields.

AI Pair-Programmer Prompt

text
Review this read query for SignalDesk. Check tenant scope, explicit projection, NULL semantics, deterministic order, result bounds, pagination cursor, parameterization, collation/time assumptions, sensitive columns, and replica consistency. Do not execute it. Provide edge-case seed rows and expected results before suggesting optimization.

Hands-on exercise

Build an inbox query for open/pending tickets ordered by urgent-first, then oldest creation, then ID. Add keyset continuation for the composite order.

Acceptance criterion: two pages contain no duplicate or missing IDs on a fixed snapshot, and ties resolve deterministically.

Knowledge check

  1. When is row order guaranteed?
  2. What does NULL = NULL evaluate to?
  3. Why is SELECT * risky in model context?
  4. What problem does keyset pagination reduce?

Answers

  1. When a complete ORDER BY defines it.
  2. Unknown.
  3. It can fetch unintended, sensitive, or large columns and makes contracts unstable.
  4. Deep-offset cost and page drift under concurrent inserts, within its ordering assumptions.

Completion checklist

  • Queries project only needed columns.
  • NULL behavior has edge-case tests.
  • Ordering includes deterministic tie-breakers.
  • Result size and pagination are bounded.

Primary references

  • SELECT
  • Value expressions
  • Comparison functions and operators
  • Row and array comparisons