[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D1TF7N3BKMVR9B6MXKM7B3":3,"skill-same:01M6D1TF7N3BKMVR9B6MXKM7B3":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":45,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6D1TF7N3BKMVR9B6MXKM7B3","database-queries",null,"Writing queries that are correct and fast: joins, aggregates, window functions and CTEs, the N+1 problem, keyset pagination, selecting only what is needed, parameters always, reading EXPLAIN, and the ORM habits that cause slow queries. Read before writing or reviewing a query or an ORM data access path.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-queries\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"database","queries","database queries","writing","fast","data","access","correct","explain","orm","read","only","functions","pagination","query","aggregates","2026-11-10 10:12:30",false,"---\nname: database-queries\ndescription: \"Writing queries that are correct and fast: joins, aggregates, window functions and CTEs, the N+1 problem, keyset pagination, selecting only what is needed, parameters always, reading EXPLAIN, and the ORM habits that cause slow queries. Read before writing or reviewing a query or an ORM data access path.\"\n---\n\n# Queries that are right and fast\n\nThe generated query: `SELECT *` over two joins, summed in code, `DISTINCT`\nadded when the totals came out doubled, a day filtered with\n`date(created_at) = ?` in the server's time zone, `NOT IN` against a column\nwith NULLs, and an ORM loop that loads each order's customer one at a time.\nIt returns plausible numbers on seed data and wrong ones, slowly, on real\ndata. This skill is correctness first, then speed. Indexes are in\n`database-indexes`, locking and races in `database-transactions`. Examples\nare PostgreSQL unless marked.\n\n## 1. Correct before fast\n\n- **Joins that multiply rows.** Joining orders and payments to customers\n  repeats each order once per payment, and the sums double. Aggregate each\n  child before joining (or use LATERAL or a subquery):\n\n```sql\nSELECT c.id, c.name, coalesce(o.order_count, 0) AS order_count, o.revenue_cents\nFROM customers c\nLEFT JOIN (\n  SELECT customer_id, count(*) AS order_count, sum(total_cents) AS revenue_cents\n  FROM orders WHERE status = 'paid'\n  GROUP BY customer_id\n) o ON o.customer_id = c.id;\n```\n\n  `DISTINCT` added to fix a count hides the fan-out while the sums stay\n  wrong. For \"has any\", use `EXISTS`, not a join.\n- **NULL.** `x = NULL` is never true: `IS NULL`, `IS DISTINCT FROM`.\n  `NOT IN (subquery)` returns nothing at all if the subquery yields one NULL:\n  use `NOT EXISTS`. `count(col)` skips NULLs, `count(*)` does not; `sum` over\n  no rows is NULL (`coalesce(sum(x), 0)`); `avg` ignores NULLs.\n- **Outer joins.** A condition on the right-hand table in `WHERE` turns a\n  LEFT JOIN into an inner join; put it in `ON`.\n- **GROUP BY.** Every selected column is grouped or aggregated. Keep MySQL's\n  `ONLY_FULL_GROUP_BY` on; without it MySQL returns an arbitrary row's value.\n- **Time ranges**: half-open, in the user's zone, on the raw column:\n\n```sql\n-- orders placed on 1 September 2026, Jakarta time\nWHERE created_at >= '2026-09-01 00:00:00+07' AND created_at \u003C '2026-09-02 00:00:00+07'\n```\n\n  Not `created_at::date = '2026-09-01'` (server zone, no index), not\n  `BETWEEN` (includes the end, misses 23:59:59.5).\n- **Order.** Without `ORDER BY` rows come in whatever order the plan made.\n  With `LIMIT`, end the sort on a unique column (`created_at DESC, id DESC`).\n- **Arithmetic**: `7 \u002F 2` is `3` on integers; cast for ratios\n  (`7::numeric \u002F 2`), and round money once, at the end.\n\n## 2. SQL worth knowing\n\n- Top N per group: `row_number()`, `DISTINCT ON` for the top one\n  (Postgres), or `LATERAL` with `LIMIT`, which walks an index on\n  `(customer_id, created_at)` instead of ranking every row:\n\n```sql\nSELECT c.id, last.*\nFROM customers c\nCROSS JOIN LATERAL (\n  SELECT id, total_cents, created_at FROM orders\n  WHERE customer_id = c.id\n  ORDER BY created_at DESC, id DESC\n  LIMIT 3\n) last;\n```\n\n- Running totals: `sum(amount_cents) OVER (PARTITION BY account_id ORDER BY\n  created_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. Say\n  `ROWS`: the default `RANGE` frame lumps rows with equal sort keys.\n- Conditional aggregates: `count(*) FILTER (WHERE status = 'paid')`\n  (Postgres, SQLite 3.30+); in MySQL `SUM(status = 'paid')`.\n- CTEs for readability. Since Postgres 12 a CTE used once is inlined;\n  `AS MATERIALIZED` computes it once as a fence, `NOT MATERIALIZED` inlines.\n- Upsert: `INSERT ... ON CONFLICT (shop_id, sku) DO UPDATE SET stock =\n  excluded.stock` (Postgres, SQLite 3.24+); MySQL 8.0.19+\n  `INSERT ... AS new ON DUPLICATE KEY UPDATE stock = new.stock` (`VALUES()`\n  there is deprecated). `ON CONFLICT DO NOTHING RETURNING id` returns no row\n  when it already existed: select it afterwards.\n- `RETURNING` on insert, update and delete saves a round trip (Postgres,\n  SQLite 3.35+, MariaDB 10.5+ on insert and delete; not MySQL).\n- `MERGE` (Postgres 15+, `RETURNING` from 17) for multi-branch syncs; for\n  one table and a unique key, `ON CONFLICT` is simpler and safe under races.\n\n## 3. Bulk work\n\n- Inserts as multi-row `VALUES` in batches of 500 to 1,000 rows. Postgres\n  takes at most 65,535 bind parameters per statement, SQLite 32,766 by\n  default. Or send arrays: `INSERT INTO tags (name) SELECT unnest($1::text[])`,\n  and `WHERE id = ANY($1)` for a list in one parameter.\n- Large loads: `COPY ... FROM STDIN` through the driver (Postgres),\n  `LOAD DATA` (MySQL), one transaction around the inserts (SQLite: thousands\n  per second instead of dozens).\n- Reading a big table: keyset batches (`WHERE id > $last ORDER BY id LIMIT\n  1000`) or a server-side cursor (psycopg named cursors, SQLAlchemy\n  `yield_per`, Django `.iterator(chunk_size=2000)`, Rails `find_each`,\n  Laravel `chunkById` or `lazyById`). OFFSET chunking skips or repeats rows\n  while the table changes.\n- Bulk updates as one statement:\n  `UPDATE products p SET price_cents = v.price FROM (VALUES (1, 1500), (2, 990)) AS v(id, price) WHERE p.id = v.id;`\n\n## 4. N+1\n\n- One query for a list, then one per row for a relation: 50 rows are 51\n  round trips, 100ms of waiting at 2ms each before any work is done.\n- Find it: the query log in development (Prisma `log: ['query']`,\n  `django-debug-toolbar`, Rails `bullet` or `strict_loading`, Laravel\n  `Model::preventLazyLoading()`), or a test that counts queries per request\n  (Django `assertNumQueries`).\n- Fix it with one more query or a join:\n\n| Layer | Eager load |\n|---|---|\n| Prisma | `include: { customer: true }`, or `select` with the relation |\n| Drizzle | relational queries, `with: { customer: true }` |\n| SQLAlchemy | `selectinload(Order.items)`, `joinedload(Order.customer)` |\n| Django | `select_related(\"customer\")`, `prefetch_related(\"items\")` |\n| Rails | `includes(:customer)`, `preload`, `eager_load` |\n| Laravel | `with('customer')`, `load()` |\n| GraphQL | a DataLoader per request |\n\n- For to-many relations prefer the separate `IN` query (`selectinload`,\n  `prefetch_related`, `preload`): a join repeats the parent's columns for\n  each child.\n\n## 5. Pagination and counts\n\n- Keyset for long or changing lists, with an index on the sort key and id:\n\n```sql\nSELECT id, created_at, total_cents FROM orders\nWHERE customer_id = $1\n  AND (created_at, id) \u003C ($2, $3)   -- the last row of the previous page\nORDER BY created_at DESC, id DESC\nLIMIT 50;\n```\n\n  Row comparison works in Postgres and SQLite; in MySQL write\n  `created_at \u003C ? OR (created_at = ? AND id \u003C ?)`, which it plans reliably.\n- OFFSET only for short lists and page-numbered admin screens: every skipped\n  row is read and thrown away, and rows shift between pages as data changes.\n- Exact counts scan in Postgres and InnoDB. For a whole table, an estimate:\n  `SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclass;`.\n  For a filter, a capped count shown as \"10,000+\":\n  `SELECT count(*) FROM (SELECT 1 FROM orders WHERE ... LIMIT 10001) t;`.\n  Or no total at all, only \"next\".\n\n## 6. Fast by default\n\n- Select the columns you use. `SELECT *` drags big `text` and `jsonb`\n  columns over the network, prevents index-only scans, and changes shape\n  when a column is added.\n- Keep predicates usable by an index: nothing computed on the indexed column\n  (`created_at > now() - interval '1 day'`, not\n  `created_at + interval '1 day' > now()`; `lower(email) = $1` only with an\n  index on `lower(email)`), and no implicit casts (MySQL comparing a\n  `VARCHAR` column to a number scans the table).\n- `LIKE 'abc%'` can use a B-tree (Postgres needs `text_pattern_ops` unless\n  the collation is `C`); `LIKE '%abc%'` and `ILIKE` need trigrams\n  (`database-indexes`) or full-text search.\n- `OR` across different columns often scans; rewrite as `UNION ALL` of two\n  indexed queries when the plan says so.\n- `EXISTS` for \"is there any\", not `count(*) > 0`.\n- A ceiling on every query: `statement_timeout` for the web role (5 to 15s)\n  and `SET LOCAL statement_timeout = '2s'` inside the transaction of a risky\n  one, so a bad plan fails instead of piling up connections.\n\n## 7. Parameters, always\n\n- Values through placeholders (`$1`, `?`, `:name`) or a safe template\n  (postgres.js and Drizzle `sql` tagged templates, Prisma `$queryRaw` with a\n  template literal, SQLAlchemy `text()` with bound parameters). Never\n  `$queryRawUnsafe`, `sql.raw`, f-strings or `+` with anything a user sent.\n- Identifiers (sort column, direction) cannot be parameters: map them from\n  an allow-list (`{ newest: 'created_at DESC', total: 'total_cents DESC' }`),\n  or quote with `format('%I', name)` inside Postgres functions.\n- A list as one array parameter (`= ANY($1)`) or the builder's expansion,\n  never a joined string.\n\n## 8. Reading EXPLAIN\n\n`EXPLAIN (ANALYZE, BUFFERS)` runs the query and reports what happened\n(Postgres 18 adds buffers by default). For a write:\n`BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE ...; ROLLBACK;`.\n\n| You see | It means | Try |\n|---|---|---|\n| `Seq Scan` on a big table, `Rows Removed by Filter` in the millions | No usable index for the filter | An index on the filter; a sargable rewrite |\n| Estimated `rows=10`, actual `rows=100000` | Stale statistics or correlated columns | `ANALYZE orders`; `CREATE STATISTICS` on the columns |\n| `Nested Loop` with a large `loops=` | A plan made for few rows ran for many | Fix the estimate; index the inner join key |\n| `Sort Method: external merge  Disk: ...` | The sort spilled to disk | An index in `ORDER BY` order, or more `work_mem` for it |\n| `Index Only Scan` with many `Heap Fetches` | The visibility map is behind | Vacuum the table |\n| `Buffers: shared read=` large | Pages came from disk, not cache | Fewer rows or columns; check the cache hit ratio |\n\n- Per-node times are per loop: multiply by `loops`. Paste a plan into\n  explain.dalibo.com or explain.depesz.com to read it as a tree.\n- MySQL: `EXPLAIN ANALYZE` (8.0.18+) or `EXPLAIN FORMAT=TREE`; `type: ALL` is\n  a full scan, `Using filesort` and `Using temporary` are sorts and temp\n  tables. SQLite: `EXPLAIN QUERY PLAN` (`SCAN` is a full scan, `SEARCH ...\n  USING INDEX` is not). MongoDB: `explain(\"executionStats\")`.\n- Judge plans on realistic volumes: on a 100-row table a sequential scan is\n  the right plan.\n\n## 9. ORM habits that make queries slow\n\n- Lazy loading inside a loop or a template (section 4).\n- Whole records loaded to use two fields: `select`, `only()`, `values()`,\n  `pluck`, `defer` for big columns.\n- Counting or checking in memory (`len(queryset)`, `->get()->count()`,\n  `.length` of a fetched array); use `count()` and `exists()`.\n- Read, change, save for counters and totals; an `UPDATE` with an expression\n  (`F(\"stock\") - 1`, `decrement('stock')`, `{ stock: { decrement: 1 } }`) is\n  one query and race-free (`database-transactions`).\n- A save per row in a loop; use `bulk_create`, `insert_all`, `createMany`.\n- Filtering after fetching; filter in the query.\n- `findMany()` or `all()` behind an endpoint with no limit.\n\n## Check it\n\n- Run the query with the edge rows present: NULLs, a customer with no\n  orders, an order with several payments, a row at 23:59 on the boundary\n  day.\n- Compute an aggregate a second, simpler way (a count through `EXISTS`\n  against the join version) and compare.\n- `EXPLAIN (ANALYZE, BUFFERS)` on production-like volumes: the intended\n  index is used and estimates are within about ten times of actual rows.\n- Count queries per request in development: a list page issues the same\n  number of queries for 5 rows as for 500.\n- After release, `pg_stat_statements` or the slow log: the new query is not\n  among the top by total time.\n\n## Avoid\n\n`SELECT *`; `DISTINCT` to hide duplicated rows; sums over joins that fan\nout; `NOT IN` with a nullable subquery; `date(created_at) = ?`; `BETWEEN` on\ntimestamps; `LIMIT` without a unique `ORDER BY`; deep OFFSET pages; exact\ncounts of millions of rows on every page view; a query per row; values or\nsort columns concatenated into SQL; functions on indexed columns in `WHERE`;\na plan judged on a 100-row table; a table read into memory to filter or\ncount it.\n","# Queries that are right and fast\n\nThe generated query: `SELECT *` over two joins, summed in code, `DISTINCT`\nadded when the totals came out doubled, a day filtered with\n`date(created_at) = ?` in the server's time zone, `NOT IN` against a column\nwith NULLs, and an ORM loop that loads each order's customer one at a time.\nIt returns plausible numbers on seed data and wrong ones, slowly, on real\ndata. This skill is correctness first, then speed. Indexes are in\n`database-indexes`, locking and races in `database-transactions`. Examples\nare PostgreSQL unless marked.\n\n## 1. Correct before fast\n\n- **Joins that multiply rows.** Joining orders and payments to customers\n  repeats each order once per payment, and the sums double. Aggregate each\n  child before joining (or use LATERAL or a subquery):\n\n```sql\nSELECT c.id, c.name, coalesce(o.order_count, 0) AS order_count, o.revenue_cents\nFROM customers c\nLEFT JOIN (\n  SELECT customer_id, count(*) AS order_count, sum(total_cents) AS revenue_cents\n  FROM orders WHERE status = 'paid'\n  GROUP BY customer_id\n) o ON o.customer_id = c.id;\n```\n\n  `DISTINCT` added to fix a count hides the fan-out while the sums stay\n  wrong. For \"has any\", use `EXISTS`, not a join.\n- **NULL.** `x = NULL` is never true: `IS NULL`, `IS DISTINCT FROM`.\n  `NOT IN (subquery)` returns nothing at all if the subquery yields one NULL:\n  use `NOT EXISTS`. `count(col)` skips NULLs, `count(*)` does not; `sum` over\n  no rows is NULL (`coalesce(sum(x), 0)`); `avg` ignores NULLs.\n- **Outer joins.** A condition on the right-hand table in `WHERE` turns a\n  LEFT JOIN into an inner join; put it in `ON`.\n- **GROUP BY.** Every selected column is grouped or aggregated. Keep MySQL's\n  `ONLY_FULL_GROUP_BY` on; without it MySQL returns an arbitrary row's value.\n- **Time ranges**: half-open, in the user's zone, on the raw column:\n\n```sql\n-- orders placed on 1 September 2026, Jakarta time\nWHERE created_at >= '2026-09-01 00:00:00+07' AND created_at \u003C '2026-09-02 00:00:00+07'\n```\n\n  Not `created_at::date = '2026-09-01'` (server zone, no index), not\n  `BETWEEN` (includes the end, misses 23:59:59.5).\n- **Order.** Without `ORDER BY` rows come in whatever order the plan made.\n  With `LIMIT`, end the sort on a unique column (`created_at DESC, id DESC`).\n- **Arithmetic**: `7 \u002F 2` is `3` on integers; cast for ratios\n  (`7::numeric \u002F 2`), and round money once, at the end.\n\n## 2. SQL worth knowing\n\n- Top N per group: `row_number()`, `DISTINCT ON` for the top one\n  (Postgres), or `LATERAL` with `LIMIT`, which walks an index on\n  `(customer_id, created_at)` instead of ranking every row:\n\n```sql\nSELECT c.id, last.*\nFROM customers c\nCROSS JOIN LATERAL (\n  SELECT id, total_cents, created_at FROM orders\n  WHERE customer_id = c.id\n  ORDER BY created_at DESC, id DESC\n  LIMIT 3\n) last;\n```\n\n- Running totals: `sum(amount_cents) OVER (PARTITION BY account_id ORDER BY\n  created_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. Say\n  `ROWS`: the default `RANGE` frame lumps rows with equal sort keys.\n- Conditional aggregates: `count(*) FILTER (WHERE status = 'paid')`\n  (Postgres, SQLite 3.30+); in MySQL `SUM(status = 'paid')`.\n- CTEs for readability. Since Postgres 12 a CTE used once is inlined;\n  `AS MATERIALIZED` computes it once as a fence, `NOT MATERIALIZED` inlines.\n- Upsert: `INSERT ... ON CONFLICT (shop_id, sku) DO UPDATE SET stock =\n  excluded.stock` (Postgres, SQLite 3.24+); MySQL 8.0.19+\n  `INSERT ... AS new ON DUPLICATE KEY UPDATE stock = new.stock` (`VALUES()`\n  there is deprecated). `ON CONFLICT DO NOTHING RETURNING id` returns no row\n  when it already existed: select it afterwards.\n- `RETURNING` on insert, update and delete saves a round trip (Postgres,\n  SQLite 3.35+, MariaDB 10.5+ on insert and delete; not MySQL).\n- `MERGE` (Postgres 15+, `RETURNING` from 17) for multi-branch syncs; for\n  one table and a unique key, `ON CONFLICT` is simpler and safe under races.\n\n## 3. Bulk work\n\n- Inserts as multi-row `VALUES` in batches of 500 to 1,000 rows. Postgres\n  takes at most 65,535 bind parameters per statement, SQLite 32,766 by\n  default. Or send arrays: `INSERT INTO tags (name) SELECT unnest($1::text[])`,\n  and `WHERE id = ANY($1)` for a list in one parameter.\n- Large loads: `COPY ... FROM STDIN` through the driver (Postgres),\n  `LOAD DATA` (MySQL), one transaction around the inserts (SQLite: thousands\n  per second instead of dozens).\n- Reading a big table: keyset batches (`WHERE id > $last ORDER BY id LIMIT\n  1000`) or a server-side cursor (psycopg named cursors, SQLAlchemy\n  `yield_per`, Django `.iterator(chunk_size=2000)`, Rails `find_each`,\n  Laravel `chunkById` or `lazyById`). OFFSET chunking skips or repeats rows\n  while the table changes.\n- Bulk updates as one statement:\n  `UPDATE products p SET price_cents = v.price FROM (VALUES (1, 1500), (2, 990)) AS v(id, price) WHERE p.id = v.id;`\n\n## 4. N+1\n\n- One query for a list, then one per row for a relation: 50 rows are 51\n  round trips, 100ms of waiting at 2ms each before any work is done.\n- Find it: the query log in development (Prisma `log: ['query']`,\n  `django-debug-toolbar`, Rails `bullet` or `strict_loading`, Laravel\n  `Model::preventLazyLoading()`), or a test that counts queries per request\n  (Django `assertNumQueries`).\n- Fix it with one more query or a join:\n\n| Layer | Eager load |\n|---|---|\n| Prisma | `include: { customer: true }`, or `select` with the relation |\n| Drizzle | relational queries, `with: { customer: true }` |\n| SQLAlchemy | `selectinload(Order.items)`, `joinedload(Order.customer)` |\n| Django | `select_related(\"customer\")`, `prefetch_related(\"items\")` |\n| Rails | `includes(:customer)`, `preload`, `eager_load` |\n| Laravel | `with('customer')`, `load()` |\n| GraphQL | a DataLoader per request |\n\n- For to-many relations prefer the separate `IN` query (`selectinload`,\n  `prefetch_related`, `preload`): a join repeats the parent's columns for\n  each child.\n\n## 5. Pagination and counts\n\n- Keyset for long or changing lists, with an index on the sort key and id:\n\n```sql\nSELECT id, created_at, total_cents FROM orders\nWHERE customer_id = $1\n  AND (created_at, id) \u003C ($2, $3)   -- the last row of the previous page\nORDER BY created_at DESC, id DESC\nLIMIT 50;\n```\n\n  Row comparison works in Postgres and SQLite; in MySQL write\n  `created_at \u003C ? OR (created_at = ? AND id \u003C ?)`, which it plans reliably.\n- OFFSET only for short lists and page-numbered admin screens: every skipped\n  row is read and thrown away, and rows shift between pages as data changes.\n- Exact counts scan in Postgres and InnoDB. For a whole table, an estimate:\n  `SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclass;`.\n  For a filter, a capped count shown as \"10,000+\":\n  `SELECT count(*) FROM (SELECT 1 FROM orders WHERE ... LIMIT 10001) t;`.\n  Or no total at all, only \"next\".\n\n## 6. Fast by default\n\n- Select the columns you use. `SELECT *` drags big `text` and `jsonb`\n  columns over the network, prevents index-only scans, and changes shape\n  when a column is added.\n- Keep predicates usable by an index: nothing computed on the indexed column\n  (`created_at > now() - interval '1 day'`, not\n  `created_at + interval '1 day' > now()`; `lower(email) = $1` only with an\n  index on `lower(email)`), and no implicit casts (MySQL comparing a\n  `VARCHAR` column to a number scans the table).\n- `LIKE 'abc%'` can use a B-tree (Postgres needs `text_pattern_ops` unless\n  the collation is `C`); `LIKE '%abc%'` and `ILIKE` need trigrams\n  (`database-indexes`) or full-text search.\n- `OR` across different columns often scans; rewrite as `UNION ALL` of two\n  indexed queries when the plan says so.\n- `EXISTS` for \"is there any\", not `count(*) > 0`.\n- A ceiling on every query: `statement_timeout` for the web role (5 to 15s)\n  and `SET LOCAL statement_timeout = '2s'` inside the transaction of a risky\n  one, so a bad plan fails instead of piling up connections.\n\n## 7. Parameters, always\n\n- Values through placeholders (`$1`, `?`, `:name`) or a safe template\n  (postgres.js and Drizzle `sql` tagged templates, Prisma `$queryRaw` with a\n  template literal, SQLAlchemy `text()` with bound parameters). Never\n  `$queryRawUnsafe`, `sql.raw`, f-strings or `+` with anything a user sent.\n- Identifiers (sort column, direction) cannot be parameters: map them from\n  an allow-list (`{ newest: 'created_at DESC', total: 'total_cents DESC' }`),\n  or quote with `format('%I', name)` inside Postgres functions.\n- A list as one array parameter (`= ANY($1)`) or the builder's expansion,\n  never a joined string.\n\n## 8. Reading EXPLAIN\n\n`EXPLAIN (ANALYZE, BUFFERS)` runs the query and reports what happened\n(Postgres 18 adds buffers by default). For a write:\n`BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE ...; ROLLBACK;`.\n\n| You see | It means | Try |\n|---|---|---|\n| `Seq Scan` on a big table, `Rows Removed by Filter` in the millions | No usable index for the filter | An index on the filter; a sargable rewrite |\n| Estimated `rows=10`, actual `rows=100000` | Stale statistics or correlated columns | `ANALYZE orders`; `CREATE STATISTICS` on the columns |\n| `Nested Loop` with a large `loops=` | A plan made for few rows ran for many | Fix the estimate; index the inner join key |\n| `Sort Method: external merge  Disk: ...` | The sort spilled to disk | An index in `ORDER BY` order, or more `work_mem` for it |\n| `Index Only Scan` with many `Heap Fetches` | The visibility map is behind | Vacuum the table |\n| `Buffers: shared read=` large | Pages came from disk, not cache | Fewer rows or columns; check the cache hit ratio |\n\n- Per-node times are per loop: multiply by `loops`. Paste a plan into\n  explain.dalibo.com or explain.depesz.com to read it as a tree.\n- MySQL: `EXPLAIN ANALYZE` (8.0.18+) or `EXPLAIN FORMAT=TREE`; `type: ALL` is\n  a full scan, `Using filesort` and `Using temporary` are sorts and temp\n  tables. SQLite: `EXPLAIN QUERY PLAN` (`SCAN` is a full scan, `SEARCH ...\n  USING INDEX` is not). MongoDB: `explain(\"executionStats\")`.\n- Judge plans on realistic volumes: on a 100-row table a sequential scan is\n  the right plan.\n\n## 9. ORM habits that make queries slow\n\n- Lazy loading inside a loop or a template (section 4).\n- Whole records loaded to use two fields: `select`, `only()`, `values()`,\n  `pluck`, `defer` for big columns.\n- Counting or checking in memory (`len(queryset)`, `->get()->count()`,\n  `.length` of a fetched array); use `count()` and `exists()`.\n- Read, change, save for counters and totals; an `UPDATE` with an expression\n  (`F(\"stock\") - 1`, `decrement('stock')`, `{ stock: { decrement: 1 } }`) is\n  one query and race-free (`database-transactions`).\n- A save per row in a loop; use `bulk_create`, `insert_all`, `createMany`.\n- Filtering after fetching; filter in the query.\n- `findMany()` or `all()` behind an endpoint with no limit.\n\n## Check it\n\n- Run the query with the edge rows present: NULLs, a customer with no\n  orders, an order with several payments, a row at 23:59 on the boundary\n  day.\n- Compute an aggregate a second, simpler way (a count through `EXISTS`\n  against the join version) and compare.\n- `EXPLAIN (ANALYZE, BUFFERS)` on production-like volumes: the intended\n  index is used and estimates are within about ten times of actual rows.\n- Count queries per request in development: a list page issues the same\n  number of queries for 5 rows as for 500.\n- After release, `pg_stat_statements` or the slow log: the new query is not\n  among the top by total time.\n\n## Avoid\n\n`SELECT *`; `DISTINCT` to hide duplicated rows; sums over joins that fan\nout; `NOT IN` with a nullable subquery; `date(created_at) = ?`; `BETWEEN` on\ntimestamps; `LIMIT` without a unique `ORDER BY`; deep OFFSET pages; exact\ncounts of millions of rows on every page view; a query per row; values or\nsort columns concatenated into SQL; functions on indexed columns in `WHERE`;\na plan judged on a 100-row table; a table read into memory to filter or\ncount it.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fdatabase-queries",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add enowdev\u002Fenowxcli --skill database-queries",{"tool":55,"command":56},"bunx","bunx skills add enowdev\u002Fenowxcli --skill database-queries",{"tool":58,"command":59},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill database-queries","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-queries\u002FSKILL.md",true,[],[64,75,91,104,125,144],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":35},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[71,72,73,74,29],"demo skill","demo","tests","project",{"skillNo":76,"name":22,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":35},"01M6D2HM0GCPM0TM2HPG9HHR2R","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[22,81,82,83,84,85,29,86,87,88,89,90],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":35},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[93,98,99,100,101,86,102,29,103],"icons","components","SET","responsive","layout","before building",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":35},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[93,111,112,113,114,115,116,117,118,29,103,119,86,120,121,122,98,123,124],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":35},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[132,93,133,99,134,135,120,136,137,138,102,114,139,140,141,29,103,86,142,143],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":35},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[93,151,152,153,154,155,156,157,102,74,158,159,29,160,161,162,163,164,165,166],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory","testing"]