SQL Date & Time Functions
SQL provides powerful functions to handle dates and times β essential for filtering, formatting, and calculating time-based data. πΉ Common Date Functions (DBMS-Agnostic Examples) πΉ Examples πΉ Key Date Functions by DBMS Function MySQL PostgreSQL SQL Server Current Date CURDATE() CURRENT_DATE GETDATE() Extract Year YEAR(date_col) EXTRACT(YEAR FROM β¦) YEAR(date_col) Add Days DATE_ADD() + INTERVAL or […]
SQL provides powerful functions to handle dates and times β essential for filtering, formatting, and calculating time-based data.
πΉ Common Date Functions (DBMS-Agnostic Examples)
-- Get current date and time
SELECT CURRENT_DATE; -- PostgreSQL / MySQL
SELECT GETDATE(); -- SQL Server
-- Extract parts of a date
SELECT EXTRACT(YEAR FROM order_date) FROM orders; -- PostgreSQL
SELECT YEAR(order_date) FROM orders; -- MySQL / SQL Server
-- Add or subtract dates
SELECT order_date + INTERVAL '7 day' FROM orders; -- PostgreSQL
SELECT DATE_ADD(order_date, INTERVAL 7 DAY) FROM orders; -- MySQL
SELECT DATEADD(DAY, 7, order_date) FROM orders; -- SQL Server
-- Difference between dates
SELECT DATEDIFF(CURDATE(), order_date); -- MySQL
SELECT DATEDIFF(DAY, order_date, GETDATE());-- SQL Server
-- Format dates
SELECT TO_CHAR(order_date, 'YYYY-MM-DD') FROM orders; -- PostgreSQL
SELECT DATE_FORMAT(order_date, '%Y-%m-%d') FROM orders; -- MySQL
SELECT FORMAT(order_date, 'yyyy-MM-dd') FROM orders; -- SQL ServerπΉ Examples
-- Find orders placed in last 30 days
SELECT * FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 day'; -- PostgreSQL
-- Find orders placed in a specific month
SELECT * FROM orders
WHERE MONTH(order_date) = 5; -- MayπΉ Key Date Functions by DBMS
| Function | MySQL | PostgreSQL | SQL Server |
|---|---|---|---|
| Current Date | CURDATE() | CURRENT_DATE | GETDATE() |
| Extract Year | YEAR(date_col) | EXTRACT(YEAR FROM β¦) | YEAR(date_col) |
| Add Days | DATE_ADD() | + INTERVAL or DATE + | DATEADD() |
| Date Difference | DATEDIFF() | AGE() | DATEDIFF() |
| Format Date | DATE_FORMAT() | TO_CHAR() | FORMAT() |
π§ Quick Recap
| Task | Function Example |
|---|---|
| Current Date/Time | CURRENT_DATE, GETDATE() |
| Extract Date Part | YEAR(order_date) |
| Add Days | DATE_ADD(order_date, INTERVAL 7 DAY) |
| Date Difference | DATEDIFF() |
| Format Date | TO_CHAR(), DATE_FORMAT() |
π‘ Use the right function depending on your DBMS, and always format or extract dates smartly for reports and filters.