PostgreSQL
Beginner
1 min read
Date, Time, UUID, and Array Types
Example
-- Temporal types
CREATE TABLE events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_date DATE NOT NULL,
starts_at TIMETZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
duration INTERVAL
);
-- Insert with various date literals
INSERT INTO events (event_date, starts_at, duration)
VALUES
('2024-06-15', '14:30:00+00', INTERVAL '2 hours 30 minutes'),
(CURRENT_DATE, NOW()::TIME, '90 minutes');
-- Date arithmetic
SELECT
NOW() + INTERVAL '7 days' AS next_week,
NOW() - INTERVAL '1 month' AS last_month,
AGE(TIMESTAMP '2024-01-01', NOW()) AS time_since,
DATE_TRUNC('month', NOW()) AS start_of_month,
EXTRACT(DOW FROM NOW()) AS day_of_week; -- 0=Sun
-- Array type
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT,
tags TEXT[], -- array of text
scores INTEGER[] -- array of integers
);
INSERT INTO users (name, tags, scores)
VALUES ('Alice', ARRAY['admin', 'editor'], ARRAY[95, 87, 92]);
-- Array operators
SELECT * FROM users WHERE 'admin' = ANY(tags);
SELECT name, tags[1] AS first_tag FROM users;
SELECT name, array_length(scores, 1) AS num_scores FROM users;
Related Resources
PostgreSQL Reference
Complete tag & property list
PostgreSQL How-To Guides
Step-by-step practical guides
PostgreSQL Exercises
Practice what you've learned
More in PostgreSQL