…
…
SQL and Database Fundamentals · Lesson 27 / 41 · Type, text, and date conversions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The student office wants to send birthday greetings to students whose birthday is this month, work out how many years each instructor has served, see how many days each term lasts, and prepare a monthly enrollment report. Every one of these calculations uses the date columns of the report.
In this unit you learn to clean and transform data. In lesson 25 you converted types, and in lesson 26 you fixed text. Now it is time for a column that appears in almost every report: dates. Questions like "Whose birthday is this month?", "How many years has this instructor worked here?", and "How many enrollments were made each month?" all look at a date column. Working with dates has rules of its own: you can subtract two dates, but the result is a number of days; adding a month is different from adding days; and the shortcut for calculating age sometimes gives a wrong answer. In this lesson you will see these rules one by one, with the real data of the case.
In this lesson you will:
All the dates in the case database have the DATE type: a student's birth date and enrollment date, an instructor's hire date, the start and end of each term, and the date of each enrollment. DATE holds only the year, month, and day. If you also need hours, minutes, and seconds, you use the TIMESTAMP type, for example for the exact moment an order was placed. Our case has no time of day, so in this lesson you always work with DATE.
A date is written like text in single quotes, in year-month-day order: '2026-11-24'. This is the ISO format, and it is the one to use in your queries. You already used it in lesson 4 when you wrote enrollment_date >= '2026-09-01'; PostgreSQL converted the quoted text to the type of the column it was compared with, which is a date. When you want to say clearly that a value is a date, there are two ways to write it: DATE '2026-11-24', or '2026-11-24'::date with the conversion from lesson 25. Both produce the same date. In this lesson we will use the DATE '...' form for dates that stand alone.
In a real report you write CURRENT_DATE to say "today"; its type is date. If you also need the time, you use NOW(); its type is timestamp with time zone, which is a date and time together with a time zone. The value of both changes with the day the query runs: the same query can show age 17 today and age 18 tomorrow. So that the examples and exercises in this lesson give everyone the same result, we use a fixed date as "today": DATE '2026-11-24'. In a real report, you only need to write CURRENT_DATE in its place.
When you subtract one date from another, you get the number of days between them, and this number is an integer (integer). To see how many days each term lasts, subtract the start from the end.
Example 1 (case): Term lengths
SELECT name, start_date, end_date, end_date - start_date AS days FROM term;
| name | start_date | end_date | days |
|---|---|---|---|
| 2025-Fall | 2025-09-22 | 2026-01-16 | 116 |
| 2026-Spring | 2026-02-16 | 2026-06-12 | 116 |
| 2026-Fall | 2026-09-21 | 2027-01-15 | 116 |
(3 rows)
All three terms last 116 days. If you ask for the type of the days column with pg_typeof(end_date - start_date), the answer is integer: the difference is an ordinary number, not a date. So you can add it up, average it, or compare it with a number. You calculate a single difference the same way. Try to predict the answer to "How many days from today until the end of the year?"
What does this query return?
SELECT DATE '2026-12-31' - DATE '2026-11-24';
The order of subtraction matters. If you subtract the earlier date from the later date, you get a positive number; if you do it the other way around, you get a negative number. There is no error message; the query quietly returns a negative value.
What happens if you write the subtraction in Example 1 the other way around?
SELECT name, start_date - end_date FROM term;
Adding an integer to a date moves it forward by that many days: DATE '2026-11-24' + 30 gives 2026-12-24. For units whose length changes, such as months and years, you use an INTERVAL: INTERVAL '1 month' means one month, and INTERVAL '15 years' means fifteen years. DATE '2026-11-24' + INTERVAL '1 month' also gives 2026-12-24, but adding an INTERVAL turns the result into a timestamp (timestamp). If you only want a date, you convert the result back with ::date: (DATE '2026-11-24' + INTERVAL '1 month')::date. Subtraction works the same way: DATE '2026-11-24' - INTERVAL '15 years' gives the date fifteen years earlier, which is November 24, 2011. You write a condition like "people who have worked for more than 15 years" with it: WHERE hire_date < DATE '2026-11-24' - INTERVAL '15 years'.
"One month later" does not always point to the same day. Because months have different lengths, if the target month does not have that day, PostgreSQL moves to the last day of the month.
What date do you get when you add one month to January 31, 2026?
SELECT (DATE '2026-01-31' + INTERVAL '1 month')::date;
You often need only the year, month, or day of a date: "people born this month", "enrollments by year", "things done on weekends". The EXTRACT function pulls the part you want out of a date as a number. You write it as EXTRACT(part FROM date); the part is written by its English name.
| Expression | Result | What it gives |
|---|---|---|
EXTRACT(YEAR FROM DATE '2026-11-24') | 2026 | Year |
EXTRACT(MONTH FROM DATE '2026-11-24') | 11 | Month (1–12) |
EXTRACT(DAY FROM DATE '2026-11-24') | 24 | Day of the month (1–31) |
EXTRACT(ISODOW FROM DATE '2026-11-24') | 2 | Day of the week: Monday is 1, Sunday is 7 (2 = Tuesday) |
The type EXTRACT returns is numeric, a number that can have decimals. In comparisons and grouping it behaves like an ordinary number: WHERE EXTRACT(MONTH FROM birth_date) = 11 returns the students born in November. The "ISO" in ISODOW refers to the international way of counting in which the week starts on Monday; in this count the weekend is 6 (Saturday) and 7 (Sunday).
You can give the number EXTRACT produces an alias and group by it, as in lesson 12. Suppose the president's office asks in which years the students were born.
Example 2 (case): Number of students by birth year
SELECT EXTRACT(YEAR FROM birth_date) AS birth_year, COUNT(*) AS students FROM student GROUP BY birth_year ORDER BY birth_year;
| birth_year | students |
|---|---|
| 2004 | 9 |
| 2005 | 20 |
| 2006 | 31 |
| 2007 | 35 |
| 2008 | 21 |
| 2009 | 4 |
(6 rows)
Most students were born in 2006 and 2007. The same function works in WHERE too. If you sort the students born in November by day of the month for the student office's greeting list, 9 people come back: at the top of the list is Amara Santos, born on November 13, and at the end are two students born on November 30, Victor Abara and Greta Cohen. Run the query in the cell below, then try two changes.
Try it now· not graded; doesn't affect progress
There are 15 students born in December. When you group by month, the busiest month is August with 16 students (8); December comes next with 15. We wrote last_name as the second sort key because some students share a birthday: two people were born on November 15 and two on November 30, and without a second key the order between them might not be the same on every run.
When you want to see the difference between two dates not in days but as "how many years, how many months, how many days", you use the AGE function. AGE(end, start) calculates the difference by the calendar and returns an interval (interval): the later date is written first, then the earlier date. For full years of age, you take the year part of this interval with EXTRACT.
Example 3 (case): Students' ages
SELECT first_name, last_name, birth_date, AGE(DATE '2026-11-24', birth_date) AS diff, EXTRACT(YEAR FROM AGE(DATE '2026-11-24', birth_date)) AS age FROM student ORDER BY id LIMIT 4;
| first_name | last_name | birth_date | diff | age |
|---|---|---|---|---|
| Anika | Park | 2004-12-06 | 21 years 11 mons 18 days | 21 |
| Anika | Rivera | 2006-07-03 | 20 years 4 mons 21 days | 20 |
| Felix | Abara | 2007-10-02 | 19 years 1 mon 22 days | 19 |
| Isabella | Popescu | 2006-02-04 | 20 years 9 mons 20 days | 20 |
(4 rows)
The diff column is written with English units: years, mons for months, and days. Anika Park's 22nd birthday is on December 6; on November 24 she is still 21, and AGE shows this correctly.
The shortcut that comes to mind for calculating age is to divide the number of days by 365. For most students this also gives the right result, but because of leap years (years with 366 days), it can show one year too many for people whose birthday is a few days away. Among the 120 students in the case, the only person for whom the two methods differ is Elena Larsen: she was born on November 26, 2008, and on November 24, 2026 her 18th birthday is two days away. Compare the two ways step by step:
| Step | AGE way | Division way |
|---|---|---|
| 1 | AGE(DATE '2026-11-24', DATE '2008-11-26') | DATE '2026-11-24' - DATE '2008-11-26' |
| 2 | 17 years 11 mons 28 days | 6572 (days) |
| 3 | EXTRACT(YEAR FROM ...) | 6572 / 365 |
| 4 | 17 | 18 (integer division, lesson 25) |
The division way counts every year as 365 days. But 4 leap years have passed since Elena was born (2012, 2016, 2020, 2024); for a full 18 years to pass, you need 18 × 365 + 4 = 6574 days. Elena's 6572 days are not enough, but because it is more than 18 × 365 = 6570, the division gives 18. AGE looks at the calendar: if November 26 has not come, the 18th birthday has not come either.
Put the steps that calculate Elena Larsen's age on November 24, 2026 with AGE in the order they run.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same method works for years of service, subscription length, and warranty length. If you calculate the instructors' years of service with EXTRACT(YEAR FROM AGE(DATE '2026-11-24', hire_date)), the longest-serving are Liam Reyes (2005-02-01) and Camila Singh (2005-09-01) with 21 years; Fatima Kowalski and Rafael Popescu come next with 19 years.
For a monthly report you need to reduce each date to a single representative of its month; September 3 and September 28 must fall into the same bucket. DATE_TRUNC rounds a date down to the start of the unit you want: DATE_TRUNC('month', DATE '2026-11-24') gives the first day of the month, 2026-11-01. If you write 'year', it rounds down to the first day of the year. DATE_TRUNC also returns a value with a time of day, so converting the result with ::date makes it easier to read.
Example 4 (case): Enrollments by month
SELECT DATE_TRUNC('month', enrolled_on)::date AS month, COUNT(*) AS enrollments FROM enrollment GROUP BY month ORDER BY month;
| month | enrollments |
|---|---|
| 2025-09-01 | 233 |
| 2026-02-01 | 238 |
| 2026-09-01 | 310 |
(3 rows)
Course enrollments were made in only three months: the month each term started. In Fall 2026 the number of enrollments clearly went up. You can write the same report with TO_CHAR too. TO_CHAR converts a date to text according to the pattern you give: YYYY is the four-digit year, MM the two-digit month, and DD the two-digit day. TO_CHAR(enrolled_on, 'YYYY-MM') converts each date into text like 2026-09, and dates in the same month produce the same text. If you group the school enrollment dates in the student table this way, 8 rows come back: 13 students in 2023-08, 8 in 2023-09, ..., and 18 in 2026-09.
There is a trap in grouping: if you write EXTRACT(MONTH FROM enrolled_on) to group by month, the same months of different years merge. In the enrollment table this gives two rows: February 238, September 543. September 2025 and September 2026 fall into the same bucket. In a monthly report you use DATE_TRUNC or 'YYYY-MM', which also carry the year. Now match the tools you have seen in this lesson with their results.
Match each expression with the result it gives.
For each row, pick its match from the list, then check.
EXTRACT(MONTH FROM DATE '2026-11-24')DATE_TRUNC('month', DATE '2026-11-24')::dateTO_CHAR(DATE '2026-11-24', 'MM/DD/YYYY')DATE '2026-11-24' + 30EXTRACT(ISODOW FROM DATE '2026-11-24')Reports often need dates to look the way readers are used to. In the United States that is 11/24/2026 (month/day/year), and in long form it is November 24, 2026. TO_CHAR(birth_date, 'MM/DD/YYYY') gives the first, and TO_CHAR(birth_date, 'FMMonth FMDD, YYYY') gives the second (FM removes the extra spaces TO_CHAR adds). But the result of TO_CHAR is a text value, and text is sorted character by character: first the first character, then the second if the first are equal. If you sort by the formatted column, the calendar order breaks, because the year comes last.
OutputSELECT first_name, TO_CHAR(birth_date, 'MM/DD/YYYY') AS date
FROM student
ORDER BY date
LIMIT 4;
Aisha 01/04/2005
Liam 01/08/2007
Omar 01/16/2008
Yusuf 01/21/2008These four people are not the oldest; they are only the people born in January, because the month comes first. If you sort by the date itself, with ORDER BY birth_date, you get the correct order: Pablo (08/20/2004), Nikolai (09/30/2004), Rosa (10/11/2004), Zara (10/18/2004). The ISO format 'YYYY-MM-DD' does not have this problem, because the largest unit comes first: as text it sorts in calendar order. That is why ISO is the safest format to store, compare, and exchange dates. The rule: calculate, compare, and sort with the date itself; use TO_CHAR only at the very end, for display.
Which of these four text values comes first when sorted with ORDER BY?
'03/12/2026' '11/25/2025' '01/08/2027' '06/30/2026'
One more note: in this working environment, month names come out in English. The result of TO_CHAR(DATE '2026-11-24', 'FMMonth') is November. You can use it to put the month name in a report next to the sortable 'YYYY-MM' text; you will see an example in the Examples section below.
A situation the cleaning unit often meets: a table where dates are stored as text like '11/24/2026', for example a list moved as-is from a spreadsheet. In such a column, difference calculations, correct sorting, and EXTRACT do not work. The :: conversion from lesson 25 is risky here too, because PostgreSQL has to guess which number is the month and which is the day, and it guesses by a setting (DateStyle). In this environment the setting is month first, so '11/24/2026'::date happens to work. But '03/04/2026'::date gives March 4, even if the person who typed it meant April 3. And a date written day first fails with this error:
OutputSELECT '24/11/2026'::date;
ERROR: date/time field value out of range: "24/11/2026"A wrong guess without an error is worse than an error, because nobody notices it. The reliable way is the TO_DATE function, where you tell it the pattern of the text: TO_DATE('11/24/2026', 'MM/DD/YYYY') gives the date 2026-11-24, and it reads '03/04/2026' as March 4 only because you said so. The pattern is the same as the one in TO_CHAR; TO_CHAR converts from a date to text, and TO_DATE converts from text to a date. The permanent fix is to store the column as DATE from the start, and to write dates in the ISO format when you exchange them; you will see table design in the next unit.
The expression you group by does not have to be a column; the result of a function can be one too. With LEFT from lesson 26, you can take the first three letters of the course codes, which is the department prefix, and group by it.
Example 5 (case): Number of courses by department prefix
SELECT LEFT(code, 3) AS prefix, COUNT(*) AS courses FROM course GROUP BY prefix ORDER BY courses DESC, prefix;
| prefix | courses |
|---|---|
| BUS | 5 |
| CPR | 5 |
| SWE | 5 |
| GEN | 4 |
| IND | 4 |
| MIS | 4 |
| NMC | 3 |
| PSY | 3 |
(8 rows)
Grouping by date uses the same pattern: write the expression in SELECT, give it an alias, and use that alias in GROUP BY. Suppose the student office wants "the number of students who enrolled in 2026, by month". Put the lines of the query in the correct order; then, if you like, run it in a cell (two rows come back: 2026-08 11, 2026-09 18).
Put the lines of the query that gives the number of students who enrolled in 2026, by month, in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Notice the last explanation: text in the 'YYYY-MM' or 'YYYY-MM-DD' format sorts correctly, because the largest unit (the year) is on the far left and the month is written with two digits. The problem is with formats that put something else first, like 'MM/DD/YYYY'.
Date functions work the same way in every database. In the Earbud music app database (earbud.sql) that you will use in the last exercise, the table play(id, listener_id, song_id, played_on, seconds_played) keeps each play as one row; the played_on column has the DATE type. The plays are between September 1, 2026 and November 30, 2026.
Example 6 (outside the case): Number of plays by month
SELECT TO_CHAR(played_on, 'YYYY-MM') AS month, COUNT(*) AS plays FROM play GROUP BY month ORDER BY month;
| month | plays |
|---|---|
| 2026-09 | 79 |
| 2026-10 | 82 |
| 2026-11 | 56 |
(3 rows)
There are 217 plays in total. The product team also wants to know how many of them happened on weekends. To find the weekend, you need to choose the part that gives the day of the week.
Which condition is correct for finding the plays made on weekends?
You can see in one row what the tools from this lesson give for the same date.
SELECT EXTRACT(MONTH FROM DATE '2026-11-24') AS month, DATE '2026-11-24' + 30 AS in_30_days, (DATE '2026-11-24' + INTERVAL '1 month')::date AS in_one_month, DATE_TRUNC('month', DATE '2026-11-24')::date AS month_start, TO_CHAR(DATE '2026-11-24', 'MM/DD/YYYY') AS us_format, TO_CHAR(DATE '2026-11-24', 'FMMonth FMDD, YYYY') AS long_format;
| month | in_30_days | in_one_month | month_start | us_format | long_format |
|---|---|---|---|---|---|
| 11 | 2026-12-24 | 2026-12-24 | 2026-11-01 | 11/24/2026 | November 24, 2026 |
(1 row)
Writing a date without quotes.
OutputSELECT first_name, enrollment_date
FROM student
WHERE enrollment_date > 2026-01-01;
-- ERROR: operator does not exist: date > integerPostgreSQL reads the unquoted 2026-01-01 as a subtraction: 2026 minus 1 minus 1, which is the number 2024. Then it tries to compare a date with an integer and cannot find an operator for it. The date > integer in the message says exactly this: there is a date on the left and an integer on the right. Dates are always written in single quotes: '2026-01-01'.
+ n adds days, and + INTERVAL '1 month' adds a month and can land on the last day of the month. For full age and years of service, use EXTRACT(YEAR FROM AGE(end, start)); dividing the day difference by 365 can show one year too many for people close to their birthday.EXTRACT(YEAR | MONTH | DAY | ISODOW FROM date) gives a part as a number; you filter and group with that number. In a monthly report, use DATE_TRUNC('month', ...) or TO_CHAR(..., 'YYYY-MM'), which also carry the year; the month number alone merges different years.TO_CHAR turns a date into text for display (MM/DD/YYYY, FMMonth FMDD, YYYY), and TO_DATE turns text into a date with a pattern you state. Sorting and calculation use the date itself; dates are written in quotes and, to avoid any guess, in the ISO year-month-day order.In this unit you saw three cleaning jobs: converting types, fixing text, and calculating with dates. Now you can read and fix data. As the unit task, you can prepare the sales report of Corner Café.
Next lesson: next you will build the tables that hold the data yourself; you start the table creation and database design unit.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
You get the month name with TO_CHAR; the month text ('YYYY-MM') stays for sorting.
SELECT TO_CHAR(enrolled_on, 'YYYY-MM') AS month, TO_CHAR(enrolled_on, 'FMMonth') AS month_name, COUNT(*) AS enrollments FROM enrollment GROUP BY month, month_name ORDER BY month;
| month | month_name | enrollments |
|---|---|---|
| 2025-09 | September | 233 |
| 2026-02 | February | 238 |
| 2026-09 | September | 310 |
(3 rows)
The month name is only for the reader; sorting is done with the 'YYYY-MM' text, because sorting by month names would put April before February. If you need the month name in another language, you can turn the month number into a name with the CASE from lesson 8.