SQL 格式化
格式化、缩进和压缩 PostgreSQL、MySQL、SQLite 的 SQL,关键字大写,每个子句一行。
完全在浏览器中运行 — 粘贴的内容不会被上传。
SELECT c.id, c.email, count(o.id) AS order_count, sum(o.total) AS lifetime_value FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.created_at >= '2026-01-01' AND o.status <> 'refunded' GROUP BY c.id, c.email HAVING count(o.id) > 3 ORDER BY lifetime_value DESC LIMIT 25;
每个子句一行,SELECT 列表、GROUP BY、ON CONFLICT 和子查询都会缩进。可识别 PostgreSQL、MySQL 和 SQLite 关键字。
SQL 格式化参考
快速参考- SELECT … FROM … WHERE
- SQL 期望的子句顺序。每个子句一行,才能让长查询在评审或日志中可读。
- LEFT JOIN … ON
- 保留左表所有行,未匹配时填 NULL;INNER JOIN 则会丢弃未匹配的行。
- GROUP BY / HAVING
- HAVING 在聚合后过滤,WHERE 在聚合前过滤,因此 WHERE 中不能用 COUNT 或 SUM 的结果。
- WITH name AS (…)
- 公共表表达式。多数执行计划器会内联它,但能让长查询更易读;自引用需加 RECURSIVE。
- ON CONFLICT (key) DO UPDATE
- PostgreSQL 与 SQLite 的 upsert 写法。MySQL 使用 INSERT … ON DUPLICATE KEY UPDATE。
- LIMIT n OFFSET m
- 分页读取结果,但偏移量超过几千行后更适合用键集游标(WHERE id > last_id)。
SQL 相关语法指南
全部 SQL 指南Postgres RLS 42P17: infinite recursion detected in policy
A policy on members that reads members re-enters itself. One security definer function with a pinned search_path ends the recursion and leaves the rest of the policy intact.
SQLPgBouncer Transaction vs Session Pooling: What Breaks
Port 6543 hands out a server connection per transaction, so prepared statements, SET, LISTEN and cursors stop behaving. Driver-level settings for each stack.
SQLZero-Downtime Postgres Migrations: lock_timeout and NOT VALID
One ALTER TABLE waiting behind a slow SELECT blocks every query that arrives after it. The timeout-retry loop, NOT VALID constraints and CONCURRENTLY index rules.
SQLPostgres JSONB Indexing: GIN vs Expression B-Tree
GIN answers containment, not equality, and an expression B-tree is the reverse. Choose by operator, match the expression exactly, and prove it with EXPLAIN.