Catch All WHERE For Optional Filters
Bind optional filters as NULL so (param IS NULL OR col = param) collapses to always true, letting one statement serve every filter combination.
Code
-- p_status / p_channel / p_from 是宿主语言绑定的可选参数:
-- 没传时绑定 NULL,(param IS NULL OR col = param) 整体为真,
-- 等于跳过该维度;一条 SQL 覆盖所有筛选组合
SELECT
order_id,
status,
channel,
created_at
FROM orders
WHERE (p_status IS NULL OR status = p_status)
AND (p_channel IS NULL OR channel = p_channel)
AND (p_from IS NULL OR created_at >= p_from)
ORDER BY created_at
LIMIT 50;
-- 代价:计划器可能为这种多组合条件生成泛化计划,
-- 过滤性差的组合要先用 EXPLAIN 实测计划质量再决定Inside the snippet
At its core this is a single SELECT statement against orders and is.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Putting it to use
Run the statement against the orders table; the LIMIT keeps the probe cheap while you tune the predicates.
Core lines
SELECT
order_id,
status,
channel,
created_at
FROM orders
WHERE (p_status IS NULL OR status = p_status)
AND (p_channel IS NULL OR channel = p_channel)
AND (p_from IS NULL OR created_at >= p_from)
ORDER BY created_at
LIMIT 50;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.