LEAST And GREATEST Clip Column Extremes
GREATEST lifts the floor and LEAST caps the ceiling across mixed columns; PostgreSQL ignores NULL arguments and returns NULL only when every one is NULL.
Code
-- GREATEST 托底、LEAST 封顶:多列一起裁进安全区间
SELECT
room_id,
GREATEST(occupied, 0) AS non_negative,
LEAST(occupied, capacity) AS capped_load,
LEAST(GREATEST(occupied, 0), capacity) AS clamped
FROM rooms;
-- PostgreSQL 语义(文档 functions-comparison):列表里的 NULL 被忽略,
-- 只有全部参数都是 NULL 才返回 NULL——这与 SQL 标准的"任一 NULL 即 NULL"不同
-- 因此 GREATEST(NULL, 0) 得 0;想保留 NULL 必须先显式判断
SELECT GREATEST(NULL, 0) AS null_ignored,
GREATEST(NULL, NULL) AS all_null_is_null,
GREATEST(COALESCE(bed, 0), 1) AS explicit_default
FROM rooms LIMIT 1;How the snippet works
SELECT statements share the script, touching rooms.
What the statements actually assemble: a row cap (LIMIT) bounding the result size.
Applying it
Run the statement against the rooms table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that hold the behavior
SELECT
room_id,
GREATEST(occupied, 0) AS non_negative,
LEAST(occupied, capacity) AS capped_load,
LEAST(GREATEST(occupied, 0), capacity) AS clamped
FROM rooms;
SELECT GREATEST(NULL, 0) AS null_ignored,
GREATEST(NULL, NULL) AS all_null_is_null,
GREATEST(COALESCE(bed, 0), 1) AS explicit_default
FROM rooms LIMIT 1;
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.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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.
FAQ
- What relations does the SQL touch?
- `rooms`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.