[SQL Basic] How to work with Date Functions in SQL — SQL DATE_FORMAT, DATEDIFF
![]()
Our SQL tutorials so far have covered how to look up data, navigate through it, and perform simple calculations. But in practice we want to to extract specific data from specific tables, not all the data in all the tables. The queries we have learned so far can filter most of that information, but we still need to cover a few more. Here are a few more queries and functions that are essential to your business.
There are certain standards that cannot be omitted from marketing and data analysis. The most important criteria when looking at existing customers, new customers, sales and other data is the date. In this tutorial, we will learn how to handle dates with SQL queries.
#Glossary:
Lesson 3: SELECT / FROM / WHERE
Lesson 4: ORDER BY
Lesson 5: AND / OR / IN
Lesson 6: LIKE
Lesson 7: AS /DISTINCT / IS NULL
Lesson 9: COUNT / SUM
Lesson 10: AVG / MAX / MIN
Lesson 11: GROUP BY / HAVING
Lesson 12: CASE
Lesson 13: INNER JOIN
Lesson 14: OUTER LEFT JOIN / OUTER RIGHT JOIN
Lesson 15: SUBQUERIES
#Table of Contents
Query 1. Find the number of rentals that occur on a daily basis
SELECT DATE_FORMAT(rental_date, ‘%Y-%m-%d’) AS date, count(rental_id) AS count_rental FROM rental GROUP BY date;Query 2. Find which day of the week has the most rentals
SELECT DATE_FORMAT(rental_date, ‘%W’) AS day_of_the_week, count(rental_id) AS count_rental FROM rental GROUP BY day_of_the_week ORDER BY count_rental DESC;Query 3. Find the rental duration by calculating the difference between the rental date and return date
SELECT rental_id, customer_id, rental_date, return_date, DATEDIFF(return_date, rental_date) AS rental_duration FROM rental;
Before we dive into the information of the rental table, we need to become familiar with the date function and format of the SQL query. Let’s first run a query that prints the current date using DATE_FORMAT .
#DATE_FORMAT
Think of DATE_FORMAT as a column name and plug it in after your SELECT query, then specify a factor that has to do with the date. In our case, we want today’s date ( now() ). Next, we’ll specify the format. Using commas, spaces, and dashes, we can rearrange the date in any format we want! For our example today, we will demonstrate two: First, year-month-day followed by the name of the day( ‘%Y-%m-%d, %a’ ). Second, day-month-year preceded by the name of the day( ‘%W, %d-%m-%y’ ).
SELECT DATE_FORMAT(now(), ‘%Y-%m-%d, %a’);
SELECT DATE_FORMAT(now(), ‘%W, %d-%m-%y’);
⭐️SQLGate provides a multi-query function that enables you to run two or more queries simultaneously and view query results at the same time!
Here is a table of helpful shortcuts you can use:
Q 1. Find the number of rentals that occur on a daily basis and organize by date (using COUNT and DATE_FORMAT)
First, let’s look at the rental history data in the rental table.
SELECT * FROM rental;
The table contains the following information:
— Rental ID: (rental_id)
— Date of the rental: (rental_date)
— Inventory ID: (inventory_id)
— Date of return: (return_date)
— Customer ID:(customer_id)
— Staff ID: (staff_id)
Let’s say you want to look at the number of movie rentals that occur at the rental store on a daily basis. It’s simple. We can easily do this using the DATE_FORMAT query along with previously learned COUNT (tutorial 9) and GROUP BY (tutorial 11).
This time, instead of using now() we will designate rental_date as the column we want date information to be pulled from, and specify the format as year-month-day. Let’s also rename this new column ‘date’.
SELECT DATE_FORMAT(rental_date, ‘%Y-%m-%d’ ) AS date,
Remember to capitalize the Y in %Y so the full 4 digit year shows!
To find the number of all rentals, use COUNT and (rental_id) , then rename that new column as count_rental. We’re using ID here because every movie has a unique ID assigned to them. Specify the table we want all this information from (rental):
COUNT(rental_id) AS count_rental FROM rental
And finally organize the information date with GROUP BY . Your final query should look like this:
SELECT DATE_FORMAT(rental_date, ‘%Y-%m-%d’) AS date, count(rental_id) AS count_rental FROM rental GROUP BY date;
Tip: You can use F9 in SQLGate to instantly clean up your query!
This query returns the number of rentals on every day available on the record. Although it doesn’t offer exact time (00:00:00), it does give the year-day-month of the rental starting from 8 rentals on May 24, 2005.
Q 2. Find which day of the week has the most rentals (using GROUP BY and ORDER BY)
Now that we’ve checked the number of movie rentals on a daily basis, let’s check the number of movie rentals on a week day basis. We will use the same data in the rental table and the query statements are very similar. The only thing we’ll change is the date output format.
Before we used ‘ %Y-%m-%d ’ to find the full date of the rental day. But in this next query, we only want the name of the week-day. If you check the handy table we provided in this tutorial, you will see to get this information we need to use a capital W ( %W ).
Just like Query 1, use the rental_date column as a basis for the date information( DATE_FORMAT(rental_date, ). For the format, clarify that you only want the name of the day( %W ). And rename the new column with AS .
SELECT DATE_FORMAT(rental_date, ‘%W’) AS day_of_the_week
Next use COUNT to find the sum of the rentals and rename that column as well:
count(rental_id) AS count_rental
Clarify the name of the table:
Organize the information with GROUP BY and ORDER BY using the new column names we just made:
GROUP BY day_of_the_week ORDER BY count_rental DESC
Put it all together!!
SELECT DATE_FORMAT(rental_date, ‘%W’) AS day_of_the_week, count(rental_id) AS count_rental FROM rental GROUP BY day_of_the_week ORDER BY count_rental DESC;
Once again, don’t forget you can use F9 in SQLGate to tidy the query.
As you can see in the results, the largest number of loans occurred on Tuesday.
Q 3. Find the rental duration by calculating the difference between the rental date and return date
Still using the information in the rental table, let’s calculate the rental period, rental date and the return date for each movie. We can do this using the query DATEDIFF .
#DATEDIFF
DATEDIFF calculates the number of days between two date values, date1 and date2. In our example, we want to know how long the movie was rented. So we will calculate the difference between the day it was rented out (rental_date) and the day it was returned (return_date). Go ahead and rename the new column to Rental Duration:
DATEDIFF(return_date, rental_date) AS rental_duration FROM rental
Earlier we mentioned we also want to see the rental ID, customer ID, rental date and return date, so specify those in the SELECT line.
SELECT rental_id, customer_id, rental_date, return_date
Of course, don’t forget to clarify which table you want all this info from:
Put it all together and it should look like this:
SELECT rental_id, customer_id, rental_date, return_date, DATEDIFF(return_date, rental_date) AS rental_duration FROM rental;
This method can also be useful for inquiring the average lease period/max loan period/minimum loan period.
SQL функции даты и времени
Приветствую Вас, уважаемые читатели блога webcodius.ru. В базе данных часто требуется хранить различные данные связанные с датой и временем. Это может быть дата добавления информации, дата регистрации пользователя, время последней автоизации и другие данные. В языке SQL есть множество функций связанных с датой и временем, сегодня их и рассмотрим.
Все ниже рассмотренные функции работают с календарными типами данных.
Получение текущей даты и времени.
Чтобы получить текущую дату и время используется функция NOW ().
SELECT NOW ()
Результат: 2015-09-25 14:42:53
Для получения только текущей даты есть функция CURDATE ().
SELECT CURDATE ()
Результат: 2015-09-25
И функция CURTIME (), которая возвращает только текущее время:
SELECT CURTIME ()
Результат: 14:42:53
Функции CURDATE () и NOW () удобно использовать для добавления в базу данных записей, для которых требуется хранить дату добавления. Например, при добавлении статьи на сайт хорошо бы хранить ее дату публикации. Тогда запрос на добавление статьи в базу будет примерно таким:
INSERT INTO posts (id_post, text_post, date_publication) VALUES (1, 'текст статьи', NOW ());
Прибавление и вычитание дат и времени
Функция ADDDATE (date, INTERVAL value) прибавляет к дате date значение value и возвращает полученное значение. В качестве value могут выступать следующие значения:
- SECOND — секунды
- MINUTE — минуты
- HOUR — часы
- DAY — дни
- WEEK — недели
- MONTH — месяцы
- QUARTER — кварталы
- YEAR — годы
а также их комбинации:
- MINUTE_SECOND — минуты и секунды
- HOUR_SECONDчасы — минуты и секунды
- HOUR_MINUTE — часы и минуты
- DAY_SECOND — дни, часы, минуты и секунды
- DAY_MINUTE — дни, часы и минуты
- DAY_HOUR — дни и часы
- YEAR_MONTH — года и месяцы.
SELECT ADDDATE ('2015-09-28 10:30:20', INTERVAL 1 DAY)
Результат: 2015-09-29 10:30:20
SELECT ADDDATE ('2015-09-28 10:30:20', INTERVAL '3 1:20' DAY_MINUTE)
Результат: 2015-10-01 11:50:20
Функция SUBDATE (date, INTERVAL value) производит вычитание значения value из даты date . Пример:
SELECT SUBDATE ('2015-09-28 10:30:20', INTERVAL 20 HOUR)
Результат: 2015-09-27 14:30:20
Функция PERIOD_ADD (period, n) прибавляет к значению period n месяцев. Значение период должно быть представлено в формате YYYYMM (например сентябрь 2015 года будет 201509). Пример:
SELECT PERIOD_ADD (201509, 4)
Результат: 201601
Функция TIMESTAMPADD (interval, n, date) прибавляет к дате date временной интервал n , значения которого задаются параметром interval . Возможные значения параметра interval:
- FRAC_SECOND — микросекунды
- SECOND — секунды
- MINUTE — минуты
- HOUR — часы
- DAY — дни
- WEEK — недели
- MONTH — месяцы
- QUARTER — кварталы
- YEAR — годы
SELECT TIMESTAMPADD (QUARTER, 1, '2015-09-28')
Результат: 2015-12-28
Функция SUBTIME (date, time) вычитает из даты date время time. Пример:
SELECT SUBTIME ('2015-09-28 10:30:20', '50:20:19')
Результат: 2015-09-26 08:10:01
Вычисление интервала между датами
Функция TIMEDIFF (date1, date2) вычисляет разницу в часах, минутах и секундах между двумя датами date1 и date2 . Пример:
SELECT TIMEDIFF ('2015-09-28 10:30:20', '2015-09-29 10:30:20')
Результат: -24:10:00
Функция DATEDIFF (date1, date2) вычисляет разницу в днях между двумя датами, при этом часы, минуты и секунды при указании дат игнорируются. Пример:
SELECT DATEDIFF ('2015-09-28 00:00:20', '2015-09-27 23:40:20')
Результат: 1
С помощью этой функции легко определить сколько дней прошло с даты публикации статьи:
SELECT DATEDIFF (CURDATE (), date_publication) FROM posts WHERE id_post = 1
Функция PERIOD_DIFF (period1, period2) вычисляет разницу в месяцах между двумя датами. Даты должны быть представлены в формате YYYYMM . Например, узнаем сколько месяцев прошло с января 2015 по сентябрь 2015:
SELECT PERIOD_DIFF (201509, 201501)
Результат: 9
Функция TIMESTAMPDIFF (interval, date1, date2) вычисляет разницу между датами date2 и date1 в единицах указанных в параметре interval . При этом interval может принимать следующие значения:
- FRAC_SECOND — микросекунды
- SECOND — секунды
- MINUTE — минуты
- HOUR — часы
- DAY — дни
- WEEK — недели
- MONTH — месяцы
- QUARTER — кварталы
- YEAR — годы
SELECT TIMESTAMPDIFF (HOUR, '2015-09-28 10:30:20', '2015-09-28 19:50:20')
Результат: 9
Получение различных форматов даты и времени и другой информации
Функция DATE (datetime) возвращает дату, отсекая время. Пример:
SELECT DATE ('2015-09-28 10:30:20')
Результат: 2015-09-28
Функция TIME (datetime) возвращает время, отсекая дату. Пример:
SELECT TIME ('2015-09-28 10:30:20')
Результат: 10:30:20
Функция TIMESTAMP (date) возвращает полный формат со временем даты date . Пример:
TIMESTAMP ('2015-09-28')
Результат: 2015-09-28 00:00:00
DAY (date) и DAYOFMONTH (date). Функции-синонимы, которые возвращают порядковый номер дня месяца. Пример:
SELECT DAY ('2015-09-28'), DAYOFMONTH ('2015-09-28')
Результат: 28 | 28
Функции DAYNAME (date), DAYOFWEEK (date) и WEEKDAY (date). Первая функция возвращает название дня недели, вторая — номер дня недели (отсчет от 1 — воскресенье до 7 — суббота), третья также номер дня недели только другой отсчет(отсчет от 0 — понедельник, до 6 — воскресенье). Пример:
SELECT DAYNAME ('2015-09-28'), DAYOFWEEK ('2015-09-28'), WEEKDAY ('2015-09-28')
Результат: Monday 2 | 0
Функции WEEK (date) и WEEKOFYEAR (datetime). Обе функции возвращают номер недели в году, только у первой неделя начинается с воскресенья, а у второй с понедельника. Пример:
SELECT WEEK ('2015-09-28 10:30:20'), WEEKOFYEAR ('2015-09-28 10:30:20')
Результат: 39 | 40
Функция MONTH (date) возвращает числовое значение месяца (от 1 до 12), а MONTHNAME (date) название месяца. Пример:
SELECT MONTH ('2015-09-28 10:30:20'), MONTHNAME ('2015-09-28 10:30:20')
Результат: 9 | September
Функция QUARTER (date) возвращает номер квартала года (от 1 до 4). Пример:
SELECT QUARTER ('2015-09-28 10:30:20')
Результат: 3
Функция YEAR (date) возвращает значение года (от 1000 до 9999). Пример:
SELECT YEAR ('2015-09-28 10:30:20')
Результат: 2015
Функция DAYOFYEAR (date) возвращает порядковый номер дня в году (от 1 до 366). Прмиер:
SELECT DAYOFYEAR ('2015-09-28 10:30:20')
Результат: 271
Функция HOUR (datetime) возвращает значение часа (от 0 до 23). Пример:
SELECT HOUR ('2015-09-28 10:30:20')
Результат: 10
Функция MINUTE (datetime) возвращает значение минут (от 0 до 59). Пример:
SELECT MINUTE ('2015-09-28 10:30:20')
Результат: 30
Функция SECOND (datetime) возвращает значение секунд (от 0 до 59). Пример:
SELECT SECOND ('2015-09-28 10:30:20')
Результат: 20
Функция EXTRACT (type FROM date) возвращает часть даты date определяемую параметром type . Пример:
SELECT EXTRACT (YEAR FROM '2015-09-28 10:30:20'), EXTRACT (MONTH FROM '2015-09-28 10:30:20'), EXTRACT (DAY FROM '2015-09-28 10:30:20'), EXTRACT (HOUR FROM '2015-09-28 10:30:20'), EXTRACT (MINUTE FROM '2015-09-28 10:30:20'), EXTRACT (SECOND FROM '2015-09-28 10:30:20')
Результат: 2015 | 9 | 28 | 10 | 30 | 20
Взаимообратные функции TO_DAYS (date) и FROM_DAYS (n). Первая преобразует дату в количество дней, прошедших с нулевого года. Вторая, наоборот, принимает число дней, прошедших с нулевого года и преобразует их в дату. Пример:
SELECT TO_DAYS ('2015-09-28 10:30:20'), FROM_DAYS (736234)
Результат: 736234 | 2015-09-28
Взаимообратные функции UNIX_TIMESTAMP (date) и FROM_UNIXTIME (n). Первая преобразует дату в количество секунд, прошедших с 1 января 1970 года. Вторая, наоборот, принимает число секунд, с 1 января 1970 года и преобразует их в дату. Пример:
SELECT UNIX_TIMESTAMP ('2015-09-28 10:30:20'), FROM_UNIXTIME (1443425420)
Результат: 1443425420 | 2015-09-28 10:30:20
Взаимообратные функции TIME_TO_SEC (time) и SEC_TO_TIME (n). Первая преобразует время в количество секунд, прошедших от начала суток. Вторая, наоборот, принимает число секунд с начала суток и преобразует их во время. Пример:
SELECT TIME_TO_SEC ('10:30:20'), SEC_TO_TIME (37820)
Результат: 37820 | 10:30:20
Функция MAKEDATE (year, n) принимает год year и номер дня в году n и преобразует их в дату. Пример:
Sql как вычесть из даты дату
Table 9.30 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9.29 illustrates the behaviors of the basic arithmetic operators ( + , * , etc.). For formatting functions, refer to Section 9.8. You should be familiar with the background information on date/time data types from Section 8.5.
All the functions and operators described below that take time or timestamp inputs actually come in two variants: one that takes time with time zone or timestamp with time zone , and one that takes time without time zone or timestamp without time zone . For brevity, these variants are not shown separately. Also, the + and * operators come in commutative pairs (for example both date + integer and integer + date); we show only one of each such pair.
Table 9.29. Date/Time Operators
| Operator | Example | Result |
|---|---|---|
| + | date ‘2001-09-28’ + integer ‘7’ | date ‘2001-10-05’ |
| + | date ‘2001-09-28’ + interval ‘1 hour’ | timestamp ‘2001-09-28 01:00:00’ |
| + | date ‘2001-09-28′ + time ’03:00’ | timestamp ‘2001-09-28 03:00:00’ |
| + | interval ‘1 day’ + interval ‘1 hour’ | interval ‘1 day 01:00:00’ |
| + | timestamp ‘2001-09-28 01:00′ + interval ’23 hours’ | timestamp ‘2001-09-29 00:00:00’ |
| + | time ’01:00′ + interval ‘3 hours’ | time ’04:00:00′ |
| — | — interval ’23 hours’ | interval ‘-23:00:00’ |
| — | date ‘2001-10-01’ — date ‘2001-09-28’ | integer ‘3’ (days) |
| — | date ‘2001-10-01’ — integer ‘7’ | date ‘2001-09-24’ |
| — | date ‘2001-09-28’ — interval ‘1 hour’ | timestamp ‘2001-09-27 23:00:00’ |
| — | time ’05:00′ — time ’03:00′ | interval ’02:00:00′ |
| — | time ’05:00′ — interval ‘2 hours’ | time ’03:00:00′ |
| — | timestamp ‘2001-09-28 23:00′ — interval ’23 hours’ | timestamp ‘2001-09-28 00:00:00’ |
| — | interval ‘1 day’ — interval ‘1 hour’ | interval ‘1 day -01:00:00’ |
| — | timestamp ‘2001-09-29 03:00’ — timestamp ‘2001-09-27 12:00’ | interval ‘1 day 15:00:00’ |
| * | 900 * interval ‘1 second’ | interval ’00:15:00′ |
| * | 21 * interval ‘1 day’ | interval ’21 days’ |
| * | double precision ‘3.5’ * interval ‘1 hour’ | interval ’03:30:00′ |
| / | interval ‘1 hour’ / double precision ‘1.5’ | interval ’00:40:00′ |
Table 9.30. Date/Time Functions
| Function | Return Type | Description | Example | Result |
|---|---|---|---|---|
| age( timestamp , timestamp ) | interval | Subtract arguments, producing a “ symbolic ” result that uses years and months, rather than just days | age(timestamp ‘2001-04-10’, timestamp ‘1957-06-13’) | 43 years 9 mons 27 days |
| age( timestamp ) | interval | Subtract from current_date (at midnight) | age(timestamp ‘1957-06-13’) | 43 years 8 mons 3 days |
| clock_timestamp() | timestamp with time zone | Current date and time (changes during statement execution); see Section 9.9.4 | ||
| current_date | date | Current date; see Section 9.9.4 | ||
| current_time | time with time zone | Current time of day; see Section 9.9.4 | ||
| current_timestamp | timestamp with time zone | Current date and time (start of current transaction); see Section 9.9.4 | ||
| date_part( text , timestamp ) | double precision | Get subfield (equivalent to extract ); see Section 9.9.1 | date_part(‘hour’, timestamp ‘2001-02-16 20:38:40’) | 20 |
| date_part( text , interval ) | double precision | Get subfield (equivalent to extract ); see Section 9.9.1 | date_part(‘month’, interval ‘2 years 3 months’) | 3 |
| date_trunc( text , timestamp ) | timestamp | Truncate to specified precision; see also Section 9.9.2 | date_trunc(‘hour’, timestamp ‘2001-02-16 20:38:40’) | 2001-02-16 20:00:00 |
| date_trunc( text , interval ) | interval | Truncate to specified precision; see also Section 9.9.2 | date_trunc(‘hour’, interval ‘2 days 3 hours 40 minutes’) | 2 days 03:00:00 |
| extract ( field from timestamp ) | double precision | Get subfield; see Section 9.9.1 | extract(hour from timestamp ‘2001-02-16 20:38:40’) | 20 |
| extract ( field from interval ) | double precision | Get subfield; see Section 9.9.1 | extract(month from interval ‘2 years 3 months’) | 3 |
| isfinite( date ) | boolean | Test for finite date (not +/-infinity) | isfinite(date ‘2001-02-16’) | true |
| isfinite( timestamp ) | boolean | Test for finite time stamp (not +/-infinity) | isfinite(timestamp ‘2001-02-16 21:28:30’) | true |
| isfinite( interval ) | boolean | Test for finite interval | isfinite(interval ‘4 hours’) | true |
| justify_days( interval ) | interval | Adjust interval so 30-day time periods are represented as months | justify_days(interval ’35 days’) | 1 mon 5 days |
| justify_hours( interval ) | interval | Adjust interval so 24-hour time periods are represented as days | justify_hours(interval ’27 hours’) | 1 day 03:00:00 |
| justify_interval( interval ) | interval | Adjust interval using justify_days and justify_hours , with additional sign adjustments | justify_interval(interval ‘1 mon -1 hour’) | 29 days 23:00:00 |
| localtime | time | Current time of day; see Section 9.9.4 | ||
| localtimestamp | timestamp | Current date and time (start of current transaction); see Section 9.9.4 | ||
| make_date( year int , month int , day int ) | date | Create date from year, month and day fields | make_date(2013, 7, 15) | 2013-07-15 |
| make_interval( years int DEFAULT 0, months int DEFAULT 0, weeks int DEFAULT 0, days int DEFAULT 0, hours int DEFAULT 0, mins int DEFAULT 0, secs double precision DEFAULT 0.0) | interval | Create interval from years, months, weeks, days, hours, minutes and seconds fields | make_interval(days => 10) | 10 days |
| make_time( hour int , min int , sec double precision ) | time | Create time from hour, minute and seconds fields | make_time(8, 15, 23.5) | 08:15:23.5 |
| make_timestamp( year int , month int , day int , hour int , min int , sec double precision ) | timestamp | Create timestamp from year, month, day, hour, minute and seconds fields | make_timestamp(2013, 7, 15, 8, 15, 23.5) | 2013-07-15 08:15:23.5 |
| make_timestamptz( year int , month int , day int , hour int , min int , sec double precision , [ timezone text ]) | timestamp with time zone | Create timestamp with time zone from year, month, day, hour, minute and seconds fields; if timezone is not specified, the current time zone is used | make_timestamptz(2013, 7, 15, 8, 15, 23.5) | 2013-07-15 08:15:23.5+01 |
| now() | timestamp with time zone | Current date and time (start of current transaction); see Section 9.9.4 | ||
| statement_timestamp() | timestamp with time zone | Current date and time (start of current statement); see Section 9.9.4 | ||
| timeofday() | text | Current date and time (like clock_timestamp , but as a text string); see Section 9.9.4 | ||
| transaction_timestamp() | timestamp with time zone | Current date and time (start of current transaction); see Section 9.9.4 | ||
| to_timestamp( double precision ) | timestamp with time zone | Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to timestamp | to_timestamp(1284352323) | 2010-09-13 04:32:03+00 |
In addition to these functions, the SQL OVERLAPS operator is supported:
This expression yields true when two time periods (defined by their endpoints) overlap, false when they do not overlap. The endpoints can be specified as pairs of dates, times, or time stamps; or as a date, time, or time stamp followed by an interval. When a pair of values is provided, either the start or the end can be written first; OVERLAPS automatically takes the earlier value of the pair as the start. Each time period is considered to represent the half-open interval start <= time < end , unless start and end are equal in which case it represents that single time instant. This means for instance that two time periods with only an endpoint in common do not overlap.
When adding an interval value to (or subtracting an interval value from) a timestamp with time zone value, the days component advances or decrements the date of the timestamp with time zone by the indicated number of days. Across daylight saving time changes (when the session time zone is set to a time zone that recognizes DST), this means interval ‘1 day’ does not necessarily equal interval ’24 hours’ . For example, with the session time zone set to CST7CDT , timestamp with time zone ‘2005-04-02 12:00-07’ + interval ‘1 day’ will produce timestamp with time zone ‘2005-04-03 12:00-06′ , while adding interval ’24 hours’ to the same initial timestamp with time zone produces timestamp with time zone ‘2005-04-03 13:00-06’ , as there is a change in daylight saving time at 2005-04-03 02:00 in time zone CST7CDT .
Note there can be ambiguity in the months field returned by age because different months have different numbers of days. PostgreSQL ‘s approach uses the month from the earlier of the two dates when calculating partial months. For example, age(‘2004-06-01’, ‘2004-04-30’) uses April to yield 1 mon 1 day , while using May would yield 1 mon 2 days because May has 31 days, while April has only 30.
Subtraction of dates and timestamps can also be complex. One conceptually simple way to perform subtraction is to convert each value to a number of seconds using EXTRACT(EPOCH FROM . ) , then subtract the results; this produces the number of seconds between the two values. This will adjust for the number of days in each month, timezone changes, and daylight saving time adjustments. Subtraction of date or timestamp values with the “ — ” operator returns the number of days (24-hours) and hours/minutes/seconds between the values, making the same adjustments. The age function returns years, months, days, and hours/minutes/seconds, performing field-by-field subtraction and then adjusting for negative field values. The following queries illustrate the differences in these approaches. The sample results were produced with timezone = ‘US/Eastern’ ; there is a daylight saving time change between the two dates used:
9.9.1. EXTRACT , date_part
The extract function retrieves subfields such as year or hour from date/time values. source must be a value expression of type timestamp , time , or interval . (Expressions of type date are cast to timestamp and can therefore be used as well.) field is an identifier or string that selects what field to extract from the source value. The extract function returns values of type double precision . The following are valid field names:
The first century starts at 0001-01-01 00:00:00 AD, although they did not know it at the time. This definition applies to all Gregorian calendar countries. There is no century number 0, you go from -1 century to 1 century. If you disagree with this, please write your complaint to: Pope, Cathedral Saint-Peter of Roma, Vatican.
For timestamp values, the day (of the month) field (1 — 31) ; for interval values, the number of days
The year field divided by 10
The day of the week as Sunday ( 0 ) to Saturday ( 6 )
Note that extract ‘s day of the week numbering differs from that of the to_char(. ‘D’) function.
The day of the year (1 — 365/366)
For timestamp with time zone values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative); for date and timestamp values, the number of seconds since 1970-01-01 00:00:00 local time; for interval values, the total number of seconds in the interval
You can convert an epoch value back to a time stamp with to_timestamp :
The hour field (0 — 23)
The day of the week as Monday ( 1 ) to Sunday ( 7 )
This is identical to dow except for Sunday. This matches the ISO 8601 day of the week numbering.
This field is not available in PostgreSQL releases prior to 8.3.
The seconds field, including fractional parts, multiplied by 1 000 000; note that this includes full seconds
Years in the 1900s are in the second millennium. The third millennium started January 1, 2001.
The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.
The minutes field (0 — 59)
For timestamp values, the number of the month within the year (1 — 12) ; for interval values, the number of months, modulo 12 (0 — 11)
The quarter of the year (1 — 4) that the date is in
The seconds field, including fractional parts (0 — 59 [7] )
The time zone offset from UTC, measured in seconds. Positive values correspond to time zones east of UTC, negative values to zones west of UTC. (Technically, PostgreSQL does not use UTC because leap seconds are not handled.)
The hour component of the time zone offset
The minute component of the time zone offset
In the ISO week-numbering system, it is possible for early-January dates to be part of the 52nd or 53rd week of the previous year, and for late-December dates to be part of the first week of the next year. For example, 2005-01-01 is part of the 53rd week of year 2004, and 2006-01-01 is part of the 52nd week of year 2005, while 2012-12-31 is part of the first week of 2013. It’s recommended to use the isoyear field together with week to get consistent results.
The year field. Keep in mind there is no 0 AD , so subtracting BC years from AD years should be done with care.
When the input value is +/-Infinity, extract returns +/-Infinity for monotonically-increasing fields ( epoch , julian , year , isoyear , decade , century , and millennium ). For other fields, NULL is returned. PostgreSQL versions before 9.6 returned zero for all cases of infinite input.
The extract function is primarily intended for computational processing. For formatting date/time values for display, see Section 9.8.
The date_part function is modeled on the traditional Ingres equivalent to the SQL -standard function extract :
Note that here the field parameter needs to be a string value, not a name. The valid field names for date_part are the same as for extract .
9.9.2. date_trunc
The function date_trunc is conceptually similar to the trunc function for numbers.
source is a value expression of type timestamp or interval . (Values of type date and time are cast automatically to timestamp or interval , respectively.) field selects to which precision to truncate the input value. The return value is of type timestamp or interval with all fields that are less significant than the selected one set to zero (or one, for day and month).
Valid values for field are:
| microseconds |
| milliseconds |
| second |
| minute |
| hour |
| day |
| week |
| month |
| quarter |
| year |
| decade |
| century |
| millennium |
9.9.3. AT TIME ZONE
The AT TIME ZONE converts time stamp without time zone to/from time stamp with time zone , and time values to different time zones. Table 9.31 shows its variants.
Table 9.31. AT TIME ZONE Variants
| Expression | Return Type | Description |
|---|---|---|
| timestamp without time zone AT TIME ZONE zone | timestamp with time zone | Treat given time stamp without time zone as located in the specified time zone |
| timestamp with time zone AT TIME ZONE zone | timestamp without time zone | Convert given time stamp with time zone to the new time zone, with no time zone designation |
| time with time zone AT TIME ZONE zone | time with time zone | Convert given time with time zone to the new time zone |
In these expressions, the desired time zone zone can be specified either as a text string (e.g., ‘America/Los_Angeles’ ) or as an interval (e.g., INTERVAL ‘-08:00’ ). In the text case, a time zone name can be specified in any of the ways described in Section 8.5.3.
Examples (assuming the local time zone is America/Los_Angeles ):
The first example adds a time zone to a value that lacks it, and displays the value using the current TimeZone setting. The second example shifts the time stamp with time zone value to the specified time zone, and returns the value without a time zone. This allows storage and display of values different from the current TimeZone setting. The third example converts Tokyo time to Chicago time. Converting time values to other time zones uses the currently active time zone rules since no date is supplied.
The function timezone ( zone , timestamp ) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone .
9.9.4. Current Date/Time
PostgreSQL provides a number of functions that return values related to the current date and time. These SQL-standard functions all return values based on the start time of the current transaction:
CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone.
CURRENT_TIME , CURRENT_TIMESTAMP , LOCALTIME , and LOCALTIMESTAMP can optionally take a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field. Without a precision parameter, the result is given to the full available precision.
Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the “ current ” time, so that multiple modifications within the same transaction bear the same time stamp.
Other database systems might advance these values more frequently.
PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. The complete list of non-SQL-standard time functions is:
transaction_timestamp() is equivalent to CURRENT_TIMESTAMP , but is named to clearly reflect what it returns. statement_timestamp() returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp() and transaction_timestamp() return the same value during the first command of a transaction, but might differ during subsequent commands. clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command. timeofday() is a historical PostgreSQL function. Like clock_timestamp() , it returns the actual current time, but as a formatted text string rather than a timestamp with time zone value. now() is a traditional PostgreSQL equivalent to transaction_timestamp() .
All the date/time data types also accept the special literal value now to specify the current date and time (again, interpreted as the transaction start time). Thus, the following three all return the same result:
You do not want to use the third form when specifying a DEFAULT clause while creating a table. The system will convert now to a timestamp as soon as the constant is parsed, so that when the default value is needed, the time of the table creation would be used! The first two forms will not be evaluated until the default value is used, because they are function calls. Thus they will give the desired behavior of defaulting to the time of row insertion.
9.9.5. Delaying Execution
The following functions are available to delay execution of the server process:
pg_sleep makes the current session’s process sleep until seconds seconds have elapsed. seconds is a value of type double precision , so fractional-second delays can be specified. pg_sleep_for is a convenience function for larger sleep times specified as an interval . pg_sleep_until is a convenience function for when a specific wake-up time is desired. For example:
The effective resolution of the sleep interval is platform-specific; 0.01 seconds is a common value. The sleep delay will be at least as long as specified. It might be longer depending on factors such as server load. In particular, pg_sleep_until is not guaranteed to wake up exactly at the specified time, but it will not wake up any earlier.
Warning
Make sure that your session does not hold more locks than necessary when calling pg_sleep or its variants. Otherwise other sessions might have to wait for your sleeping process, slowing down the entire system.
Sql как вычесть из даты дату
This section describes the functions that can be used to manipulate temporal values. See Section 11.2, “Date and Time Data Types”, for a description of the range of values each date and time type has and the valid formats in which values may be specified.
Table 12.11 Date and Time Functions
| Name | Description |
|---|---|
| ADDDATE() | Add time values (intervals) to a date value |
| ADDTIME() | Add time |
| CONVERT_TZ() | Convert from one time zone to another |
| CURDATE() | Return the current date |
| CURRENT_DATE() , CURRENT_DATE | Synonyms for CURDATE() |
| CURRENT_TIME() , CURRENT_TIME | Synonyms for CURTIME() |
| CURRENT_TIMESTAMP() , CURRENT_TIMESTAMP | Synonyms for NOW() |
| CURTIME() | Return the current time |
| DATE() | Extract the date part of a date or datetime expression |
| DATE_ADD() | Add time values (intervals) to a date value |
| DATE_FORMAT() | Format date as specified |
| DATE_SUB() | Subtract a time value (interval) from a date |
| DATEDIFF() | Subtract two dates |
| DAY() | Synonym for DAYOFMONTH() |
| DAYNAME() | Return the name of the weekday |
| DAYOFMONTH() | Return the day of the month (0-31) |
| DAYOFWEEK() | Return the weekday index of the argument |
| DAYOFYEAR() | Return the day of the year (1-366) |
| EXTRACT() | Extract part of a date |
| FROM_DAYS() | Convert a day number to a date |
| FROM_UNIXTIME() | Format Unix timestamp as a date |
| GET_FORMAT() | Return a date format string |
| HOUR() | Extract the hour |
| LAST_DAY | Return the last day of the month for the argument |
| LOCALTIME() , LOCALTIME | Synonym for NOW() |
| LOCALTIMESTAMP , LOCALTIMESTAMP() | Synonym for NOW() |
| MAKEDATE() | Create a date from the year and day of year |
| MAKETIME() | Create time from hour, minute, second |
| MICROSECOND() | Return the microseconds from argument |
| MINUTE() | Return the minute from the argument |
| MONTH() | Return the month from the date passed |
| MONTHNAME() | Return the name of the month |
| NOW() | Return the current date and time |
| PERIOD_ADD() | Add a period to a year-month |
| PERIOD_DIFF() | Return the number of months between periods |
| QUARTER() | Return the quarter from a date argument |
| SEC_TO_TIME() | Converts seconds to ‘hh:mm:ss’ format |
| SECOND() | Return the second (0-59) |
| STR_TO_DATE() | Convert a string to a date |
| SUBDATE() | Synonym for DATE_SUB() when invoked with three arguments |
| SUBTIME() | Subtract times |
| SYSDATE() | Return the time at which the function executes |
| TIME() | Extract the time portion of the expression passed |
| TIME_FORMAT() | Format as time |
| TIME_TO_SEC() | Return the argument converted to seconds |
| TIMEDIFF() | Subtract time |
| TIMESTAMP() | With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments |
| TIMESTAMPADD() | Add an interval to a datetime expression |
| TIMESTAMPDIFF() | Return the difference of two datetime expressions, using the units specified |
| TO_DAYS() | Return the date argument converted to days |
| TO_SECONDS() | Return the date or datetime argument converted to seconds since Year 0 |
| UNIX_TIMESTAMP() | Return a Unix timestamp |
| UTC_DATE() | Return the current UTC date |
| UTC_TIME() | Return the current UTC time |
| UTC_TIMESTAMP() | Return the current UTC date and time |
| WEEK() | Return the week number |
| WEEKDAY() | Return the weekday index |
| WEEKOFYEAR() | Return the calendar week of the date (1-53) |
| YEAR() | Return the year |
| YEARWEEK() | Return the year and week |
Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:
The query also selects rows with dates that lie in the future.
Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.
Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. (For our purposes, a single query also includes a call to a stored program (stored routine, trigger, or event) and all subprograms called by that program.) This principle also applies to CURDATE() , CURTIME() , UTC_DATE() , UTC_TIME() , UTC_TIMESTAMP() , and to any of their synonyms.
The CURRENT_TIMESTAMP() , CURRENT_TIME() , CURRENT_DATE() , and FROM_UNIXTIME() functions return values in the current session time zone, which is available as the session value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the session time zone. See Section 5.1.15, “MySQL Server Time Zone Support”.
Some date functions can be used with “ zero ” dates or incomplete dates such as ‘2001-11-00’ , whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example:
Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:
Several functions are strict when passed a DATE() function value as their argument and reject incomplete dates with a day part of zero: CONVERT_TZ() , DATE_ADD() , DATE_SUB() , DAYOFYEAR() , TIMESTAMPDIFF() , TO_DAYS() , TO_SECONDS() , WEEK() , WEEKDAY() , WEEKOFYEAR() , YEARWEEK() .
Fractional seconds for TIME , DATETIME , and TIMESTAMP values are supported, with up to microsecond precision. Functions that take temporal arguments accept values with fractional seconds. Return values from temporal functions include fractional seconds as appropriate.
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD() . The related function SUBDATE() is a synonym for DATE_SUB() . For information on the INTERVAL unit argument, see Temporal Intervals.
When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr .
This function returns NULL if date or days is NULL .
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is a time expression. Returns NULL if expr1 or expr2 is NULL .
Beginning with MySQL 8.0.28, the return type of this function and of the SUBTIME() function is determined as follows:
If the first argument is a dynamic parameter (such as in a prepared statement), the return type is TIME .
Otherwise, the resolved type of the function is derived from the resolved type of the first argument.
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones are specified as described in Section 5.1.15, “MySQL Server Time Zone Support”. This function returns NULL if any of the arguments are invalid, or if any of them are NULL .
On 32-bit platforms, the supported range of values for this function is the same as for the TIMESTAMP type (see Section 11.2.1, “Date and Time Data Type Syntax”, for range information). On 64-bit platforms, beginning with MySQL 8.0.28, the maximum supported value is ‘3001-01-18 23:59:59.999999’ UTC.
Regardless of platform or MySQL version, if the value falls out of the supported range when converted from from_tz to UTC, no conversion occurs.
To use named time zones such as ‘MET’ or ‘Europe/Amsterdam’ , the time zone tables must be properly set up. For instructions, see Section 5.1.15, “MySQL Server Time Zone Support”.
Returns the current date as a value in ‘ YYYY-MM-DD ‘ or YYYYMMDD format, depending on whether the function is used in string or numeric context.