SQL MONTHS_BETWEEN function
Returns the number of months from one date to another. Oracle's version returns a fraction; on the other engines you build it from DATEDIFF, age() or TIMESTAMPDIFF.
- Category
- Dates & times
- Returns
numeric (fractional on Oracle)- In this category
- 12 of 121
Syntax
MONTHS_BETWEEN(later, earlier) -- Oracle
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | DATEDIFF(month, a, b) counts boundaries, not fractions |
| PostgreSQL | Different name or syntax | age(b, a) plus arithmetic, or EXTRACT(year/month) |
| MySQL | Different name or syntax | PERIOD_DIFF or TIMESTAMPDIFF(month, a, b) |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Yes | Supported under this name. |
Examples
Oracle
SELECT MONTHS_BETWEEN(SYSDATE, hire_date) AS tenure_months FROM employees;
SQL Server
SELECT DATEDIFF(month, hire_date, SYSDATETIME()) AS tenure_months FROM employees;
PostgreSQL
SELECT (EXTRACT(year FROM age(now(), hired_at)) * 12
+ EXTRACT(month FROM age(now(), hired_at))) AS tenure_months
FROM employees;
Good to know
- Oracle returns a fraction when the days of the month differ, always dividing the leftover days by 31: MONTHS_BETWEEN(DATE '2026-03-15', DATE '2026-01-31') is 1.4839. SQL Server's DATEDIFF(month, ...) for the same dates is 2, and MySQL's TIMESTAMPDIFF(MONTH, ...) is 1.
- Argument order: Oracle is (later, earlier) and returns positive forward; flip them and get a negative. DATEDIFF(month, a, b) on SQL Server is (start, end).
- PostgreSQL's age(b, a) gives years and months as separate fields, which is friendlier for billing periods.
Questions about MONTHS_BETWEEN
Why does MONTHS_BETWEEN return a decimal?
Oracle counts whole months, then adds the leftover days divided by 31, whatever the month's real length: 15 leftover days add 0.48. If both dates fall on the same day of the month, or both on a month's last day, the result is a whole number. TRUNC it for completed months.
What is MONTHS_BETWEEN in SQL Server?
No direct match. DATEDIFF(month, a, b) counts month boundaries crossed: January 31 to February 1 is 1. That equals whole months only when both dates are on the same day of the month.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: Oracle, SQL Server, PostgreSQL, MySQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.