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
String positions are 1-based.
lengthcounts characters andoctet_lengthcounts bytes, which differ for UTF-8 text. - 2
||returns NULL if either side is NULL;concatandconcat_wsskip NULLs. Integer/truncates, andmod/%take the sign of the dividend. - 3
timestamptzstores an instant and displays it in the session TimeZone;timestampstores wall-clock time.AT TIME ZONEconverts between them in both directions. - 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
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
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
In dynamic SQL use
format()with%Ifor identifiers and%Lfor literals, or better,EXECUTE … USINGparameters.
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), whileround(2.5)on numeric is 3.
Read the source
Test yourself on Functions, Dates, Views and Procedures
Ten questions, with the answer and explanation after each one.