This function takes the difference between two dates and shows it in a date format yyyy-mm-dd. All you need is to execute the code below and then use the function. After executing you can use it like this
SELECT datedifference(date1, date2)
FROM ....
.
.
.
.
DELIMITER $$
CREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE
NO SQL
BEGIN
DECLARE dif DATE;
IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0 THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),
'%Y-%m-%d');
ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
ELSE
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
END IF;
RETURN dif;
END $$
DELIMITER;
I have a table like this:
rowInt Value
2 23
3 45
17 10
9 0
....
The column rowInt values are integer but not in a sequence with same increament. I can use the following sql to list values by rowInt:
SELECT * FROM myTable ORDER BY rowInt;
This will list values by rowInt. How can get get the difference of Value between two rows with the result like this:
rowInt Value Diff
2 23 22 --45-23
3 45 -35 --10-45
9 0 -45 --0-45
17 10 10 -- 10-0
....
The table is in SQL 2005 (Miscrosoft)
asked Mar 11, 2009 at 13:43
David.Chu.caDavid.Chu.ca
37k63 gold badges148 silver badges190 bronze badges
4
SELECT
[current].rowInt,
[current].Value,
ISNULL([next].Value, 0) - [current].Value
FROM
sourceTable AS [current]
LEFT JOIN
sourceTable AS [next]
ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)
EDIT:
Thinking about it, using a subquery in the select (ala Quassnoi’s answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have…
EDIT2:
I still see this garnering votes, though it’s unlikely many people still use SQL Server 2005.
If you have access to Windowed Functions such as LEAD()
, then use that instead…
SELECT
RowInt,
Value,
LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
sourceTable
answered Mar 11, 2009 at 13:50
MatBailieMatBailie
82.8k18 gold badges102 silver badges137 bronze badges
2
SELECT rowInt, Value,
COALESCE(
(
SELECT TOP 1 Value
FROM myTable mi
WHERE mi.rowInt > m.rowInt
ORDER BY
rowInt
), 0) - Value AS diff
FROM myTable m
ORDER BY
rowInt
answered Mar 11, 2009 at 13:50
0
SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).
A SQL 2012 example on this data
/* Prepare */
select * into #tmp
from
(
select 2 as rowint, 23 as Value
union select 3, 45
union select 17, 10
union select 9, 0
) x
/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value
from #tmp
LEAD(value) will return the value of the next row in respect to the given order in «over» clause.
ChrisW
9,1331 gold badge20 silver badges33 bronze badges
answered Oct 4, 2016 at 19:50
AnsonmusAnsonmus
3252 silver badges9 bronze badges
3
If you really want to be sure of orders, use «Row_Number()» and compare next record of current record (take a close look at «on» clause)
T1.ID + 1 = T2.ID
You are basically joining next row with current row, without specifying «min» or doing «top». If you have a small number of records, other solutions by «Dems» or «Quassanoi» will work fine.
with T2 as (
select ID = ROW_NUMBER() over (order by rowInt),
rowInt, Value
from myTable
)
select T1.RowInt, T1.Value, Diff = IsNull(T2.Value, 0) - T1.Value
from ( SELECT ID = ROW_NUMBER() over (order by rowInt), *
FROM myTable ) T1
left join T2 on T1.ID + 1 = T2.ID
ORDER BY T1.ID
answered Mar 12, 2009 at 1:34
dance2diedance2die
35.5k39 gold badges130 silver badges194 bronze badges
Does SQL Server support analytic functions?
select rowint,
value,
value - lag(value) over (order by rowint) diff
from myTable
order by rowint
/
answered Mar 12, 2009 at 1:39
David AldridgeDavid Aldridge
51.3k8 gold badges68 silver badges95 bronze badges
3
select t1.rowInt,t1.Value,t2.Value-t1.Value as diff
from (select * from myTable) as t1,
(select * from myTable where rowInt!=1
union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2
where t1.rowInt=t2.rowInt-1
LPL
16.8k6 gold badges50 silver badges95 bronze badges
answered Nov 23, 2009 at 12:02
Query to Find the date difference between 2 rows of a single column
SELECT
Column name,
DATEDIFF(
(SELECT MAX(date) FROM table name WHERE Column name < b. Column name),
Column name) AS days_since_last
FROM table name AS b
Thomas G
9,8117 gold badges27 silver badges40 bronze badges
answered May 27, 2016 at 17:09
1
I’d just make a little function for that. Toss in the two values you need to know the difference between and have it subtract the smaller from the larger value. Something like:
CREATE FUNCTION [dbo].[NumDifference]
( @p1 FLOAT,
@p2 FLOAT )
RETURNS FLOAT
AS
BEGIN
DECLARE @Diff FLOAT
IF @p1 > @p2 SET @Diff = @p1 - @p2 ELSE SET @Diff = @p2 - @p1
RETURN @Diff
END
In a query to get the difference between column a and b:
SELECT a, b, dbo.NumDifference(a, b) FROM YourTable
answered Jul 22, 2019 at 11:38
In this tutorial, we will study the MySQL DATEDIFF()
function. Suppose you are an HR executive at a company and you have data on the check-in date and time for each employee for today as well as the date they first joined the company in a table. The CEO of the company has tasked you with finding out how many days have elapsed since each employee joined the company.
Now doing this manually would be a mammoth task. Some employees may have joined more than 5 years ago or so and besides, your CEO wants the exact number of days each employee has been in the company. But we have a computer and we know MySQL, so let us make things easy for ourselves. Let us see how we can use the MySQL DATEDIFF()
function to solve this problem.
The MySQL DATEDIFF()
function is used to find the difference between two dates or datetime values. In other words, it returns the number of days between two dates. Let us dive deep and take a look at the syntax before we move on to the examples.
Syntax of MySQL DATEDIFF()
DATEDIFF(date1, date2)
Code language: SQL (Structured Query Language) (sql)
Where, ‘date1’ and ‘date2’ are two date or datetime expressions.
Note that DATEDIFF() calculates the differences by subtracting date2 from date1, i.e. MySQL DATEDIFF() computes and returns the value of date1– date2.
Examples of MySQL DATEDIFF()
Let us start by looking at a few basic examples. Let us find the number of days between the following –
- ‘2020-05-31’ and ‘2020-05-01’ ,and
- ‘2020-06-15’, ‘2020-05-01’.
We will use the SELECT
statement and an alias called ‘Number of Days’ to make our output readable. The query is –
SELECT DATEDIFF('2020-05-31', '2020-05-01') AS 'Number of Days';
SELECT DATEDIFF('2020-06-15', '2020-05-01') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
MySQL DATEDIFF() With Larger Differences
DATEDIFF()
can support large differences between the date values, unlike the TIMEDIFF()
function. However, make sure you enter valid date values. Let us see a couple of examples where the dates are years apart. Consider the below queries.
SELECT DATEDIFF('2021-03-01', '2000-02-25') AS 'Number of Days';
SELECT DATEDIFF('2021-01-01', '1999-11-19') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
DATEDIFF() With Wrong Date Values
Building on what I said earlier about having valid date values, what if we pass invalid date values? If either of the date in the DATEDIFF()
function is wrong or invalid, then the DATEDIFF()
function returns NULL. Let us see an example of this.
SELECT DATEDIFF('2020-56-12', '2019-05-15') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
MySQL DATEDIFF() With Negative Days Difference
If, by mistake, you pass the second date value as a value larger than the first, you’ll get a negative value for the date difference. This is alright as DATEDIFF()
supports a negative date difference. Let us see an example of this. Consider the below query.
SELECT DATEDIFF('2000-02-25', '2021-03-01') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
DATEDIFF() With CURDATE()
We can also use the CURDATE()
function with the DATEDIFF()
function. Let us find out the number of days between the present day (At the time this article was written, the date was 17th March, 2021) and the date India got independence on August 15, 1947. The query is –
SELECT DATEDIFF(CURDATE(), '1947-08-15') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
DATEDIFF() With Datetime Values
As I mentioned in the syntax section, DATEDIFF()
also works with datetime values. However, while computation of the difference between the values, the time value in the datetime value is ignored. Let us see an example of DATEDIFF()
with datetime values.
SELECT DATEDIFF('2020-05-31 00:00:30', '2020-05-01 23:59:59') AS 'Number of Days';
Code language: SQL (Structured Query Language) (sql)
And the output is –
Working With Tables
Finally, let us see an example of DATEDIFF()
with tables. Consider the below Employee table.
Now, coming back to the problem I mentioned in the beginning of this article. Suppose you are an HR executive at a company and you have data on the check-in date and time for each employee for today as well as the date they first joined the company in a table. The CEO of the company has tasked you with finding out how many days have elapsed since each employee joined the company.
Now that we know how to use the DATEDIFF()
function, let us use it to solve the above problem. Our query is –
SELECT eid, Name, DATEDIFF(CheckInDateTime, Date_Joined) AS 'Number Of Days' FROM Employee;
Code language: SQL (Structured Query Language) (sql)
And the output is –
Conclusion
DATEDIFF()
is a very important datetime function. Basic subtraction operations are always very important and have abundant use cases. I would encourage you to practice more examples of this function!
References
- MySQL Official Documentation on the
DATEDIFF()
function.
So working with dates is something every MySQL database developer must do once in a while. And most of the time, this will require calculating the number of days between date values. Fortunately, MySQL provides a handy date function to make such calculations easy-breezy – say hello to the MySQL datediff function.
Therefore, in this article, we’re going to provide you with information on how to use the datediff() function. In addition, we will show you practical situations where you’ll find this function most helpful in your MySQL development journey.
In the first place, let’s put things into perspective – what is MySQL datediff() function? This function allows you to determine the difference between two dates quickly. Therefore, all you have to do is to pass required input parameters to the function; and it will return a value indicating the difference between the two inputs.
datediff(expression1,expression2);
Note: expression1is the first date, and expression2 is the second date.
How To Find DateDiff In MySQL
When working with MySQL database and trying to figure out how to find datediff in MySQL, all you have to do is use the MySQL datediff function.
For example, let’s you have two dates: September 1, 2023, and September 20, 2023. And you want to programmatically find the difference between the two (without using your calculator or fingers to count), you’ll use the datediff() function as follows:
Select datediff('2023-09-20','2023-09-01') as Difference;Once you run the above query against the database, you’ll get the following result:
+------------+ | Difference | +------------+ | 19 | +------------+
Notably, bear in mind that the MySQL datediff() function works with the following MySQL versions: 5.7, 5.6, 5.5, 5.1, 5.0 and 4.1.1.
What Does DateDiff Return MySQL
Equally important, you may be wondering what does the MySQL datediff function return. As you can see from the above example, the function will return the number of days between the two dates you provided.
Also, if you provided datetimes instead of date days, then the function will equally return the difference between the two provided date times in days.
[SPECIAL OFFER]: Fastest Web Hosting with FREE MySQL
[BENEFITS]:
- FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
- Support for PHP, MySQL, ASP.NET, SQL Server, WordPress, Joomla and much more!
- Multi-Domain Hosting & 99.9% Uptime Guarantee!
- Super Fast Servers with 24/7/365 Technical Support!
Click here to access this [SPECIAL OFFER]
How To Use DateDiff In MySQL
Now, let’s take a look at how to use datediff() in MySQL with some practical examples so you can fully understand the concept.
MySQL DateDiff Seconds
First, how do you get the difference between two times in seconds? The datediff() function is probably not the best function to use in such a situation.
So if you’re trying to do MySQL datediff seconds, you’ll come to realize that the datediff() function only returns day values. Therefore, if you supply the seconds in the date, only the date portion is used in the calculation to return the number of days.
Now, there’s the timestampdiff() function which will provide you with the needed capability to calculate the differences between two datetime expressions. And the two expressions must be of the same type.
The syntax is as follows:
timestampdiff(unit,expression1,expression2);And for the arguments:
1. unit: The unit can be one of the following options: FRAC_SECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.
2. expression1: This is a datetime expression you’ll substract expression2 from.
3. expression2: This is a datetime expression you’ll substract from expression1.Therefore, if you’re looking for MySQL DateDiff seconds, you can use the TimeStampDiff function to accomplish your objective. For example:
Select timestampdiff(SECONDS, '2023-09-20 12:30:15', '2023-09-01 10:15:00') as Difference;The above query statement will return the different between the two datetime values provided in seconds 2023-09-20 12:30:15 and 2023-09-01 10:15:00 as shown below:
+------------------+ | Difference | +------------------+ | 15 | +------------------+
MySQL DateDiff Minutes
Likewise, there will be times you need to get the difference in two datetime expression in minutes. Consequently, your natural inclination might be to there’s a MySQL DateDiff Minutes as a solution.
However, as stated above, you’ll come to realize that this won’t work out very well. Instead, use the TimeStampDiff() function to accomplish this task.
Select timestampdiff(MINUTES, '2023-09-20 12:30:15', '2023-09-01 10:15:00') as Difference;The above query statement will return the difference between the two datetime values provided in minutes 2023-09-20 12:30:15 and 2023-09-01 10:15:00 as shown below:
+------------------+ | Difference | +------------------+ | 15 | +------------------+
MySQL DateDiff Hours
Furthermore, as you can see from the above two examples when looking for the difference in two datetime expressions, the MySQL DateDiff hours is not a reliable solution.
Once again, you can use the TimeStampDiff() function to get the job done. Let’s take look:
Select timestampdiff(HOURS, '2023-09-20 12:30:15', '2023-09-01 10:15:00') as Difference;The above query statement will return the difference between the two datetime values provided in hours 2023-09-20 12:30:15 and 2023-09-01 10:15:00 as shown below:
+------------------+ | Difference | +------------------+ | 2 | +------------------+
MySQL DateDiff Days
The MySQL DateDiff() function’s default return value is the number of days between two date or datetime expressions.
And as we’ve also indicated earlier, if you run a query statement like this:
Select datediff('2023-09-20','2023-09-15') as Difference;You’ll get the following result:
+------------+ | Difference | +------------+ | 5 | +------------+
The result tells you that there’s a difference of 5 days between the two expressions. So this is how the function works.
[SPECIAL OFFER]: Fastest Web Hosting with FREE MySQL
[BENEFITS]:
- FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
- Support for PHP, MySQL, ASP.NET, SQL Server, WordPress, Joomla and much more!
- Multi-Domain Hosting & 99.9% Uptime Guarantee!
- Super Fast Servers with 24/7/365 Technical Support!
Click here to access this [SPECIAL OFFER]
MySQL DateDiff Months
Of course, there will be occasions where you need to know the difference between two periods. Particularly, let’say you want to know the difference between the periods in months.
Certainly, trying to use the MySQL DateDiff Months in such a situation won’t cut. Luckily, MySQL provides another handy function called the PERIOD_DIFF() which can do the trick.
Syntax:
The PERIOD_DIFF() syntax is as follows:
period_diff(expression1,expression2);where “expression1” indicates the first period and “expression2” means the second period to subtract from “expression1”.
So here’s an example:
Select period_diff(202310,202302) As Difference;The above query statement will output
+------------------+ | Difference | +------------------+ | 8 | +------------------+
The result shows that there is eight months difference between the two periods.
MySQL DateDiff Years
Moreover, if you’re looking for MySQL DateDiff Years, you can accomplish the same using the PERIOD_DIFF() function above as well as the TIMESTAMPDIFF() described above as well.
For PERIOD_DIFF() example:
Select period_diff(2025,2023) As Difference;The above query statement will return:
+------------------+ | Difference | +------------------+ | 2 | +------------------+
For TIMESTAMPDIFF() example:
Select timestampdiff(YEAR, '2025-09-20 12:30:15', '2023-09-01 10:15:00') as Difference;The above query statement will also return:
+------------------+ | Difference | +------------------+ | 2 | +------------------+
MySQL DateDiff Current Date
Besides, you can use the function together with the Current Date function. The CURDATE() function returns the value of the current date on the system.
So here’s a practical example:
Select datediff(curdate(),'2023-09-01') as Difference;Once you run the above query against the database, If the current date is ‘2023-09-30’, you’ll get the following result (in days):
+------------+ | Difference | +------------+ | 29 | +------------+
Final Thought
We hope that this article has given you more insight into this function, it’s applications as well as limitations. As with anything, feel free to solidify your understanding of the fundamental concepts by reading other available resources as well as MySQL documentation. Good luck!
[SPECIAL OFFER]: Fastest Web Hosting with FREE MySQL
[BENEFITS]:
- FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
- Support for PHP, MySQL, ASP.NET, SQL Server, WordPress, Joomla and much more!
- Multi-Domain Hosting & 99.9% Uptime Guarantee!
- Super Fast Servers with 24/7/365 Technical Support!
Click here to access this [SPECIAL OFFER]
- Главная»
- Уроки»
- Разное»
- 6 запросов для MySQL
- Метки урока:
- mysql
- кодинг
Искусство в построении запросов с использованием Structured Query Language (язык структурированных запросов) заключается в создании правильных, эффективных вопросов и команд для базы данных. В запросах SELECT можно использовать ключевые слова JOIN, WHERE и HAVING для уточнения результатов, GROUP BY для комбинирования результатов в легко анализируемые блоки, и UNION для комбинирования результатов нескольких запросов. Команды INSERT, DELETE и UPDATE могут использовать JOIN. Запрос INSERT … SELECT вставляет результаты в другую таблицу. В запросах DELETE и UPDATE можно использовать ключевое слово WHERE, чтобы указать область действия.
Ниже приводятся 6 запросов для MySQL.
1. Возраст в годах
Если у вас в таблице хранится дата рождения и нужно вычислить возраст, то можно использовать следующий запрос. @dateofbirth — дата рождения:
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;
2. Разница между двумя датами
Находим разницу между двумя датами, выраженную в секундах, минутах, часах или днях. Если dt1 и dt2 значения дат в формате ‘yyyy-mm-dd hh:mm:ss’, то количество секунд между dt1 и dt2 вычисляется:
UNIX_TIMESTAMP( dt2 ) - UNIX_TIMESTAMP( dt1 )
Чтобы получить количество минут, делим вычисленное значение на 60, для вычисления количества часов — делим на 3600, а для определения количества дней — делим на 3600*24.
3. Выводим значение, которое встречается в столбце N раз
SELECT id FROM tbl GROUP BY id HAVING COUNT(*) = N;
4. Вычисляем количество рабочих дней между двумя датами
Простейшим способом вычислить количество рабочих дней между двумя датами является использование таблицы календаря calendar со столбцами даты d и логического флага праздников holiday для всех дней во всех возможных годах. Затем используется соответствующий запрос, который возвращает количество рабочих дней между двумя датами Start и Stop включительно:
SELECT COUNT(*) FROM calendar WHERE d BETWEEN Start AND Stop AND DAYOFWEEK(d) NOT IN(1,7) AND holiday=0;
5. Находим основной ключ для таблицы
SELECT k.column_name FROM information_schema.table_constraints t JOIN information_schema.key_column_usage k USING (constraint_name,table_schema,table_name) WHERE t.constraint_type='PRIMARY KEY' AND t.table_schema='db' AND t.table_name='tbl'
6. Определяем, насколько велика таблица
SELECT table_schema AS 'Db Name', Round( Sum( data_length + index_length ) / 1024 / 1024, 3 ) AS 'Db Size (MB)', Round( Sum( data_free ) / 1024 / 1024, 3 ) AS 'Free Space (MB)' FROM information_schema.tables GROUP BY table_schema ;
5 последних уроков рубрики «Разное»
-
Как выбрать хороший хостинг для своего сайта?
Выбрать хороший хостинг для своего сайта достаточно сложная задача. Особенно сейчас, когда на рынке услуг хостинга действует несколько сотен игроков с очень привлекательными предложениями. Хорошим вариантом является лидер рейтинга Хостинг Ниндзя — Макхост.
-
Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг — это будущее Ваших сайтов
Проект готов, Все проверено на локальном сервере OpenServer и можно переносить сайт на хостинг. Вот только какую компанию выбрать? Предлагаю рассмотреть хостинг fornex.com. Отличное место для твоего проекта с перспективами бурного роста.
-
Разработка веб-сайтов с помощью онлайн платформы Wrike
Создание вебсайта — процесс трудоёмкий, требующий слаженного взаимодействия между заказчиком и исполнителем, а также между всеми членами коллектива, вовлечёнными в проект. И в этом очень хорошее подспорье окажет онлайн платформа Wrike.
-
20 ресурсов для прототипирования
Подборка из нескольких десятков ресурсов для создания мокапов и прототипов.
-
Топ 10 бесплатных хостингов
Небольшая подборка провайдеров бесплатного хостинга с подробным описанием.