Dates and Times in SQL: Types, Current Time, Parts, Formatting and Time Zones
How SQL represents dates and times: DATE, TIME, TIMESTAMP and TIMESTAMP WITH TIME ZONE, literals, the current date and time, EXTRACT and DATE_TRUNC, formatting and parsing with TO_CHAR and TO_DATE, time zones and AT TIME ZONE, daylight saving time, and the equivalents in each database.
kvi5hnuCode Sprout team member12 min readOn this page
Dates and times look simple until you have to use them: which day of the week is day 0? Which week does 31 December belong to? Is 09 in the database 09 for the user in Mumbai? What happens to "one hour later" when the clocks go forward?
This article covers the date and time types, getting the current time, taking dates apart and rounding them, turning them into text and back, and time zones. Article 40 covers date arithmetic, adding intervals and measuring differences, and article 41 covers calendars and date series. Date functions differ more between databases than anything else in SQL, so each section ends with the equivalents.
Date and time types and literals
| Type | Holds | PostgreSQL literal |
|---|---|---|
DATE | a calendar day | DATE '2026-03-05' |
TIME | a time of day | TIME '14:30:00' |
TIMESTAMP | a date and time, with no time zone | TIMESTAMP '2026-03-05 14:30:00' |
TIMESTAMP WITH TIME ZONE (timestamptz) | an absolute moment | TIMESTAMPTZ '2026-03-05 14:30:00+01' |
INTERVAL | a duration | INTERVAL '1 day 2 hours' |
-- Date and time literals use ISO 8601: year-month-day
SELECT DATE '2026-03-05' AS a_date,
TIME '14:30:00' AS a_time,
TIMESTAMP '2026-03-05 14:30:00' AS a_timestamp,
INTERVAL '1 day 2 hours' AS an_interval;
-- Impossible dates are rejected
SELECT DATE '2026-02-29'; -- 2026 isn't a leap year
SELECT DATE '2028-02-29' AS leap_day;
a_date | a_time | a_timestamp | an_interval
------------+----------+---------------------+----------------
2026-03-05 | 14:30:00 | 2026-03-05 14:30:00 | 1 day 02:00:00
(1 row)
psql:/workspace/solution.sql:8: ERROR: date/time field value out of range: "2026-02-29"
LINE 1: SELECT DATE '2026-02-29';
^
leap_day
------------
2028-02-29
(1 row)
Write dates in ISO 8601 format, YYYY-MM-DD, with a type keyword in front. Every database understands it, and it's unambiguous: 03/05/2026 is 3 May in most of the world and 5 March in the United States, but 2026-03-05 is always 5 March. Date types also validate: 29 February 2026 doesn't exist, so it's rejected, while 29 February 2028 is a leap day.
Timestamps can store fractions of a second: PostgreSQL, MySQL (DATETIME(6)) and SQL Server (DATETIME2(7)) go down to microseconds or finer.
| Purpose | PostgreSQL | MySQL | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| date | date | DATE | date | DATE (includes a time!) | text 'YYYY-MM-DD' |
| date and time | timestamp | DATETIME | datetime2 | TIMESTAMP | text 'YYYY-MM-DD HH:MM:SS' |
| instant | timestamptz | TIMESTAMP (stored as UTC, range ends in 2038) | datetimeoffset | TIMESTAMP WITH TIME ZONE | text or Unix time |
Two traps in that table: Oracle's DATE includes a time of day, so WHERE order_date = DATE '2026-03-05' misses rows stored with a time. And SQLite has no date types at all. It stores dates as text, real or integer values, and its date functions work on ISO 8601 text, which is why dates in SQLite must always be written in that format.
The current date and time
| Function | Returns |
|---|---|
CURRENT_DATE | today's date |
CURRENT_TIMESTAMP or now() | the current date and time, with time zone |
LOCALTIMESTAMP | the current date and time, without time zone |
clock_timestamp() | the actual current time, changing during a statement |
-- now() and CURRENT_TIMESTAMP are fixed for the whole transaction;
-- clock_timestamp() keeps moving
BEGIN;
SELECT pg_sleep(0.1) AS pause_a_moment;
SELECT now() = CURRENT_TIMESTAMP AS now_is_current_timestamp,
now() = transaction_timestamp() AS now_is_transaction_start,
now() < statement_timestamp() AS statement_started_later,
now() < clock_timestamp() AS clock_has_moved,
pg_typeof(now()) AS now_type,
pg_typeof(CURRENT_DATE) AS current_date_type,
pg_typeof(LOCALTIMESTAMP) AS localtimestamp_type;
COMMIT;
pause_a_moment
----------------
(1 row)
now_is_current_timestamp | now_is_transaction_start | statement_started_later | clock_has_moved | now_type | current_date_type | localtimestamp_type
--------------------------+--------------------------+-------------------------+-----------------+--------------------------+-------------------+-----------------------------
t | t | t | t | timestamp with time zone | date | timestamp without time zone
(1 row)
In PostgreSQL, now() and CURRENT_TIMESTAMP return the time the transaction started, and they keep returning it for the whole transaction. Every row inserted in one transaction gets the same timestamp, which is usually what you want: the rows were created "together". statement_timestamp() is the start of the current statement, and clock_timestamp() the real time at the moment it's called, which advances even within one statement.
The equivalents: MySQL has CURDATE(), NOW() (statement start) and SYSDATE() (actual time). SQL Server has GETDATE(), SYSDATETIME() and SYSDATETIMEOFFSET(), all returning the actual time. Oracle has SYSDATE and SYSTIMESTAMP (the server's time) and CURRENT_DATE and CURRENT_TIMESTAMP (the session's time zone). SQLite has date('now') and datetime('now'), in UTC.
The current time makes query results change from run to run, which is why the examples in this course use fixed dates.
Taking dates apart: EXTRACT
EXTRACT(field FROM value) returns one part of a date or timestamp as a number:
-- Parts of a date or timestamp with EXTRACT
SELECT ts,
EXTRACT(YEAR FROM ts) AS year,
EXTRACT(QUARTER FROM ts) AS quarter,
EXTRACT(MONTH FROM ts) AS month,
EXTRACT(DAY FROM ts) AS day,
EXTRACT(DOW FROM ts) AS dow, -- 0 = Sunday
EXTRACT(ISODOW FROM ts) AS isodow, -- 7 = Sunday
EXTRACT(DOY FROM ts) AS day_of_year,
EXTRACT(WEEK FROM ts) AS iso_week,
EXTRACT(HOUR FROM ts) AS hour
FROM (VALUES (TIMESTAMP '2026-03-08 14:30:00'),
(TIMESTAMP '2026-12-31 23:59:00'),
(TIMESTAMP '2027-01-01 00:15:00')) AS t(ts);
ts | year | quarter | month | day | dow | isodow | day_of_year | iso_week | hour
---------------------+------+---------+-------+-----+-----+--------+-------------+----------+------
2026-03-08 14:30:00 | 2026 | 1 | 3 | 8 | 0 | 7 | 67 | 10 | 14
2026-12-31 23:59:00 | 2026 | 4 | 12 | 31 | 4 | 4 | 365 | 53 | 23
2027-01-01 00:15:00 | 2027 | 1 | 1 | 1 | 5 | 5 | 1 | 53 | 0
(3 rows)
Most fields are what you'd expect, but a few need care:
- Day of week:
DOWnumbers Sunday as 0 and Saturday as 6.ISODOWfollows ISO 8601, with Monday as 1 and Sunday as 7. Other databases have their own numbering: MySQL'sDAYOFWEEKgives Sunday 1, itsWEEKDAYgives Monday 0, and SQL Server'sDATEPART(weekday, ...)depends on theDATEFIRSTsetting. Always check which convention a function uses. - Week:
WEEKis the ISO week number. ISO weeks start on Monday, and week 1 is the week containing the year's first Thursday. So 31 December 2026 is in week 53 of 2026, and so is 1 January 2027. When grouping by ISO week, combine it with the ISO year,ISOYEAR, not the calendar year, or the days of week 53 end up split between two years. - Epoch:
EXTRACT(EPOCH FROM ts)gives the number of seconds since 1970-01-01 00 UTC, the Unix time.
EXTRACT with YEAR, MONTH, DAY, HOUR, MINUTE and SECOND works in PostgreSQL, MySQL and Oracle. DOW, ISODOW, DOY, ISOYEAR and EPOCH are PostgreSQL extensions. SQL Server uses DATEPART(month, d), and DATENAME(weekday, d) for names. SQLite uses strftime('%m', d), which returns text.
Rounding dates: DATE_TRUNC
DATE_TRUNC(unit, value) rounds a timestamp down to the start of a year, quarter, month, week, day, hour or minute. It's the tool for grouping by period:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- DATE_TRUNC: round down to the start of a month, week or hour
SELECT DATE_TRUNC('month', TIMESTAMP '2026-03-18 14:30:00') AS month_start,
DATE_TRUNC('week', TIMESTAMP '2026-03-18 14:30:00') AS week_start, -- Monday
DATE_TRUNC('hour', TIMESTAMP '2026-03-18 14:30:00') AS hour_start;
-- ...which is how you group by month or by week
SELECT CAST(DATE_TRUNC('week', placed_on) AS date) AS week_starting,
COUNT(*) AS orders
FROM orders
GROUP BY DATE_TRUNC('week', placed_on)
ORDER BY week_starting;
month_start | week_start | hour_start
---------------------+---------------------+---------------------
2026-03-01 00:00:00 | 2026-03-16 00:00:00 | 2026-03-18 14:00:00
(1 row)
week_starting | orders
---------------+--------
2026-03-02 | 2
2026-03-09 | 2
2026-03-16 | 2
(3 rows)
DATE_TRUNC('week', ...) goes back to Monday, the ISO start of the week. The second query groups the orders into weeks. Grouping by DATE_TRUNC('month', placed_on) rather than EXTRACT(MONTH FROM placed_on) keeps March 2026 separate from March 2027, and the result is a real date that sorts and displays correctly.
For a date input, DATE_TRUNC returns a timestamp with time zone (the date is read in the session's time zone), hence the cast back to date for display.
Equivalents: SQL Server 2022 added DATETRUNC(month, d). Earlier versions use DATEFROMPARTS(YEAR(d), MONTH(d), 1) for the month. Oracle uses TRUNC(d, 'MM') and TRUNC(d, 'IW') for the ISO week. MySQL has no DATE_TRUNC: use DATE_FORMAT(d, '%Y-%m-01') for the month. SQLite uses date(d, 'start of month').
Formatting and parsing: TO_CHAR and TO_DATE
-- Formatting with TO_CHAR
SELECT TO_CHAR(TIMESTAMP '2026-03-08 14:05:09', 'YYYY-MM-DD HH24:MI:SS') AS iso,
TO_CHAR(TIMESTAMP '2026-03-08 14:05:09', 'DD/MM/YYYY') AS day_first,
TO_CHAR(TIMESTAMP '2026-03-08 14:05:09', 'FMDay, FMDD FMMonth YYYY') AS long_form,
TO_CHAR(TIMESTAMP '2026-03-08 14:05:09', 'Mon YY, HH12:MI AM') AS short_form,
TO_CHAR(TIMESTAMP '2026-03-08 14:05:09', 'IYYY-"W"IW') AS iso_week;
-- Parsing text in a known format with TO_DATE and TO_TIMESTAMP
SELECT TO_DATE('08/03/2026', 'DD/MM/YYYY') AS from_day_first,
TO_DATE('March 8, 2026', 'Month DD, YYYY') AS from_words,
TO_TIMESTAMP('2026-03-08 2:05 PM', 'YYYY-MM-DD HH12:MI AM')::timestamp AS from_12_hour;
iso | day_first | long_form | short_form | iso_week
---------------------+------------+----------------------+------------------+----------
2026-03-08 14:05:09 | 08/03/2026 | Sunday, 8 March 2026 | Mar 26, 02:05 PM | 2026-W10
(1 row)
from_day_first | from_words | from_12_hour
----------------+------------+---------------------
2026-03-08 | 2026-03-08 | 2026-03-08 14:05:00
(1 row)
TO_CHAR(value, format) turns a date or timestamp into text using a format pattern. The common pattern codes:
| Code | Meaning | Example |
|---|---|---|
YYYY, YY | year | 2026, 26 |
MM, Mon, Month | month number, short and long name | 03, Mar, March |
DD, Day, Dy | day of month, weekday name | 08, Sunday, Sun |
HH24, HH12, MI, SS, AM | hours, minutes, seconds, AM/PM | 14, 02, 05, 09, PM |
IYYY, IW | ISO year and ISO week | 2026, 10 |
FM | "fill mode": no padding for the next code | FMDay → Sunday without trailing spaces |
Text in double quotes is copied literally, as in "W". Month and Day are padded with spaces to a fixed width unless preceded by FM.
TO_DATE(text, format) and TO_TIMESTAMP(text, format) do the reverse: they parse text in a known format. Use them for imported data in non-ISO formats, such as 08/03/2026 from a European spreadsheet. A plain CAST('08/03/2026' AS date) depends on the DateStyle setting, so it might mean 3 August instead. TO_TIMESTAMP returns a timestamptz, so the example casts it to timestamp.
The same functions exist in Oracle, with almost the same codes. Elsewhere:
| Database | Format | Parse |
|---|---|---|
| MySQL | DATE_FORMAT(d, '%Y-%m-%d %H:%i') | STR_TO_DATE(s, '%d/%m/%Y') |
| SQL Server | FORMAT(d, 'yyyy-MM-dd') or CONVERT(varchar, d, 23) | CONVERT(date, s, 103) (style 103 = dd/mm/yyyy), TRY_PARSE |
| SQLite | strftime('%Y-%m-%d', d) | no parser: rearrange the text with substr |
Format dates for display in the application when possible, where the user's language and locale are known. Month and day names from the database come in the server's language.
Time zones
There are two ways to store a date and time:
TIMESTAMP(without time zone) stores a wall-clock reading: "09 on 1 July". It says nothing about where, so it's a different moment in London, Kolkata and New York.TIMESTAMP WITH TIME ZONEstores an instant: a single point in time. In PostgreSQL, it's converted to UTC on input and converted to the session's time zone for display. Despite its name, it doesn't store the time zone itself.

-- TIMESTAMP WITH TIME ZONE stores an instant; it's shown in the session's time zone
SET TIME ZONE 'UTC';
SELECT TIMESTAMPTZ '2026-07-01 09:00:00+02' AS stored_instant;
SET TIME ZONE 'Asia/Kolkata';
SELECT TIMESTAMPTZ '2026-07-01 09:00:00+02' AS same_instant_in_kolkata;
-- AT TIME ZONE converts in both directions
SET TIME ZONE 'UTC';
SELECT TIMESTAMPTZ '2026-07-01 07:00:00+00' AT TIME ZONE 'America/New_York' AS new_york_wall_clock,
TIMESTAMP '2026-07-01 09:00:00' AT TIME ZONE 'Europe/Paris' AS paris_9am_as_instant;
-- Daylight saving time: the clocks in London went forward at 01:00 UTC on 29 March 2026
SELECT TIMESTAMPTZ '2026-03-29 00:30:00+00' AT TIME ZONE 'Europe/London' AS before_change,
(TIMESTAMPTZ '2026-03-29 00:30:00+00' + INTERVAL '1 hour') AT TIME ZONE 'Europe/London' AS one_hour_later;
-- An offset in a zone name follows POSIX rules: 'UTC+5' means five hours WEST of UTC
SELECT TIMESTAMPTZ '2026-07-01 12:00:00+00' AT TIME ZONE 'UTC+5' AS posix_utc_plus_5,
TIMESTAMPTZ '2026-07-01 12:00:00+00' AT TIME ZONE 'Asia/Karachi' AS karachi;
stored_instant
------------------------
2026-07-01 07:00:00+00
(1 row)
same_instant_in_kolkata
---------------------------
2026-07-01 12:30:00+05:30
(1 row)
new_york_wall_clock | paris_9am_as_instant
---------------------+------------------------
2026-07-01 03:00:00 | 2026-07-01 07:00:00+00
(1 row)
before_change | one_hour_later
---------------------+---------------------
2026-03-29 00:30:00 | 2026-03-29 02:30:00
(1 row)
posix_utc_plus_5 | karachi
---------------------+---------------------
2026-07-01 07:00:00 | 2026-07-01 17:00:00
(1 row)
TIMESTAMPTZ '2026-07-01 09:00:00+02'is stored as 07 UTC. With the session's time zone set to UTC, it's shown as07:00:00+00. With the time zone set to Asia/Kolkata, the same value is shown as12:30:00+05:30.AT TIME ZONEconverts in both directions. Applied to atimestamptz, it gives the wall-clock time in that zone, as atimestamp: 07 UTC is 03 in New York. Applied to atimestamp, it interprets the wall-clock time as being in that zone and returns the instant: 09 in Paris in July is 07 UTC.- Daylight saving time: in London, the clocks went forward at 01 UTC on 29 March 2026, from 01 to 02 local time. An instant at 00 UTC is 00 in London, and one hour later, 01 UTC, is 02 in London. Arithmetic on
timestamptzvalues is done on real elapsed time, and the local display follows the zone's rules. - Offsets in zone names are inverted. In POSIX-style names such as
'UTC+5', a positive offset means west of Greenwich, so'UTC+5'is five hours behind UTC, the opposite of ISO 8601. 12 UTC is 07 in'UTC+5', but 17 in Karachi, which is UTC+05 in the usual notation.
Rules for time zones:
- Store events as
timestamptz(or UTC in atimestampcolumn, if your database lacks a proper type). An order placed at a moment should stay at that moment, whoever reads it. - Use plain
timestampordate+timefor wall-clock values that must not move: a shop's opening hours, or a meeting "at 09 local time" in the future, whose UTC instant depends on daylight saving rules that may change. - Use IANA zone names such as
'Europe/London'and'Asia/Kolkata', never abbreviations like'IST'(India, Ireland and Israel all use it) or fixed offsets, which don't follow daylight saving. - Convert to the user's zone at the edges: in the application, or with
AT TIME ZONEin reports.
Equivalents: MySQL's TIMESTAMP stores UTC and converts using the session's time_zone, and CONVERT_TZ(dt, 'UTC', 'Europe/London') converts explicitly (it needs the time zone tables loaded). SQL Server has datetimeoffset, which does store the offset, and AT TIME ZONE 'GMT Standard Time' with Windows zone names. Oracle has TIMESTAMP WITH TIME ZONE, which stores the zone, and TIMESTAMP WITH LOCAL TIME ZONE, which works like PostgreSQL's timestamptz. SQLite stores no zone: keep UTC and convert in the application.
Oracle's interval and time zone types
Oracle has two interval types instead of one, because months and days don't convert into each other exactly:
INTERVAL YEAR TO MONTHholds years and months:INTERVAL '1-6' YEAR TO MONTHis a year and a half.INTERVAL DAY TO SECONDholds days, hours, minutes and seconds:INTERVAL '2 10:30:00' DAY TO SECOND.
Subtracting two TIMESTAMPs gives a DAY TO SECOND interval, while subtracting two DATEs gives a number of days. PostgreSQL's single interval type stores months, days and seconds separately inside, for the same reason.
Oracle also has TIMESTAMP WITH LOCAL TIME ZONE: values are stored normalised to the database's time zone and shown in each session's time zone, like PostgreSQL's timestamptz. Oracle's TIMESTAMP WITH TIME ZONE, by contrast, keeps the original offset or region with each value.
What's current
- PostgreSQL 17 added
AT LOCAL, shorthand forAT TIME ZONEwith the session's current time zone. - SQL Server 2022 added
DATETRUNC,DATE_BUCKETandGENERATE_SERIES. - SQLite 3.38 added
unixepoch(), and 3.43 addedtimediff()and the'ceiling'and'floor'modifiers. - MySQL's
TIMESTAMPtype still ends at 2038-01-19 03:14 UTC. UseDATETIMEfor later dates.
Common questions
Should I store dates as text? No. Date types validate values, sort chronologically and support arithmetic. SQLite is the exception, where ISO 8601 text is the standard way.
What's the difference between now() and clock_timestamp() in PostgreSQL?
now() is the start of the current transaction and doesn't change within it. clock_timestamp() is the actual current time.
Why is 1 January in week 53? ISO weeks belong to the year that contains their Thursday. If 1 January falls on a Friday, Saturday or Sunday, it belongs to the last week of the previous ISO year.
timestamp or timestamptz?
timestamptz for moments when things happen. timestamp for wall-clock values, such as a recurring local time.
Does timestamptz store the time zone?
Not in PostgreSQL. It stores the UTC instant and displays it in the session's zone. If you need the original zone, store it in a separate column.
How do I group rows by month?
GROUP BY DATE_TRUNC('month', d) in PostgreSQL, DATETRUNC(month, d) in SQL Server 2022, TRUNC(d, 'MM') in Oracle, DATE_FORMAT(d, '%Y-%m') in MySQL.
Summary
DATE,TIME,TIMESTAMP,TIMESTAMP WITH TIME ZONEandINTERVALare the standard types. Write literals in ISO 8601 form.- Type names and behaviour differ: Oracle's
DATEhas a time, and SQLite stores dates as text. CURRENT_DATE,CURRENT_TIMESTAMPandnow()give the current time. In PostgreSQL,now()is fixed for the transaction.EXTRACTreturns parts of a date. Know which day-of-week numbering a function uses, and pair ISO weeks with ISO years.DATE_TRUNCrounds down to the start of a period and is the way to group by month or week.TO_CHARformats dates, andTO_DATEandTO_TIMESTAMPparse text in a known format.- Store moments as
timestamptz, use IANA zone names, and convert withAT TIME ZONE.
Practice questions
What do EXTRACT(DOW FROM DATE '2026-03-08') and EXTRACT(ISODOW FROM DATE '2026-03-08') return, and why are they different?
Answer
0 and 7. 8 March 2026 is a Sunday. DOW numbers Sunday as 0, and ISODOW follows ISO 8601, where Monday is 1 and Sunday is 7.
Write a query that counts the orders placed in each month, showing the month as 2026-03.
Answer
SELECT TO_CHAR(DATE_TRUNC('month', placed_on), 'YYYY-MM') AS month,
COUNT(*) AS orders
FROM orders
GROUP BY DATE_TRUNC('month', placed_on)
ORDER BY DATE_TRUNC('month', placed_on);
All six orders are in March 2026, so it returns one row: 2026-03, 6.
A CSV file contains dates like 31/12/2026. How do you convert them in PostgreSQL, and why not just CAST?
Answer
TO_DATE(text, 'DD/MM/YYYY'). A cast interprets the text according to the DateStyle setting, so the same text could be read as month-first, or rejected. TO_DATE with an explicit format always reads it the same way.
A meeting is stored as TIMESTAMPTZ '2026-11-02 15:00:00+00'. Write an expression that shows its local start time in New York.
Answer
TIMESTAMPTZ '2026-11-02 15:00:00+00' AT TIME ZONE 'America/New_York'
It returns 2026-11-02 10:00:00. New York's daylight saving time ended on 1 November 2026, so the city is 5 hours behind UTC.
Why is WHERE created_at = DATE '2026-03-05' likely to miss rows when created_at is a timestamp?
Answer
The date is converted to the timestamp 2026-03-05 00:00:00, so only rows created exactly at midnight match. Use a half-open range: WHERE created_at >= DATE '2026-03-05' AND created_at < DATE '2026-03-06', which also lets an index on created_at be used.
Previous: Numbers in SQL: Rounding, Division, Median, Mode and Percentiles
Next: Date Arithmetic in SQL: Adding Intervals and Measuring Differences

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.