Обсуждение: Why is this SELECT evaluated?

Поиск
Список
Период
Сортировка

Why is this SELECT evaluated?

От
Miles Elam
Дата:
Postgres v15

Given this example of a conversion from a byte array to an int8
masquerading as an "unsigned" int4

      SELECT (get_byte(bytes, byte_offset)::int8 << 24)
             | (get_byte(bytes, byte_offset + 1) << 16)
             | (get_byte(bytes, byte_offset + 2) << 8)
             | (get_byte(bytes, byte_offset + 3))
        FROM ( VALUES ('\x010000'::bytea, 0) ) b(bytes, byte_offset)
       WHERE length(bytes) >= (4 + byte_offset)
      ;

Why does this error result?

    ERROR: index 3 out of valid range, 0..2
    SQL state: 2202E

I was under the impression that if the WHERE clause evaluated to
false, the SELECT clause would not be evaluated. Why is get_byte(...)
ever run in the first place even though length(bytes) is 3?

- Miles Elam



Re: Why is this SELECT evaluated?

От
Christophe Pettus
Дата:

> On Jan 28, 2023, at 11:29, Miles Elam <miles.elam@productops.com> wrote:
> Why does this error result?

While the standard order of operations is to evaluate the WHERE before the SELECT list, it's not guaranteed to result
inshort-cut execution.  In particular, constant folding happens very early in the processing of a query, well before
theWHERE clause is evaluated: 

xof=# SELECT 1/0 WHERE FALSE;
ERROR:  division by zero