Sub topic 2
SQL Data Types in PostgreSQL
This chapter assumes you know basic SQL (SELECT, INSERT, CREATE TABLE), can run queries in psql, and understand tables, columns and constraints.
Boolean values and NULL
A boolean column holds TRUE, FALSE or NULL. NULL means unknown or missing. It is not zero or an empty string. Any comparison with NULL returns NULL, so PostgreSQL uses three-valued logic.
SELECT NULL = NULL AS equal_test,
NULL IS NULL AS is_null_test,
TRUE AND NULL AS and_result,
FALSE AND NULL AS and_false;The results are NULL, true, NULL and false. Test for missing values with IS NULL or IS NOT NULL. A WHERE clause drops rows whose condition is NULL, so WHERE is_paid = false skips rows where is_paid is NULL. Declare boolean columns NOT NULL DEFAULT false when a missing value has no meaning.
Dates, times, timestamps and intervals
A timestamptz value is a point in time. PostgreSQL converts the input to UTC, stores that instant, and converts it to the session time zone on output. A plain timestamp stores a wall-clock reading with no zone.
An interval is a duration.
SELECT '2026-01-15 12:00:00+00'::timestamptz AT TIME ZONE 'America/New_York' AS new_york_local,
'2026-01-15'::date + interval '3 days' AS later;The first column returns 2026-01-15 07:00:00. The second returns 2026-01-18 00:00:00.
Casting values between types
PostgreSQL converts some values implicitly, such as integer to numeric. Write explicit casts as CAST(value AS type) or value::type. A cast fails when the text cannot be parsed as the target type.
SELECT '42'::integer + 1 AS answer,
CAST('2026-01-15' AS date) AS d;
SELECT 'abc'::integer;
-- ERROR: invalid input syntax for type integer: "abc"UUIDs as identifiers
A UUID is a 128-bit identifier written as 32 hex digits in five groups. Clients can generate UUIDs without asking a central counter, which helps across multiple systems. The uuid type uses 16 bytes, less than the 36-character text form. Since PostgreSQL 13, gen_random_uuid() is built in.
CREATE TABLE sessions (
id uuid NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
user_email text NOT NULL,
started_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO sessions (user_email) VALUES ('[email protected]') RETURNING id;Random UUIDs are not ordered, so their indexes grow more fragmented than those of sequential bigint identity keys.
Exercises
Exercise
Why does SELECT NULL = NULL not return true, and how do you test for a missing value instead?
Show answer
Any comparison with NULL is unknown, so the result is NULL. Use IS NULL or IS NOT NULL.
Exercise
What does '2026-01-15 12:00:00+00'::timestamptz store, and what does it store for a plain timestamp?
Show answer
The timestamptz stores the UTC instant. A plain timestamp stores the wall-clock reading with no time zone.