SQL
In SQL when it comes to working with dates, the SELECT DATE, command is very useful for a variety of tasks. This command helps to find today’s date, Filter data after a specific date, Format dates neatly and many more.
The basic syntax for a simple SQL SELECT statement involving dates is as follows:
SELECT column1, column2, ...
FROM table
WHERE date_condition;
To fetch the current date and time, you can use a function such as GETDATE() in SQL Server or CURRENT_TIMESTAMP in MySQL:
SELECT GETDATE() AS CurrentDateTime;
This will return a single-column result with the current date and time.
CurrentDateTime
2024-02-04 12:30:45
Database: Students
| StudentID | FirstName | LastName | EnrollmentDate |
|---|---|---|---|
| 1 | John | Doe | 2023-01-15 |
| 2 | Jane | Smith | 2023-02-20 |
| 3 | Alex | Johnson | 2023-03-10 |
| 4 | Emma | Davis | 2023-04-05 |
SELECT FirstName, LastName, EnrollmentDate
FROM Students
WHERE EnrollmentDate > '2023-02-01';
Output:
| FirstName | LastName | EnrollmentDate |
|---|---|---|
| Jane | Smith | 2023-02-20 |
| Alex | Johnson | 2023-03-10 |
| Emma | Davis | 2023-04-05 |
In this example, we demonstrate how to format the date output using the FORMAT() function
SELECT FirstName, LastName, FORMAT(EnrollmentDate, 'MM/dd/yyyy') AS FormattedDate
FROM Students;
| FirstName | LastName | FormattedDate |
|---|---|---|
| John | Doe | 01/15/2023 |
| Jane | Smith | 02/20/2023 |
| Alex | Johnson | 03/10/2023 |
| Emma | Davis | 04/05/2023 |
SELECT FirstName, LastName, DATEADD(DAY, 30, EnrollmentDate) AS EnrollmentDateAfter30Days
FROM Students;
| FirstName | LastName | EnrollmentDateAfter30Days |
|---|---|---|
| John | Doe | 2023-02-14 |
| Jane | Smith | 2023-03-22 |
| Alex | Johnson | 2023-04-09 |
| Emma | Davis | 2023-05-05 |
SELECT MIN(EnrollmentDate) AS OldestEnrollmentDate, MAX(EnrollmentDate) AS NewestEnrollmentDate
FROM Students;
| OldestEnrollmentDate | NewestEnrollmentDate |
|---|---|
| 2023-01-15 | 2023-04-05 |
SELECT FirstName, LastName, MONTH(EnrollmentDate) AS EnrollMonth, YEAR(EnrollmentDate) AS EnrollYear
FROM Students;
| FirstName | LastName | EnrollMonth | EnrollYear |
|---|---|---|---|
| John | Doe | 1 | 2023 |
| Jane | Smith | 2 | 2023 |
| Alex | Johnson | 3 | 2023 |
| Emma | Davis | 4 | 2023 |
SELECT FirstName, LastName, EnrollmentDate
FROM Students
WHERE EnrollmentDate >= DATEADD(MONTH, -3, GETDATE());
| FirstName | LastName | EnrollmentDate |
|---|---|---|
| Alex | Johnson | 2023-03-10 |
| Emma | Davis | 2023-04-05 |
SELECT YEAR(EnrollmentDate) AS EnrollmentYear, COUNT(StudentID) AS StudentCount
FROM Students
GROUP BY YEAR(EnrollmentDate);
| EnrollmentYear | StudentCount |
|---|---|
| 2023 | 4 |