Trying To Pull Date Out Of MySQL - mysql

But I cannot Format it? Date is saved currently in the database under a 'text' type structure and saved a '1/1/2000'. I'm trying to pull this info out of the database and DATE_FORMAT it to '01/01/2000' (2 digit day & month) but it's showing all dates as 12/31/1969? Here's the query i'm using:
$query = "SELECT Event_Title, Event_Details, Event_Time, Event_ID, DATE_FORMAT(Start_Date, '%m/%d/%Y') FROM tevents ORDER by Start_Date DESC";
Is there something wrong with my query?
database:
Rows Start_Date Ascending
1 04/30/2014
1 05/03/2014
1 05/1/2014
1 05/3/2014
3 5/1/2014
1 5/15/2014
1 5/2/2014
2 5/20/2014
1 5/23/2014
1 5/24/2014
5 5/3/2014
3 5/6/2014
1 6/21/2014
1 6/23/2014
1 6/24/2014
1 6/25/2014
1 6/26/2014
1 6/27/2014
1 6/28/2014
1 6/5/2014
1 6/6/2014

Date stored as varchar or TEXT makes life miserable so better to store as date or datetime data type.
In your case you need to use str_to_date() for conversion before doing any format
$query = "SELECT
Event_Title,
Event_Details,
Event_Time,
Event_ID,
date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%m/%d/%Y') as Start_Date
FROM tevents
ORDER by date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%Y-%m-%d') DESC";
If its just for ordering then no need to do the
date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%m/%d/%Y') as Start_Date
You can directly select since its converting to the same format, for ordering its needed.

If you put a question into a closed envelope and give it to the neighbour, why can't he answer you?
'Text' means 'do not bother about the contents' for MySQL, it normally does not care about the content. If you use a DATE datatype, things get much easier at reading (and sorting works, and ranges, and where-clauses...) and a bit difficult on writing - you should format the dates into the form '2014-05-01' in the program code.

Related

mysql - how to select data from next month

i have table with id, date_from, date_to fileds.
I need to find all the data where date_to +1 month is equal to condition
for example>
if data in date_to field is 2015-06-01 and WHERE condition is 2015-07-01 i should get the result
SELECT *, (date_to + INTERVAL 1 MONTH) as 'next' FROM table_name WHERE 'next'='2015-07-01'
this is my query, that obviously doesn't work ;)
Tnx in adavance
First thing you can not use alias in the where condition and also the condition is wrong. It will be
SELECT * FROM table_name
WHERE
date_add(date_to,interval 1 month)='2015-07-01'
Now note that for large data-set its not a good idea to use function on the date filed since even if the field is index it will fail to use index. So better to use the function on the data to be filtered rather than on the field. So the above query could be written as
SELECT * FROM table_name
WHERE
date_to= date_sub('2015-07-01',interval 1 month)

mysql query to fetch the quarter month from table

Table name: activity
Field name: ProcessYM
I have mysql data like below.
ProcessYM
==========
201312
201311
201310
201309
201308
201307
201306
201305
201304
201303
201302
201301
201212
201211
201210
201209
201208
201207
201206
I want to fetch the result like below. I mean, the mysql query to fetch the every quarter of the year like 201312, 201309, 201306, 201303, 201212, 201209.. and so on.
Actual Output I expect
=======================
ProcessYM
201312
201309
201306
201303
201212
201209
201206
I have tried the below query, but it does not produce the expected result.
SELECT distinct `ActProcessYM` from `activity` where `ActProcessYM`%3=0 order by ActProcessYM desc
Output of above query
=====================
201312
201309
201306
201303
201210
201207
It is much appreciated for your smart reply.
You need to modulo of the month part only. Your query is implicitly casting your ProcessYM as an INT.
For example:
SELECT DISTINCT ProcessYM
FROM activity
WHERE RIGHT(ProcessYM,2)%3=0
ORDER BY ProcessYM DESC
fiddle
you should retrieve the last two digits from field value and do the logic as you are doing.
SELECT distinct `ActProcessYM` from `activity` where substring(ActProcessYM,5,2)%3=0 order by ActProcessYM desc
Here's a not-so-quick-and-dirty way of handing this date processing. I believe you're looking for a MySQL formula like this:
yyyymm = TRUNC_QUARTER(yyyymm)
That is, you are looking for a function that converts any yyyymm month notation into a notation that shows the month that ends the quarter in question.
Let's start with an expression that converts any particular DATETIME expression to the DATE of the beginning of the quarter.
DATE(CONCAT(YEAR(value),'-', 1 + 3*(QUARTER(value)-1),'-01'))
This takes a timestamp (e.g. '2011-04-20 11:15:01') and turns it into the date of the starting of the quarter. (e.g. '2011-04-01')
Having things in this date form is helpful because you can use them for date arithmetic. For example, you can get the last day of that quarter like this.
DATE(CONCAT(YEAR(value),'-', 1 + 3*(QUARTER(value)-1),'-01'))
+ INTERVAL 1 QUARTER - INTERVAL 1 DAY
Here's a writeup on all this: http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
I've found it helpful to try to stick to the date datatype when processing time series data.
You need to separate out the month value before doing the modulo 3 (% 3). Doing a modulo 100 first will do it:
(ProcessYM % 100) % 3) = 0
or
mod(mod(ProcessYM,100),3) = 0
Try this,
SELECT distinct `ProcessYM` from `activity` where SUBSTRING(`ProcessYM`,5,2)%3=0 order by ProcessYM desc

Mysql Select with Dates and maybe Case when

im having a problem where i cant think of a solution, maybe im having a bad table-structure or i just dont know enough about mysql select commands to think of a good solution. Maybe you can help me out:
So i got a table that has a Column with the Date-format (yyyy-mm-dd) i wanted to select all upcoming dates so i did:
SELECT * WHERE date >= now.
This worked kinda well but i also got "dates" where only the year is entered (2014-00-00) i also wanted to select these but "now" is already bigger so i made another column with the year only and if the month, date or both arent known i will use 0000-00-00 and the Column "year" now i could select like this:
SELECT * WHERE date >= now AND year >=now(year)
Now all entrys with 0000-00-00 wont be selected. If i use OR the entrys from last year will be shown.
So thats my problem, is there any way i can change my table so i can have entries with only the year or only year and month and of course all together? I already considered get rid of the date-format and use simple INT with seperated columns for year, month and date. But i think i will have the same problem.
Sometimes i just want to do a capsuled select like
SELECT *
WHERE (date >= now AND year >= now(year))
OR date == "0000-00-00" (i know that this doesnt work)
If I understood your problem correctly, you could use this request:
WHERE (date >= now OR year > now(year))
There is probably a simpler way though, that would preserve your design, like initializing at January 1st (01-01) instead of 00-00
I think you can use this code:
$_SESSION['month'] = //set here your selected month
$_SESSION['year'] = //set here your selected year
SELECT * FROM table WHERE DATEPART(m,date) >= '".$_SESSION['month']."' AND DATEPART(yyyy,year) >= '".$_SESSION['year']."' AND date <> '0000-00-00'
Change your table structure format. Actually just allow for that field to have null value when not entered. By default it will be null then. You shouldn't be storing 0000-00-00 as a value for Date type field. I would rather leave it as null , or as suggested in some of previous answers, initialize it with some other date. It would be much easier to manipulate with database then.
the problem is that half of you write is not MySQL and your database schema is terrible...
You have the following problems:
column data date does not have the date data type.
To fix it, you need to add a cast to the select statement eg. cast(datecolumn as date)
select * from table where cast(datecolumn as date) >= '2014-01-10';
the way to use now date is using the now function.
select now(), date(now());
result> 2014-01-10 11:11:36, 2014-01-10
select * from table where cast(datecolumn as date) >= date(now());
Because your datecolumn is not a date (2014-00-00 is not a valid date), you need to use string manipulation to extract the year.
select substring('2014-01-01', 1,4)
result> 2014
select * from table where substring(datecolumn, 1,4) = year(now());
The comparassion operator is = and not ==
the select statement syntax looks like this (pay attention because you are missing the table in your statement)
select * from [Table] where [column] = condition ...
You probably need or instead of ands, therefore your query should look like this:
select * from FooTable where
cast(datecolumn as date) >= date(now())
or substring(datecolumn, 1,4) >= year(now())
or datecolumn = '0000-00-00'
You should use something like phpmyAdmin or mySQL workbench to test your sql queries before try to use them on php, java or whatever is your programing language.

How to check if selected date range is between another date range

I am in the situation where i want to match a date range with another date range, it might be simple but i am stuck at it.
Below is table structure
Table - lifecycles
life_id
life_start_date
life_end_date
then a few records as below
1 - 07/23/2013 - 07/24/2013
2 - 07/15/2013 - 07/25/2015
3 - 03/10/2013 - 03/10/2014
Now i want to search these records by date range and want to see if some life exists in that range; e.g. i want to find the lives between 08/01/2013 - 01/01/2014
As expected result it should select the life#2 and life#3
How can this be done with MySQL query?
Any help is highly appreciated.
This query should do it:
SELECT
*
FROM
lifecycles
WHERE
str_to_date(life_start_date, '%m/%d/%Y') <= '2014-01-01'
AND str_to_date(life_end_date, '%m/%d/%Y') >= '2013-08-01';
Which basically means life hasn't started before the end of the range you are looking for, and life didn't end before the range start.
Since you keep dates in VARCHAR format, you need to use str_to_date function, which is bad since MySQL won't be able to utilize any possible indexes you have on start_date or end_date columns.
This might help you.
SELECT SUM( IF( '2014-01-02' BETWEEN from_date AND to_date, 1, 0 ) ) AS from_exist,
SUM( IF( '2014-02-12' BETWEEN from_date AND to_date, 1, 0 ) ) AS to_exist
FROM date_range
So based on the results you can check whether date is between existing date range or not.
So you want to exclude lifes that are ended BEFORE 08/01/2013 and the ones that are not started AFTER 01/01/2014. This should work:
SELECT *
FROM lifecycles as alive
WHERE NOT EXISTS (
SELECT 1
FROM lifecycles as dead
WHERE dead.life_id = alive.life_id
AND (str_to_date(life_start_date, '%m/%d/%Y') > '2014-01-01'
OR str_to_date(life_end_date, '%m/%d/%Y') < '2013-08-01'))

How to add 1 year to date stored as varchar?

How can add 1 year to a date value stored in the DB as varchar (format: "2011.03")?
I'm trying with this, but returns NULL :(
DATE_FORMAT(DATE_ADD(STR_TO_DATE('2011.03', '%Y.%m'), INTERVAL 1 YEAR),'%Y.%m')
Thank you very much!
edit.: this is the query i want to use in:
SELECT DISTINCT column FROM table WHERE column BETWEEN '2011.03' AND DATE_FORMAT(DATE_ADD(STR_TO_DATE('2011.03', '%Y.%m'), INTERVAL 1 YEAR),'%Y.%m') ORDER BY column DESC
("2011.03" is a parameter value and comes outside)
What you are trying is giving correct result
Try :
SELECT DATE_FORMAT(DATE_ADD(STR_TO_DATE('2011.03', '%Y.%m'), INTERVAL 1 YEAR),'%Y.%m')
it's giving 2012.03.
Edit:
You can use below trick to make it workable in mysql version > 5.0
Add month with date because in Mysql version > 5.0 str_to_date() sometimes would return NULL if the %D format specifier was not the last specifier in the format string input.
Try below:
SELECT DATE_FORMAT(DATE_ADD(STR_TO_DATE('2011.03.01', '%Y.%m.%d'), INTERVAL 1 YEAR),'%Y.%m')