Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Postgres Queries?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/adityaaatiwari-postgres-queries)
---
name: postgres-queries
description: "Write, index and migrate PostgreSQL safely: EXPLAIN ANALYZE, indexes, locks and zero-downtime schema changes"
---
<!-- Generated by `anvil plugin build` from catalog/. Edit the catalog, not this file. -->
# PostgreSQL queries and schema changes
Use when writing SQL, adding indexes, or changing PostgreSQL schemas.
## Query performance
1. Reproduce with realistic data volume, then run `EXPLAIN (ANALYZE, BUFFERS)` (on a safe copy, since it executes the query).
2. Look for sequential scans on large tables, row-estimate mismatches and sorts or hashes spilling to disk.
3. Add the narrowest index that serves the query: column order follows equality filters first, then ranges and sort order. Consider partial (`WHERE deleted_at IS NULL`) and covering (`INCLUDE`) indexes.
4. Re-run EXPLAIN and compare. Remove indexes nobody uses (`pg_stat_user_indexes`); each one slows writes.
## Safe migrations on live tables
- `CREATE INDEX CONCURRENTLY` (outside a transaction) instead of a plain `CREATE INDEX`, which blocks writes.
- Add columns as nullable or with a constant default (fast since PostgreSQL 11), backfill in batches, then add `NOT NULL` via a `CHECK ... NOT VALID` constraint and `VALIDATE CONSTRAINT`.
- Add foreign keys `NOT VALID`, then validate separately.
- Set `lock_timeout` (for example `SET lock_timeout = '5s'`) so a migration fails instead of queueing behind a long transaction and blocking everything.
- Renames and type changes in steps: add new, dual-write, backfill, switch reads, drop old.
## Correctness
- Parameterized queries only. Use transactions with the isolation level the invariant needs, and `SELECT ... FOR UPDATE` for read-modify-write.
- Paginate with keyset pagination (`WHERE id > $1 ORDER BY id LIMIT n`) for large or changing tables instead of large `OFFSET`s.
## Verify
EXPLAIN before and after, the migration applied on a copy with production-like size, and the application tests.