splitting date and inserting individual field in separate column in mysql - mysql

i have created a date table directly through phpmyadmin and i want to split the date(yyyy:mm:dd) into individual day, month and year and insert into separate field. Can anybody help me in the query used directly in phpmyadmin to perform above work?

Try:
UPDATE `table` SET `year` = YEAR(`date`), `month` = DATE_FORMAT(`date`, '%m'), `day` = DATE_FORMAT(`date`, '%d')
I've used DATE_FORMAT() rather than MONTH() and DAY() as the latter two remove leading zeros.

Related

SQL Server: Want to use between clause with dates, but dates in string form (YYYY.MM.DD)

Help! One column in my database is for dates. All of my dates are unfortunately in the String form (YYYY.MM.DD). I have a MASSIVE database (300+GB) so ideally would like to avoid transformations.
Is there a way I can select rows for dates in between YYYY.MM.DD and YYYY.MM.DD? What would the script look like?
Thank you!
If the months and days are stored with leading zeroes, the BETWEEN operator will work as expected. So will ORDER BY.
create table your_table (
date_value varchar(10) not null
);
insert into your_table values
('2013.01.01'), ('2013.01.13'), ('2013.01.30'), ('2013.01.31'),
('2013.02.01'), ('2013.02.13'), ('2013.02.28'), ('2013.02.31'),
('2013.03.01'), ('2013.03.15'), ('2013.03.30'), ('2013.03.31');
select date_value
from your_table
where date_value between '2013.01.01' and '2013-01-31'
order by date_value;
2013.01.01
2013.01.13
2013.01.30
One of the main problems with your structure is that you lose type safety. Look at this query.
select date_value
from your_table
where date_value between '2013.02.01' and '2013.02.31'
order by date_value;
2013.02.01
2013.02.13
2013.02.28
2013.02.31
If you'd used a column of type date or datetime or timestamp, the dbms would not have allowed inserting the values '2013.02.31', because that's not a value in the domain of date. It is a value in the domain of varchar. (And so is "Arrrrgh!", unless you've got a CHECK constraint on that column that severely restricts the acceptable values.)
Not good solution, but works (cost much performance).
You have formated date in order year, month, day (good order to compare strings, without transformation to datetime), so you can try
SELECT * FROM Table WHERE StringDate > '2013.07.10' AND StringDate < '2013.07.14'
It returns bad results if there are dates before year 1000 without leading zero ('999.07.14').
But I dont know how it works on big database.
SQL Fiddle
Between in SQL is inclusive of both bounds. If that is what you want, you can just use between:
where col between 'YYYY.MM.DD' and 'YYYY.MM.DD'
Where the two constants are whatever values you are looking for.
If you have an index on the column, then between (as well as >, >=, and so on) will use the index. You do not need to transform the values. If your constants are dates of one form or another, then you can use date_format() to create a string in the right format. For instance, to get dates within the past week:
where col >= date_format(adddate(now(), -7), '%Y.%m.%d')

Querying Where date_created without time is same as last_updated without time

In MySQL, I need to write a query (if possible) that finds all rows of a table where the date_created is the same as last_updated. The rub is that I need to ignore the time. Basically, I'm looking for user rows that were created and activated the same day (we don't store an activation date). So presumably the dates would be the same but the times may be different.
You could use the DATE() function, which returns only the date portion of a datetime value. This allows you to compare just the date portion of the values:
SELECT * FROM table_name
WHERE DATE(date_created) = DATE(last_updated)
The timezone may be relevant here. So you may want to cast the datetime values to the user's timezone prior to using the DATE() function, using CONVERT_TZ().
Try this:
SELECT *
FROM table_name
WHERE DATE_FORMAT(date_created, '%Y-%m-%d') = DATE_FORMAT(last_updated, '%Y-%m-%d')
not pretty but works:
SELECT *
FROM table_name
WHERE day(date_created) = day(last_updated) and
month(date_created) = month(last_updated) and
year(date_created) = year(last_updated)

Compare fileds with REGEXP in mysql 5.0

I would like to so a nested mysql request that is counting actions for each day like this:
SELECT `timestamp` AS `date`,
(SELECT COUNT('id')
FROM `actions` WHERE `timestamp` = `date`) AS `action_num`
FROM `actions`;
That would work great if it wasn't so that I need to calculate each day and all I got is each timestamp. If it was only a date it would work. So I thought if I can take out the date from the string and compare it this might work:
SELECT `timestamp` AS `date`,
(SELECT COUNT('id') FROM `actions`
WHERE `timestamp` REGEXP '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}' = `date`
REGEXP '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}') AS `action_num`
FROM `actions`;
But it did not work.
Any ideas on how to compare the dates from two timestamp fields directly in MySQL?
Thanks
Very easy, the inner query should be:
SELECT count(id) FROM actions
WHERE DATE(`timestamp`) = DATE(`date`) as action_num
See: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date
You can use DATEDIFF() function to compare the dates in MySQL,
and TIMESTAMPDIFF() for comparing timestamps , DATE() to get date information from timestamp.
More date and time functions and examples are available in MySQL's reference manual pages.

MySql, combining date and time column into a time stamp

I am guessing this is relatively simple to do, but I am unsure of the syntax. I have date and time columns that I want to combine to a timestamp column. how would I query this using a select?
Or you could use the built-in TIMESTAMP(date,time) function.
So then you would do something like this say from an Orders table...
SELECT OrderNumber, TIMESTAMP(date,time) as OrderTS, SalesPersonID
FROM Orders
Mysql does not seem to have a constructor for datetime such as datetime('2017-10-26', '09:28:00'). So you will have to treat the component part as string and use string concatenation function (Note mysql does not have the || operator for string concatenation). If you want the datetime type, you will have to cast it.
concat(datefield,' ',timefield) as date
select cast(concat('2017-10-26', ' ', '09:28:00') as datetime) as dt;
If it possible to use built-in function, just use it.
Any way here is an example to find records between given timestamps.
SELECT `id` FROM `ar_time` WHERE TIMESTAMP(`cdate`,`ctime`) BETWEEN fromTimeStamp AND nowTimeStamp;
For 24hr time
TIMESTAMP(Date, STR_TO_DATE(Time, '%h:%i %p'))
SELECT * FROM tablename WHERE TIMESTAMP(datecol, timecol) > '2015-01-01 12:00:00';
O.P. did say SELECT but in case anyone wants to add a timestamp column:
ALTER TABLE `t` ADD COLUMN `stamp` TIMESTAMP;
UPDATE `t` SET `stamp` = STR_TO_DATE(CONCAT(`Date`, ' ', `Time`), '%m/%d/%Y %H:%i:%s');
Adjust format strings to taste.
concat('2021-12-31', ' ', '07:00:00')
it worked in an INSERT procedure.

Mysql - selecting year from a unix timestamp

I am using this:
SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE year = 2009;
but it gives me an error:
Unknown column 'year' in 'where clause'SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE year = 2009
Both "my_unix_timestamp_column" and "table_name" are correct, i dont know why it gives me this!!!
I'm using PHP 5.3.0
I'm not quite sure whether this is due to YEAR being a reserved word in MySQL or because it wants you to do something along the lines of:
SELECT
FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year
FROM
table_name
WHERE
FROM_UNIXTIME(my_unix_timestamp_column, '%Y') = 2009;
Can't remember whether the last issue is only relevant to GROUPings :S
SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS `year`
FROM table_name
HAVING `year` = 2009
Unlike WHERE clause, HAVING clause can reference the SELECT clause aliases.
More index efficient way would be:
SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS `year`
FROM table_name
WHERE my_unix_timestamp_column >= UNIX_TIMESTAMP('2009-01-01')
AND my_unix_timestamp_column < UNIX_TIMESTAMP('2010-01-01')
Another alternative, avoiding repetition of a biggish function call:
SELECT year
FROM (SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year
FROM table_name) AS list_of_years
WHERE year = 2009;
You might still need to use back-quotes around the word 'year' to avoid conflicts with YEAR as a keyword. The optimizer should not need to create an intermediate table to answer this query.
You can't use a column created the SELECT section in your WHERE clause
replace the year variable in your where clause with the actual function to create that column (aka FROM_UNIXTIME(my_unix_timestamp_column, '%Y') ) and you should be fine.
This is because the SELECT section of your query isn't executed until the WHERE section has finished matching rows to return.
The WHERE part is executed before the aliasing in the field list. Best thing is to use BETWEEN in the WHERE clause so an index can be used.
I haven't tried it myself, but would this work?
SELECT YEAR(my_unix_timestamp_column) AS 'year'
FROM table_name
WHERE YEAR(my_unix_timestamp_column) = 2009;
Ref link: https://www.w3schools.com/sql/func_mysql_year.asp