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.

SqlData Integrity

Code

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

FAQ

What relations does the SQL touch?
`rooms`.