| Lesson 11 | Date functions |
| Objective | Understand how date functions are used in SQL |
Date functions are important in SQL because time-based information is one of the most useful ways to organize and analyze data. As soon as you begin writing report queries, dates become central to the work. Orders are placed on dates, employees are hired on dates, invoices become due on dates, and events are recorded with timestamps. Once time enters the data model, SQL needs a practical way to compare dates, add or subtract intervals, extract date parts, and display results in readable formats.
This is why date functions are used so often in reporting and analysis. They help developers segment information into meaningful time periods such as days, months, quarters, and years. They also make it possible to answer common questions such as: Which rows fall within the last 30 days? What is the current date? How many days separate two events? What date occurs 15 days after a given reference point? Without date functions, these tasks would become awkward, inconsistent, and difficult to maintain.
The purpose of this lesson is to show why date functions matter, how common date and time data types are used, how built-in date functions support query logic, and why database platforms differ in their date syntax and date arithmetic. :contentReference[oaicite:0]{index=0}
Dates are foundational to report queries because business data is usually interpreted over time. A report often needs to show monthly revenue, orders placed this week, customers added this quarter, or employees hired before a specific cutoff date. Dates help summarize and segment information into intervals that are easier to understand and easier to compare.
For example, a sales report may group results by month, a payroll report may calculate activity within a pay period, and a project report may show events between two deadlines. In all of these cases, date functions help transform raw date values into practical reporting logic. That is the main reason they are used so frequently in SQL: they turn time into something the query can organize, filter, and present clearly.
To understand date functions, it is helpful to begin with the core temporal data types. Different database systems may implement them with slightly different names or behaviors, but the main concepts are consistent:
These distinctions matter because a developer must know whether a column stores only the calendar date, only the time of day, or a full point in time. Queries behave differently depending on which type is used. A report based on employee hire dates is not the same as a log table that records exact event timestamps down to seconds or fractions of a second. :contentReference[oaicite:1]{index=1}
Although SQL platforms differ, many systems provide a familiar set of built-in date functions. The source page uses MySQL examples to illustrate the most common patterns, and these examples are useful because they show the kinds of operations developers perform regularly:
| Function | Description |
NOW() |
Returns the current date and time. |
CURDATE() |
Returns the current date. |
CURTIME() |
Returns the current time. |
DATE() |
Extracts the date portion from a date/time expression. |
EXTRACT() |
Returns a single part of a date/time value, such as year or month. |
DATE_ADD() |
Adds a specified interval to a date. |
DATE_SUB() |
Subtracts a specified interval from a date. |
DATEDIFF() |
Returns the number of days between two dates. |
DATE_FORMAT() |
Formats date/time values for display. |
These functions illustrate the main categories of date logic in SQL: retrieving the current date or time, extracting meaningful parts, performing interval arithmetic, comparing durations, and formatting results for human readers.
Functions such as NOW(), CURDATE(), and CURTIME() are useful whenever a query needs the current moment or the current business date. These functions appear in audit logic, application defaults, rolling reports, and operational filters.
For example, a query may need to identify all orders placed today, all invoices due before the current date, or all log entries recorded before the current timestamp. Instead of hard-coding a literal date into the query, the developer can use a built-in function that always reflects the system clock. This makes the query more dynamic and more useful in production systems.
Date functions are also used to reshape temporal values into more useful pieces. Suppose a column stores a timestamp, but the report only needs the calendar date. A function such as DATE() can remove the time portion. If the query needs only the month, year, or day component, a function such as EXTRACT() can return that specific part.
Formatting functions also matter because technical storage formats are not always suitable for end users. A report may require a date to appear as a month name, a short numeric form, or a more readable long form. Functions such as DATE_FORMAT() help bridge the gap between raw stored values and the presentation layer.
In other words, date functions are not used only for calculation. They are also used to make date and time data easier to group, compare, and display.
One of the most practical uses of date functions is date arithmetic. SQL developers often need to add or subtract intervals in order to define reporting windows, deadlines, eligibility periods, or time offsets. A query might ask for rows at least 15 days after a reference date, all activity within the last week, or a due date 30 days after a transaction.
The source material includes a DB2-style example in which a hire date is compared to a reference date plus 15 days:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= '05/30/2017' + 15 DAYS;
This example shows the concept clearly: SQL can treat dates as values that support interval arithmetic, not just literal labels stored in a column. That capability is essential in business systems because many decisions depend on elapsed time, scheduled time, and date-based offsets. :contentReference[oaicite:2]{index=2}
One of the most important points in this lesson is that date logic is conceptually portable, but syntax is often not. Different database systems use different literal formats, different built-in functions, and different interval expressions. A query that is perfectly natural in one product may require a noticeably different form in another.
For example, SQL Server historically used a single DATETIME type resembling a timestamp, and the same logical filter could be expressed as:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= '06/14/2017';
If no specific time is supplied, SQL Server defaults to midnight. In effect, the query is interpreted as:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= '06/14/2017 12:00AM';
SQL Server also supports date arithmetic through built-in functions such as DATEADD():
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= DATEADD(DAY, 15, '05/30/2017');
Oracle uses a different literal style and has historically treated its DATE type more like a timestamp than a pure calendar date. An Oracle-style example may look like this:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= '14-JUN-17';
Oracle can also support limited date arithmetic directly:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE HIRE_DATE >= '30-MAY-17' + 15;
These differences matter because they teach a broader lesson: the logic of date filtering may remain stable across platforms, but the exact SQL syntax often must be adjusted to match the target DBMS. :contentReference[oaicite:3]{index=3}
Date literals are often written as strings, but that introduces an important risk. Not all database systems support implicit conversion from string values to date values in the same way. Some expect a particular literal format, while others require explicit conversion functions to make the operation safe and unambiguous.
The source page correctly warns that Oracle may reject a statement unless a function such as TO_DATE() or CAST() is used to convert the character string into a true date value before date arithmetic is attempted. This is a valuable modernization point because implicit conversion can make SQL less portable and harder to debug.
As a practical rule, explicit conversion is often clearer and safer than relying on the database engine to guess the intended date format. When queries must run reliably across environments, that clarity matters. :contentReference[oaicite:4]{index=4}
Date functions are essential because time is one of the main dimensions through which organizations interpret information. Reports are built by day, week, month, quarter, and year. Transactions are judged by when they happened. Employees are analyzed by hire date. Events are measured by elapsed time. Deadlines, aging, scheduling, and trend analysis all depend on date logic.
Without date functions, SQL would struggle to support practical reporting. Developers would have difficulty filtering by time period, extracting relevant parts of a datetime value, computing offsets, or presenting dates in readable formats. Date functions make those operations routine, which is why they appear so frequently in real database applications.
Date functions are used in SQL because they make time-based data practical to analyze. They allow developers to retrieve the current date and time, extract meaningful components, add and subtract intervals, measure differences between dates, and present temporal values in useful forms. They are indispensable in reporting because business information is usually interpreted over time.
This lesson also shows that date work in SQL is not identical across database systems. DB2, SQL Server, Oracle, and MySQL each illustrate the same larger point: date logic is powerful, but platform syntax and conversion rules must be checked carefully. Once you understand both the purpose of date functions and the differences in implementation, you are much better prepared to build reliable report queries that depend on time. :contentReference[oaicite:5]{index=5}