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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Name the tables involved in this file.
`orders` — referenced directly, no join needed.