I have a problem saving 'contable dates' because every month on this way has 30 days each. I need to save a element (2014-02-30) using a type date-like (not a varchar/text/blob/etc) to save this because in this project we need that. Is it possible?
Saving such a DATE "value" in a DATE or DATETIME column is possible using the sql_mode ALLOW_INVALID_DATES and no strict mode:
ALLOW_INVALID_DATES
Do not perform full checking of dates. Check only that the month is in
the range from 1 to 12 and the day is in the range from 1 to 31. This
is very convenient for Web applications where you obtain year, month,
and day in three different fields and you want to store exactly what
the user inserted (without date validation). This mode applies to DATE
and DATETIME columns. It does not apply TIMESTAMP columns, which
always require a valid date.
So checking the date for an allowed contable date could be done with triggers, since there's no other check too. I assume that for this application the 31th of each month would be an invalid date.
Example:
CREATE TABLE example (
contable_date DATE NOT NULL
) ENGINE=INNODB;
-- set the sql_mode (here for the session)
SET ##SESSION.sql_mode = 'ALLOW_INVALID_DATES';
INSERT INTO example (contable_date) VALUES ("2014-02-30");
SELECT
DAY(contable_date) as cday,
MONTH(contable_date) as cmonth,
TIMESTAMPDIFF(DAY, contable_date, '2014-03-30') as cdiff
FROM
example;
Result:
cday cmonth cdiff
-------------------
30 2 28
Demo
Using MySQL Workbench I get with
SELECT contable_date FROM example
following result:
contable_date
-------------
2014-02-30
but this doesn't work at sqlfiddle.com.
I wouldn't recommend this though, especially because one's not able to use strict SQL mode. One should consider the effect on the date and time functions too.
Related
I have a week column with week numbers as w0, w1, w2.... I am trying to get last last six weeks data. Here's the sql query I am using.
SELECT * FROM week
WHERE uid = '9df984da-4318-1035-9589-493e89385fad'
AND report_week BETWEEN `'w52' AND 'w5'`;
'w52' is essentially week 52 in December 2015 and 'w5' is Jan 2016. The 'between' seems to not work. Whats the best way to get data from the above two weeks?
Here's the CREATE TABLE statement:
CREATE TABLE `week` (`uid` VARCHAR(255) DEFAULT '' NOT NULL,
`report_week` VARCHAR(7) NOT NULL,
`report_files_active` BIGINT DEFAULT NULL);
Essentially this table is getting populated from other table which has date column. It uses dates from other table and summarizes weekly data into this.
Any help is appreciated.
Refer to this SO Discussion which details the reasons for a problem similar to yours.
BETWEEN 'a' and 'b' actually matches to columnValue >='a' and columnValue <= 'b'
In your case w52 is greater than w5 due to lexicographic ordering of Strings - this means that the BETWEEN clause will never return a true (think about it as equivalent to saying BETWEEN 10 and 1 instead of BETWEEN 1 and 10.
Edit to my response:
Refrain from storing the week value as a string. Instead here are a couple of approaches in order of their preference:
Have a timestamp column. You can easily then use MySQL query
facilities to extract the week information out of this. For a
reference see this post.
Maintain two columns - YEAR, WEEKNO where YEAR will store values
like 2015, 2016 etc and WEEKNO will store the week number.
This way you can query data for any week in any year.
please show me table structure and DB name because it different for other, if it is any timestamp then we can use BETWEEN 'systemdate' AND 'systemdate-6'
I have the following mysql table:
tasks:
=====================
tid
status
desc
duedate
And i have the following records in that table:
records
===========================
1
active
Test description
08/15/2014
2
active
Another description
08/31/204
I am trying to get the days that there is a task for, in that particular month. I have the following query but when i run it it gets both records but "day" is null on both of them for some reason. Can someone please help me with this.
MYSQL QUERY
====================
SELECT DATE_FORMAT(due_date,'%d') AS day FROM tasks WHERE due_date BETWEEN '08/01/2014' AND '08/31/2014'
Try:
SELECT DAY(due_date) AS day
FROM tasks
WHERE due_date >= '2014-08'
AND due_date < '2014-09';
DAY() is a better function for what you want and I prefer using >= and < than BETWEEN for date comparisons, as it allows you to specify precise ranges more easily. Here, for example, you don't need to know the number of days in the month.
I have also used the default date format, which is preferable. If you need the, in my opinion, cray American date format, use DATE_FORMAT() in your SELECT.
This will only work with DATE, DATETIME and TIMESTAMP columns, which is how your due_date should be stored, preferably DATE.
UPDATE
To convert the VARCHAR column to DATE run:
UPDATE tasks SET due_date=STR_TO_DATE(due_date,'%m/%d/%Y')
Then change the type. Also remember to change your INSERT statements to use the default format.
You've got to convert those "date" strings to proper date values with STR_TO_DATE:
SELECT
DAY(STR_TO_DATE(due_date,'%m/%d/%Y')) AS day
FROM tasks
WHERE
STR_TO_DATE(due_date, '%m/%d/%Y')
BETWEEN STR_TO_DATE('08/01/2014' '%m/%d/%Y')
AND STR_TO_DATE('08/31/2014', '%m/%d/%Y')
else you're comparing strings instead.
Note:
It would be better to use a proper DATE or DATETIME column instead.
With the current VARCHAR format MySQL is unable to use indexes. That's very bad for performance.
You can convert your data by adding another column to your table:
ALTER TABLE tasks
ADD COLUMN new_due_date DATE;
Then you use an UPDATE statement to fill this new column
UPDATE tasks
SET new_due_date = STR_TO_DATE(due_date, '%m/%d/%Y');
If you don't need your old column anymore then you can delete this column and modify the new column to have the name of the old one. Then you will have your table with all your data in a DATE column.
I generally use datetime field to store created_time updated time of data within an application.
But now i have come across a database table where they have kept date and time separate fields in table.
So what are the schema in which two of these should be used and why?
What are pros and cons attached with using of two?
There is a huge difference in performance when using DATE field above DATETIME field. I have a table with more then 4.000.000 records and for testing purposes I added 2 fields with both their own index. One using DATETIME and the other field using DATE.
I disabled MySQL query cache to be able to test properly and looped over the same query for 1000x:
SELECT * FROM `logs` WHERE `dt` BETWEEN '2015-04-01' AND '2015-05-01' LIMIT 10000,10;
DATETIME INDEX:
197.564 seconds.
SELECT * FROM `logs` WHERE `d` BETWEEN '2015-04-01' AND '2015-05-01' LIMIT 10000,10;
DATE INDEX:
107.577 seconds.
Using a date indexed field has a performance improvement of: 45.55%!!
So I would say if you are expecting a lot of data in your table please consider in separating the date from the time with their own index.
I tend to think there are basically no advantages to storing the date and time in separate fields. MySQL offers very convenient functions for extracting the date and time parts of a datetime value.
Okay. There can be some efficiency reasons. In MySQL, you can put separate indexes on the fields. So, if you want to search for particular times, for instance, then a query that counts by hours of the day (for instance) can use an index on the time field. An index on a datetime field would not be used in this case. A separate date field might make it easier to write a query that will use the date index, but, strictly speaking, a datetime should also work.
The one time where I've seen dates and times stored separately is in a trading system. In this case, the trade has a valuation date. The valuation time is something like "NY Open" or "London Close" -- this is not a real time value. It is a description of the time of day used for valuation.
The tricky part is when you have to do date arithmetic on a time value and you do not want a date portion coming into the mix. Ex:
myapptdate = 2014-01-02 09:00:00
Select such and such where myapptdate between 2014-01-02 07:00:00 and 2014-01-02 13:00:00
1900-01-02 07:00:00
2014-01-02 07:00:00
One difference I found is using BETWEEN for dates with non-zero time.
Imagine a search with "between dates" filter. Standard user's expectation is it will return records from the end day as well, so using DATETIME you have to always add an extra day for the BETWEEN to work as expected, while using DATE you only pass what user entered, with no extra logic needed.
So query
SELECT * FROM mytable WHERE mydate BETWEEN '2020-06-24' AND '2020-06-25'
will return a record for 2020-06-25 16:30:00, while query:
SELECT * FROM mytable WHERE mydatetime BETWEEN '2020-06-24' AND '2020-06-25'
won't - you'd have to add an extra day:
SELECT * FROM mytable WHERE mydatetime BETWEEN '2020-06-24' AND '2020-06-26'
But as victor diaz mentioned, doing datetime calculations with date+time would be a super inefficient nightmare and far worse, than just adding a day to the second datetime. Therefore I'd only use DATE if the time is irrelevant, or as a "cache" for speeding queries up for date lookups (see Elwin's answer).
I have a scenario where I want to be able to SELECT rows from a MySQL table, but exclude rows where the current time-of-day is inside a time-range.
Example:
The "quiet" period for one row is 10pm - 8:30am.
My SQL SELECT statement should not return that row if the current server time is after 10pm or before 8:30am.
Example 2: The "quiet period" is NULL and ignored.
Example 3: A new row is created with a quiet period from 9:53am to 9:55am. If the current server time is in that 2-minute window, the row is not returned by the SELECT.
My question:
What data format would you use in the database, and how would you write the query?
I have thought about a few different approaches (defining start_time as one column and duration as another, defining both in seconds... or using Date stamps... or whatever). None of them seem ideal and require a lot of calculation.
Thanks!
I would store the start and end dates as MySQL native TIME fields.
You would need to consider ranges that span midnight as two separate ranges but you would be able to query the table like this, To find all current quiet periods
SELECT DISTINCT name FROM `quiet_periods`
WHERE start_time<=CURTIME() AND CURTIME()<=end_time
Or to find all non-active quiet periods
SELECT name FROM quiet_periods WHERE name NOT IN (
SELECT name FROM `quiet_periods`
WHERE start_time<=CURTIME() AND CURTIME()<=end_time
)
So with sample data
id -- name -- start_time -- end_time
1 -- late_night -- 00:00:00 -- 08:30:00
2 -- late_night -- 22:00:00 -- 23:59:59
3 -- null_period -- NULL -- NULL
4 -- nearly_10am -- 09:53:00 -- 09:55:00
At 11pm this would return
null_period
nearly_10am
from the second query.
Depending on performance and how many rows you had you might want to refactor the second query into a JOIN and probably add the relevant INDEXes too.
I have a PHP application that stores PHP datetime to my MySQL table. I did not noticed that the php server is using wrong timezone settings, so all the date that is stored in the table is incorrect. My timezone is GMT+8 but the PHP 'date.timezone' was GMT+0, so I need to add 8 hours to all existing date value in the table.
current data:
ID,session_start,session_close,total_sale
1,2012-01-01 01:35:33,2012-01-01 09:35:33,8211.9
2,2012-01-02 01:32:31,2012-01-02 09:46:54,4323.56
3,2012-01-03 01:21:38,2012-01-03 09:32:21,8732.33
desired data:
ID,session_start,session_close,total_sale
1,2012-01-01 09:35:33,2012-01-01 17:35:33,8211.9
2,2012-01-02 09:32:31,2012-01-02 17:46:54,4323.56
3,2012-01-03 09:21:38,2012-01-03 17:32:21,8732.33
I need to fix the datetime for all the data in my mysql table (add 8 hours more to the original datetime value, to be precise).
I know this can be done by writing a simple PHP script to loop over all rows in that table and modify the datetime value as needed, but it will be fun (and cool too!) if somebody can show me this can be done in MySQL.
UPDATE tablename SET
session_start=DATE_ADD(session_start INTERVAL 8 HOUR),
session_close=DATE_ADD(session_close INTERVAL 8 HOUR)
WHERE
whatever