sql
Skill3 starsChanged 3 months agoMITView on GitHub
MUST USE when writing SQL, creating tables, defining columns, choosing data types, writing migrations, creating indexes, diagnosing slow queries, reading EXPLAIN output, writing JOINs, defining relationships, using subqueries, or writing code with any ORM (Prisma, Django, SQLAlchemy, ActiveRecord, TypeORM, Sequelize, Drizzle). Enforces correct types (TIMESTAMPTZ, NUMERIC for money), NOT NULL discipline, composite index order, SARGability, eager loading to prevent N+1, transaction safety, and safe migration patterns.
6 other projects use a version of this.
Adopted by
Most recently taken up by
- AvilaCarlosDev/openclaw-skillstheir own version, first seen Sep 19, 2026
- nimadorostkar/Claude-Skills-collectiontheir own version, first seen Jul 14, 2026
- Pradnyeshp/Claude-Skillstheir own version, first seen Jul 6, 2026
- ffsshhttiikk/opencode-agents-skillstheir own version, first seen Feb 28, 2026
- maragudk/skillstheir own version, first seen Feb 12, 2026
- thechandanbhagat/claude-skillstheir own version, first seen Jan 22, 2026
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- maragudk/skills★ 49same name
- nimadorostkar/Claude-Skills-collection★ 28same name
- thechandanbhagat/claude-skills★ 8same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- Pradnyeshp/Claude-Skills★ 2same name
- AvilaCarlosDev/openclaw-skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository16 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- code-structureSkill
- debuggingSkill
- docker-best-practicesSkill
- drf-best-practicesSkill
- drizzle-ormSkill
- expressSkill
- fastapiSkill
- git-merge-conflictsSkill
- reactSkill
- researchSkill
- security-practicesSkill
- tanstack-querySkill
- tanstack-routerSkill
- testing-best-practicesSkill
- typescript-best-practicesSkill
The file
We split this skill into the rules it gives an agent
7 rules. 0 are common, 3 are distinctive, and 4 are very specific to this project.
0
Common
Most of the 6 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 46
Every ORM defaults to lazy loading.
- Very specific: line 72
If any value in the subquery is NULL, NOT IN returns no rows.
- Distinctive: line 198
Always inspect what your ORM generates.
- Very specific: line 213
Indexes: Always index FK columns (PG/SQLite/MSSQL).
- Distinctive: line 215
ORMs: Never rely on lazy loading.
- Very specific: line 216
Transactions: Keep them short. Use SERIALIZABLE for financial/inventory operations.
- Very specific: line 218
Measure, don't guess: Run EXPLAIN ANALYZE before and after index changes.
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL — Schema, Indexes, Joins, ORMs
Critical relational design and query patterns. The 80% case lives in this file; deep dives in the reference files.
Quick Reference — When to Load What
| Working on… | Read |
CREATE TABLE, ALTER TABLE, picking types, writing migrations | SCHEMA-DESIGN.md |
CREATE INDEX, slow queries, EXPLAIN output, pagination | INDEXING.md |
JOIN, subqueries, defining FKs, junction tables | JOINS.md |
| Any ORM code (Prisma/Django/SQLAlchemy/AR/TypeORM/Sequelize/Drizzle), transactions, locking | ORM-PATTERNS.md |
Critical Gotchas (Always-Inline)
These are the bugs that ship to production silently. Memorize them.
1. LEFT JOIN Silently Becomes INNER JOIN
Filtering the right-side table in WHERE eliminates the NULL rows the LEFT JOIN was supposed to preserve.
-- BAD: WHERE on right table kills the LEFT JOIN
SELECT c.name, o.total FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE o.status = 'shipped';
-- Customers with no shipped orders DISAPPEAR
-- GOOD: filter in the ON clause
SELECT c.name, o.total FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id AND o.status = 'shipped';Rule: ON controls how tables relate; WHERE controls what rows survive. For OUTER JOINs the distinction is critical.
2. N+1 With ORMs (Lazy Loading Default)
Every ORM defaults to lazy loading. Fetching parents then accessing children in a loop fires N+1 queries.
# BAD: 1 query for users + N queries for posts (every ORM)
users = User.find_all()
for user in users:
print(user.posts) # separate SELECT per userThe fix is ORM-specific — see ORM-PATTERNS.md for per-ORM eager loading APIs (include, select_related, joinedload, includes, relations, etc.).
Trap: SQLAlchemy joinedload + pagination silently broken — LIMIT N applies to joined rows, not parent rows, so you may get 2 users instead of 10. Use selectinload for paginated queries.
The same trap hits files. Per-file latency adds up when DuckDB reads one Parquet source per query.
# BAD: one query per file
for path in paths:
con.sql(f"SELECT * FROM read_parquet('{path}')")
# GOOD: one scan over every file; filename=true says which file a row came from
con.sql("SELECT * FROM read_parquet($paths, filename = true)", params={"paths": paths})3. NOT IN With NULLs Returns Empty Set
If any value in the subquery is NULL, NOT IN returns no rows. Always use NOT EXISTS.
-- BAD: one NULL in closed_departments → empty result
SELECT name FROM employees
WHERE department_id NOT IN (SELECT department_id FROM closed_departments);
-- GOOD
SELECT name FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM closed_departments cd WHERE cd.department_id = e.department_id
);4. NUMERIC for Money, TIMESTAMPTZ for Time
-- BAD: FLOAT loses precision; TIMESTAMP loses timezone
CREATE TABLE invoices (amount REAL, created_at TIMESTAMP);
-- GOOD
CREATE TABLE invoices (
amount NUMERIC(12,2) NOT NULL CHECK (amount >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);5. Missing FK Indexes
PostgreSQL does not auto-create indexes on foreign key columns. Without them, JOINs require sequential scans and parent DELETE/UPDATE locks the whole child table. (MySQL/InnoDB auto-indexes FKs; PG, SQLite, SQL Server do not.)
CREATE INDEX idx_orders_customer_id ON orders (customer_id);6. Composite Index Column Order
Equality → range → ORDER BY. Leftmost-prefix rule: index (A, B, C) serves A, A+B, A+B+C — but not B alone.
-- BAD: leading column is the range predicate
CREATE INDEX idx_orders ON orders (created_at, customer_id);
-- GOOD: equality first, range second
CREATE INDEX idx_orders ON orders (customer_id, created_at);7. SARGability — No Functions on Indexed Columns
-- BAD: function wraps the column → index ignored
SELECT * FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2025;
-- (MySQL syntax: YEAR(created_at) — same problem.)
-- GOOD: rewrite as range
SELECT * FROM orders
WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01';Same applies to arithmetic (price / 100 > 50 → price > 5000) and implicit type casts (VARCHAR phone = 5551234 casts every row).
8. NOT NULL by Default
NULL breaks equality (NULL != NULL) and forces three-valued logic everywhere. Make every column NOT NULL unless it's genuinely optional.
9. Pre-Aggregate Before Joining Two "Many" Tables
Joining orders and refunds both via customer_id creates a Cartesian product per customer — aggregates inflate silently.
-- BAD: 3 orders × 2 refunds = 6 rows per customer, SUM(amount) is 2x wrong
SELECT c.id, SUM(o.amount), SUM(r.refund)
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN refunds r ON c.id = r.customer_id
GROUP BY c.id;
-- GOOD: pre-aggregate
SELECT c.id, o.total, r.refunds FROM customers c
LEFT JOIN (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) o
ON c.id = o.customer_id
LEFT JOIN (SELECT customer_id, SUM(refund) AS refunds FROM refunds GROUP BY customer_id) r
ON c.id = r.customer_id;10. Safe Migrations — Three Things
Three patterns that prevent production outages. See SCHEMA-DESIGN.md for full migration playbook.
-- PG 11+: ADD COLUMN with constant NOT NULL DEFAULT is INSTANT — no table rewrite.
ALTER TABLE users ADD COLUMN bio TEXT NOT NULL DEFAULT 'No bio';
-- BUT volatile defaults (NOW(), gen_random_uuid()) or backfilling existing
-- rows from another value still need the three-step:
ALTER TABLE users ADD COLUMN bio TEXT; -- 1. nullable
UPDATE users SET bio = '...' WHERE id BETWEEN 1 AND 10000; -- 2. batched backfill
ALTER TABLE users ALTER COLUMN bio SET NOT NULL; -- 3. constrain
-- Indexes in production
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
-- Always set a lock timeout
SET lock_timeout = '5s';When to Use What
| Task | Approach |
| Money | NUMERIC(12,2) |
| Timestamps | TIMESTAMPTZ |
| Primary keys | BIGSERIAL (internal) or UUIDv7 (public) — never UUIDv4; default to BIGINT not INT to avoid future exhaustion |
| UUIDv7 in PG | PG 18+ has built-in uuidv7(); earlier versions need an extension or app-side generation |
| Membership check | EXISTS (short-circuits) |
| Exclude-with-NULLs | NOT EXISTS (never NOT IN) |
| Pagination at scale | Keyset (cursor), not OFFSET |
COUNT(*) on huge tables | Approximate via pg_class.reltuples |
| Index for OR conditions | UNION of two index scans |
| LIKE with leading wildcard | pg_trgm GIN index |
| Index foreign keys | Always |
| Soft delete | Avoid — prefer archive table + hard delete |
| EAV / multi-value columns | Never — use proper columns or JSONB+GIN |
ORM SQL Logging — Enable in Development
Always inspect what your ORM generates. See ORM-PATTERNS.md for full details.
| ORM | Enable |
| Prisma | new PrismaClient({ log: ['query'] }) |
| Django | Django Debug Toolbar or django.db.connection.queries |
| SQLAlchemy | echo=True on engine |
| ActiveRecord | Rails dev log, bullet gem |
| TypeORM | logging: true |
| Sequelize | logging: console.log |
| Drizzle | logger: true |
Rules
- Schema:
TIMESTAMPTZalways,NUMERICfor money,NOT NULLby default, FK on the "many" side, no EAV, no comma-separated IDs. - Indexes: Always index FK columns (PG/SQLite/MSSQL). Composite order = equality → range → sort. Never wrap indexed columns in functions.
SELECTonly needed columns to enable index-only scans. UseCREATE INDEX CONCURRENTLYin production. - Joins: Filter outer-join right side in
ON, notWHERE. UseNOT EXISTS, neverNOT IN. Pre-aggregate before joining "many" tables.COUNT(column)notCOUNT(*)with OUTER JOINs. - ORMs: Never rely on lazy loading. Always specify the eager-loading strategy for your ORM. Enable SQL logging in dev. Never query in a loop — read many Parquet files in one DuckDB scan.
- Transactions: Keep them short. Use
SERIALIZABLEfor financial/inventory operations. Lock rows in consistent order. Setstatement_timeoutandidle_in_transaction_session_timeout. - Migrations: Constant-default columns are instant (PG 11+); use three-step (nullable → backfill → constrain) for volatile/computed defaults or row-derived backfills.
CREATE INDEX CONCURRENTLY.ADD CONSTRAINT NOT VALIDthenVALIDATEseparately. AlwaysSET lock_timeout. - Measure, don't guess: Run
EXPLAIN ANALYZEbefore and after index changes. RunANALYZEafter bulk loads.
Reference Files
For deeper guidance, load the file matching what you're working on:
- SCHEMA-DESIGN.md — read when creating or altering tables, picking data types, writing migrations, or designing relationships. Covers: normalization (1NF/2NF/3NF), data type selection, constraints, god tables, polymorphic associations, soft delete pitfalls, three-step migrations, lock management.
- INDEXING.md — read when creating indexes, diagnosing slow queries, or reading EXPLAIN output. Covers: index types (B-tree/Hash/GIN/GiST), covering indexes, partial indexes, expression indexes, SARGability deep dive, LIKE with wildcards, OR conditions, EXPLAIN plan interpretation, keyset pagination, COUNT on large tables.
- JOINS.md — read when writing JOINs, defining FKs, or using subqueries. Covers: LEFT-to-INNER conversion variants, fan-out, EXISTS vs IN vs JOIN tradeoffs, correlated subqueries, junction tables, CASCADE pitfalls, FULL OUTER JOIN use cases.
- ORM-PATTERNS.md — read when writing ORM code or working with transactions/locking. Covers: per-ORM eager loading APIs (Prisma, Django, SQLAlchemy, ActiveRecord, TypeORM, Sequelize), transaction isolation levels, optimistic vs pessimistic locking, deadlock prevention, long-running transaction damage.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

