BETWEEN SYMMETRIC Swaps Bounds
Normalize swapped range bounds with BETWEEN SYMMETRIC so user-supplied min and max in either order still match, unlike plain BETWEEN which returns nothing.
Code
-- BETWEEN 的坑:下界大于上界时永远匹配不到任何行
SELECT 5 BETWEEN 10 AND 2; -- false
-- BETWEEN SYMMETRIC 自动交换边界:min/max 谁大谁小都能匹配
SELECT 5 BETWEEN SYMMETRIC 10 AND 2; -- true
-- 典型场景:价格区间筛选,前端可能把最低价/最高价传反
SELECT id, price_cents
FROM products
WHERE price_cents BETWEEN SYMMETRIC 500 AND 20000;
-- 非 SYMMETRIC 版本在同样输入下返回空集
SELECT count(*)
FROM products
WHERE price_cents BETWEEN 500 AND 20000;
-- 等价写法:用 LEAST/GREATEST 显式归一化边界
SELECT id, price_cents
FROM products
WHERE price_cents BETWEEN LEAST(500, 20000) AND GREATEST(500, 20000);What the code does
Several statements share this file — SELECT, with products among the objects involved.
Concretely, the SQL combines: a WHERE clause narrowing which rows one statement affects; COUNT aggregation.
Applying it
The products table is the working surface here.
Statements that matter
SELECT 5 BETWEEN 10 AND 2; -- false
SELECT 5 BETWEEN SYMMETRIC 10 AND 2; -- true
SELECT id, price_cents
FROM products
WHERE price_cents BETWEEN SYMMETRIC 500 AND 20000;
SELECT id, price_cents
FROM products
WHERE price_cents BETWEEN LEAST(500, 20000) AND GREATEST(500, 20000);
SELECT count(*)
FROM products
WHERE price_cents BETWEEN 500 AND 20000;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.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.
FAQ
- Which relations are involved here?
- `products`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.