// dates & times reference

SQL QUARTER function

Returns the calendar quarter as an integer 1-4. SQLite has no quarter function at all, and Oracle only formats it as text.

类别
Dates & times
Returns
integer
In this category
43 of 121

语法

DATEPART(quarter, d)  -- SQL Server
EXTRACT(quarter FROM d)  -- PostgreSQL
QUARTER(d)  -- MySQL

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支持

引擎Support备注
SQL Server Different name or syntax DATEPART(quarter, d)
PostgreSQL Different name or syntax EXTRACT(quarter FROM d)
MySQL 是 Supported under this name.
SQLite Different name or syntax compute it: (CAST(strftime('%m', d) AS INTEGER) + 2) / 3
Oracle Different name or syntax TO_CHAR(d, 'Q') returns text

示例

PostgreSQL

SELECT EXTRACT(year FROM created_at) AS yr,
       EXTRACT(quarter FROM created_at) AS qtr, COUNT(*)
FROM orders GROUP BY 1, 2;

MySQL

SELECT QUARTER(created_at) AS qtr FROM orders;

Oracle

SELECT TO_CHAR(created_at, 'Q') AS qtr FROM orders;

值得了解

  • Oracle has no EXTRACT(quarter): TO_CHAR(d, 'Q') is the stand-in and returns text, not a number.
  • Quarters are calendar quarters on every engine; fiscal quarters need your own mapping table or an offset by months.
  • SQLite needs the arithmetic form: (month + 2) / 3 with integer division gives 1 through 4.

Questions about QUARTER

How do I get quarters in SQLite?

No QUARTER function: (CAST(strftime('%m', d) AS INTEGER) + 2) / 3 with integer division returns 1-4.

Can I get fiscal quarters?

Not directly. Shift the date by the fiscal offset in months first (DATEADD(month, -3, d) on SQL Server), then take the calendar quarter.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.