Español Practice SQL

Dates in Oracle: ADD_MONTHS, TO_CHAR and EXTRACT

Oracle adds days with plain arithmetic and has functions for months and formats.

Dialects · Oracle

Practice this now

Free. No sign up. Your progress stays in this browser.

What you will learn

Oracle dates include a time part, so reports format or truncate them.

There is no YEAR() or MONTH(): use EXTRACT or TO_CHAR.

The basics

Oracle dates carry a time part, so reports often format or truncate them.

SELECT ADD_MONTHS(due_date, 1) AS next_month,
       TO_CHAR(due_date, 'YYYY-MM') AS month,
       EXTRACT(YEAR FROM due_date) AS year
FROM invoices

ADD_MONTHS moves a date by months; for days, add a number: due_date + 30. One date minus another gives the number of days. TRUNC(date, 'MM') gives the first day of the month. Oracle has no YEAR() or MONTH(): use EXTRACT.

Worked examples

Example 1

Invoices per month, as YYYY-MM.

SELECT TO_CHAR(due_date, 'YYYY-MM') AS month, COUNT(*)
FROM invoices
GROUP BY TO_CHAR(due_date, 'YYYY-MM')
ORDER BY month

Repeat the expression in GROUP BY.

Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.

Try a task

Common mistakes

  • Using DATEADD or DATEDIFF, which Oracle does not have.
  • Comparing dates that carry a time with a plain date and missing rows.
  • Using the alias in GROUP BY.

Where you will use it at work

  • Finance: month end reports.
  • HR: anniversaries with ADD_MONTHS.
  • Operations: shipments per week.

Questions people ask

How do I add days?

due_date + 30.

How do I get the days between two dates?

Subtract one from the other: end_date minus start_date.

What does TRUNC do on a date?

TRUNC(d) removes the time; TRUNC(d, 'MM') gives the first day of the month.

Ready to write it yourself?

Practice Dates in Oracle

Related guides

SQL Practice is independent and not affiliated with the maker of this database. The exercises run on SQLite in your browser and imitate this dialect’s syntax for practice.