Study notes · 9% of the exam

Functions, Dates, Views and Procedures

Know how PostgreSQL string, numeric and date/time functions behave at the edges, how views, materialized views, functions, procedures and triggers work, and how to build dynamic SQL safely.

Key points

  1. 1

    String positions are 1-based. length counts characters and octet_length counts bytes, which differ for UTF-8 text.

  2. 2

    || returns NULL if either side is NULL; concat and concat_ws skip NULLs. Integer / truncates, and mod/% take the sign of the dividend.

  3. 3

    timestamptz stores an instant and displays it in the session TimeZone; timestamp stores wall-clock time. AT TIME ZONE converts between them in both directions.

  4. 4

    now() is fixed for the whole transaction; clock_timestamp() reads the real clock. Month arithmetic clamps to the month end, and adding days vs hours differs across DST changes.

  5. 5

    Plain views store only a query (SELECT * is expanded at creation). Simple views are updatable; WITH CHECK OPTION blocks writes the view could not see. REFRESH … CONCURRENTLY needs a unique index.

  6. 6

    Functions run inside queries and cannot COMMIT; procedures are invoked with CALL and may commit when called outside a transaction block. Index and generated-column expressions must be IMMUTABLE.

  7. 7

    In dynamic SQL use format() with %I for identifiers and %L for literals, or better, EXECUTE … USING parameters.

Common traps

  • created BETWEEN '2024-05-01' AND '2024-05-31' on a timestamp column misses everything after midnight on the 31st; use a half-open range.

  • Comparing data->>'n' values compares text, so '10' < '9'. Cast to a number first.

  • round(2.5::float8) is 2 (half to even), while round(2.5) on numeric is 3.

Test yourself on Functions, Dates, Views and Procedures

Ten questions, with the answer and explanation after each one.