✅ SQL Date & Time Functions ✅
1. Why Date Functions Matter?
Almost every real-world database contains dates 👇
- ✔️ Orders
- ✔️ Employee joining dates
- ✔️ Transactions
- ✔️ Login activity
SQL date functions help analyze time-based data 💯
⚡ 2. Common Date Functions
Function : Purpose
NOW() : Current date & time
CURDATE() : Current date
CURTIME() : Current time
YEAR() : Extract year
MONTH() : Extract month
DAY() : Extract day
DATEDIFF() : Difference between dates
DATE_FORMAT() : Format dates
🔥 3. NOW(), CURDATE(), CURTIME()
SELECT NOW();
Output : ✔️ Current date + time
SELECT CURDATE();
Output : ✔️ Current date only
SELECT CURTIME();
Output : ✔️ Current time only
🔥 4. YEAR(), MONTH(), DAY()
SELECT YEAR(joining_date) FROM employees;
SELECT MONTH(joining_date) FROM employees;
SELECT DAY(joining_date) FROM employees;
🔥 5. DATEDIFF()
👉 Find difference between dates
SELECT DATEDIFF('2026-06-10', '2026-06-01');
✔️ Result → 9 days
🔥 6. DATE_FORMAT()
👉 Format dates professionally
SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');
✔️ Example Output → 06-06-2026
🎯 7. Real Example
👉 Employees joined in 2025
SELECT * FROM employees WHERE YEAR(joining_date) = 2025;
🎯 8. Practice Tasks
1. Show current date
2. Show current time
3. Extract joining year from employee table
4. Find employees joined in specific month
5. Calculate days between two dates
⚡ Mini Challenge 🔥
👉 Find employees who joined in the last 30 days
✅ Solution Using DATEDIFF()
SELECT * FROM employees WHERE DATEDIFF(CURDATE(), joining_date) <= 30;
✅ Alternative Solution Using DATE_SUB()
SELECT * FROM employees WHERE joining_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
🔥 Pro Tip
Date functions are heavily used in:
👉 Sales reports
👉 Monthly dashboards
👉 Retention analysis
👉 Time-series analytics 💯
No comments:
Post a Comment