I want to insert the date and day of the week for the whole of 2019-01-01 to 2019-12-31. but I`m unable to.
I try date_format function.
This is my table. table name is food_user and I want to insert the date and day in re_date, re_day 2019-01-01~2019-12-31
INSERT INTO food_user (NAME,re_date,re_day) VALUES ('Alex' , ? , ?);
If you're using MariaDB, try this code to get all dates in year:
SELECT '2019-01-01' + INTERVAL seq DAY FROM seq_0_to_364;
or
SELECT '2018-12-31' + INTERVAL seq DAY FROM seq_1_to_365;
To undestand this, MariaDB has a built in SEQUENCE Engine - reference: https://mariadb.com/kb/en/library/sequence-storage-engine/ .
Basically typing SELECT seq FROM seq_1_to_10; will return you a number seq from 1 to 10. In this case, a whole year is 365 days hence seq_1_to_365 will return number from 1 to 365. IF you're counting from zero (0), then you'll need to consider the last value as 364, hence changing the sequence to seq_0_to_364 as the example above. From your query, you can do something like this:
INSERT INTO food_user (NAME,re_date,re_day)
SELECT 'Alex','2019-01-01' + INTERVAL seq DAY,DAYNAME('2019-01-01' + INTERVAL seq DAY) FROM seq_0_to_364;
Here's an update, a few months ago I've discovered a way of using recursive statement to generate date ranges. The sequence engine is quite useful but it's only specific to MariaDB. WITH RECURSIVE is supported on both MySQL & MariaDB, although it's also version specific; MySQL from version 8 & MariaDB from version 10.2.2. This is the query:
WITH RECURSIVE date_ranges AS (
SELECT '2019-01-01' dt UNION ALL
SELECT dt + INTERVAL 1 DAY FROM date_ranges
WHERE dt + INTERVAL 1 DAY <= '2019-12-31')
SELECT dt FROM date_ranges;
Other than the reason above there's a simple yet important reason why I include this option; it's because of leap years. We had one in 2020 so the total days in that year is actually 366 days instead of 365 days.
Here is a fiddle showing the difference using sequence engine and with recursive.
As you can see in the fiddle, the sequence engine query (for leap year) still return 365 rows and the last date of the year is 2020-12-30.. we're missing a day. That is caused by the numbering sequence constraint that we've defined (seq_1_to_365). Therefore, it might not be the best option to use sequence engine unless you're only using it on non-leap years..
Here is the complete query for the INSERT operation according to the question:
INSERT INTO food_user(NAME,re_date,re_day)
/*recursive statement here*/
WITH RECURSIVE date_ranges AS (
SELECT '2019-01-01' dt UNION ALL
SELECT dt + INTERVAL 1 DAY FROM date_ranges
WHERE dt + INTERVAL 1 DAY <= '2019-12-31')
/*select statement here*/
SELECT 'Alex',dt, dayname(dt) FROM date_ranges;
Demo fiddle
If you use MySQL,
You can try
insert into food_user(name, re_date, re_day) values("Hello", "2019-01-01", dayofweek("2019-01-01"));
If you want to insert all days from 2019-01-01 to 2019-12-31, you can use php or any other server side language to insert records.
If you are using Oracle, you can use PL/SQL feature to insert all of them
maybe this can help
insert into food_user (name,re_date,re_day) values ('Alex' , DATE_FORMAT(NOW(), "%Y-%m-%d") , DATE_FORMAT(NOW(), "%W"));
from https://www.w3schools.com/sql/func_mysql_date_format.asp
Related
I want to check if a dataset is older than the current month -1 day (so if it's the first of November it should still be older than October). This is my SQL:
SELECT *
FROM XY
WHERE DATE_FORMAT(calendar_day, '%Y-%m') <> DATE_FORMAT((CURRENT_DATE()-1, '%Y-%m');
But it doesn't work because of the second DATE_FORMAT. If I remove it, it works, but then it also compares the days and not the months. How do I solve this?
I want to check if a dataset is older than the current month -1
Don't use DATE_FORMAT() on a column for this type of query. Keep all date functions on the "current date". Functions on columns impede optimization.
I think this does what you want:
SELECT *
FROM XY
WHERE calendar_day <= LAST_DAY(CURRENT_DATE() - interval 1 day - interval 1 month);
Try this using year and month function:
SELECT *
FROM XY
WHERE (year(calendar_day) <> year(CURRENT_DATE()-1))
and (month(calendar_day)<>month(CURRENT_DATE()-1))
How to get 7 days before today date in mysql using query?
I want output like this example:-
Date Day
13/2/2016 Saturday
14/2/2016 Sunday
15/2/2016 Monday
16/2/2016 Tuesday
17/2/2016 Wednesday
18/2/2016 Thursday
19/2/2016 Friday
Note: There is no such table in mysql for date showing. I think using like CURDATE() function in mysql something like that.
The question was edited to clarify there are no tables.
MySQL (to my knowledge) has no sequence generator, and in order to prevent a procedure here's a trick you can use to generate a list of dates.
SELECT DATE(NOW() - INTERVAL n DAY) AS date,
DAYNAME(NOW() - INTERVAL n DAY) AS day
FROM (
SELECT 0 n
UNION SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
) q
ORDER BY day ASC
;
Note that this is a very cumbersome approach, imagine what a range of more dates would look like. If you need this for a one-shot operation, it'll be fine, if you are going to use this on a regular basis, you may want to create a procedure for it.
The table based answer (perhaps useful to others)
MySQL supports the DATE_ADD and DATE_SUB functions, which allows you to subtract an INTERVAL. Internally this is optimised to the following syntax, which you may find more flexible
SELECT *
FROM table
WHERE field >= NOW() - INTERVAL 7 DAY;
Most 'time units' are supported (MINUTE, HOUR, WEEK, etc) and you can replace the NOW() part with a field name too.
The DATE_ADD manual has some examples on how to use INTERVAL.
Basic syntax:
date + INTERVAL expr unit
date - INTERVAL expo unit
And implementation examples:
mysql> SELECT '2008-12-31 23:59:59' + INTERVAL 1 SECOND;
-> '2009-01-01 00:00:00'
mysql> SELECT INTERVAL 1 DAY + '2008-12-31';
-> '2009-01-01'
mysql> SELECT '2005-01-01' - INTERVAL 1 SECOND;
-> '2004-12-31 23:59:59'
The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1
I'm trying to query through historical data and I need to return data just from a 1 month period: 2 weeks back and 2 weeks forward,but I need the year to not matter.
So, if I was to make the query today I would want all rows with date between xxxx-06-31 and xxxx-07-27
Thanks in advance for the help!
EDIT:
I've tried two ways. both of which I believe will not work around the new year. One is to use datepart(day) and the other would be to simply take the year off of date and compare.
The best way to think of this problem is to convert your dates to a number between 0 and 365 corresponding to the day in the year. Then simply choosing dates where this difference is less than 14 gives you your two week window.
That will break down at the beginning or end of the year. But simple modular arithmetic gives you the answer.
Fortunately, MySQL has DAYOFYEAR(date), so it's not so complicated:
SELECT * FROM tbl t
WHERE
MOD(DAYOFYEAR(currdate) - DAYOFYEAR(t.the_date) + 365, 365) <= 14
OR MOD(DAYOFYEAR(t.the_date) - DAYOFYEAR(currdate) + 365, 365) <= 14
That extra + 365 is needed since MySQL's MOD will return negative numbers.
This answer doesn't account for leap years correctly. If the current year is not a leap year and the currdate is within 14 days of the end of the year, then you'll miss one day in Jan that you should have included. If you care about that, then you should replace 365 with [the number of days in the year - 1].
Supposed you have a date like this,
create table datelist
(
d date
);
insert into datelist values
('2012-07-01'),
('2011-06-29'),
('2012-07-02'),
('2010-07-05'),
('2012-05-31'),
('2010-06-30');
Try this query below,
SELECT d, date_format(d,'%Y-%b-%d')
FROM datelist
WHERE (MONTH(d) = 6 AND DAYOFMONTH(d) >= 30)
OR (MONTH(d) = 7 AND DAYOFMONTH(d) <= 27)
SQLFiddle Demo
Is it OK if the solution is terribly slow?
SELECT tbl.*
FROM tbl
INNER JOIN (SELECT COALESCE(DATE(CONCAT(yyyy, '-', MONTH(CURRENT_DATE), '-', DAYOFMONTH(CURRENT_DATE)),
DATE(CONCAT(yyyy, '-02-28'))) AS midpoint
FROM (SELECT DISTINCT(YEAR(d)) AS yyyy
FROM tbl) all_years) adjusted
ON tbl.datecol BETWEEN adjusted.midpoint - INTERVAL 2 WEEK
AND
adjusted.midpoint + INTERVAL 2 WEEK;
That computes all midpoints for all years in the data set, and then pulls records +- 2 weeks from any such midpoint, which handles end-of-year wrapping.
The COALESCE handles 02-29 on years without leapday (which MySQL will NULL-ify), forcing it down to 02-28.
I am trying to construct the SQL query, that should be executed as is
both on HSQL (v2.2.4) and MySQL (v5.1.36) server (if it can run also on DB2 v9, that would be wonderful bonus!)
The query is:
select count(*) from document where current_date - cast(indexing_date as date) <= ?
(here current_date is a standard HSQL/MySQL function and indexing_date is a column with type datetime, parameter ? is substituted by integer 20 which is the number of days).
The problem is that MySQL returns the difference between dates as between numbers while HSQL returns the difference in days (which is logical when you subtract date from date).
Also HSQL supports this syntax (but MySQL does not):
select count(*) from document where cast(indexing_date as date) between current_date - 20 day and current_date
while MySQL does not. I am aware about DATEDIFF() in MySQL, but as I said the solution should be inter-operable.
HSQLDB also supports this:
select count(*) from document where current_date - cast(indexing_date as date) <= cast(? as interval day)
and
select count(*) from document where cast(indexing_date as date) between current_date - '20' day and current_date
or
select count(*) from document where indexing_date >= current_date - interval '20' day
Also, from version 2.2.6, HSQLDB supports DATEDIFF(datevaluea, datevalueb), which returns the number of days between the two dates, as well as DAYS(datevalue), which returns the day number since the epoch.
db2:
SELECT COUNT(*)
FROM document
WHERE DATE(indexing_date) BETWEEN DATE(DAYS(CURRENT DATE) - 20) AND CURRENT DATE