MySQL Performance DATE_FORMAT() vs YEAR() AND MONTH() - mysql

Which is better for performance when looking for timestamps in current month and year?
SELECT *
FROM mytable
WHERE YEAR(CURRENT_TIMESTAMP) = YEAR(mytable.timestamp)
AND MONTH(CURRENT_TIMESTAMP) = MONTH(mytable.timestamp)
OR
SELECT *
FROM mytable
WHERE DATE_FORMAT(CURRENT_TIMESTAMP,'%m-%Y') = DATE_FORMAT(mytable.timestamp,'%m-%Y')

For better perfomance and able to use index in mytable.timestamp, truncate the current date to month.
SELECT DATE_FORMAT(CURRENT_TIMESTAMP, '%Y-%m-01')
This create a constant value and you can index search for it.
And then you can get all the record from this month
SELECT *
FROM mytable
WHERE mytable.timestamp >= DATE_FORMAT(CURRENT_TIMESTAMP, '%Y-%m-01')

Related

How to check if datetime equal tomorrow in MySQL

I want to retrieve mysql table data if the data created_at Datetime column equal to tomorrow date, for example:
SELECT * FROM sales_order where created_at = tomorrow_date;
You can use the following solution, using DATEDIFF and DATE_ADD:
SELECT *
FROM sales_order
WHERE DATEDIFF(created_at, DATE_ADD(CURDATE(), INTERVAL 1 DAY)) = 0;
or a simpler solution only using DATEDIFF:
SELECT *
FROM sales_order
WHERE DATEDIFF(created_at, CURDATE()) = 1
DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation. - from MySQL docs.
SELECT * FROM sales_order where created_at = CURDATE() + 1;

How to select year in sql statement

My code:
$results = $GLOBALS['wpdb']->get_results( 'SELECT * FROM myTable WHERE date = 2014 ORDER BY id DESC', object );
The problem is date is stored in this format: 2014-01-01
So how do I select just the year ( I don't care about month and day for the time being ).
Thanks
Use the year() function:
WHERE year(date) = 2014
or use explicit comparisons:
WHERE (date >= '2014-01-01' and date < '2015-01-01')
The latter is better because it can make use of an index on the date column.
Try this Query :
SELECT * FROM myTable WHERE year(`date`)='2014' ORDER BY id DESC
Try this:
SELECT * FROM myTable WHERE date >= '2014-01-01 00:00:00' ORDER BY id DESC
To select all rows where the year of a date column (called date_col) is equal to 2014 use the year function:
SELECT * FROM `tbl` WHERE Year(`date_col`) = '2014';
You can select year for get posts with query_posts(); parameter is year. Example: query_posts("year=2014"); This is not full question for you, only alternative..

How to convert a mysql datetime column to just date?

Here is an explanation of how my table is set up (in sqlfiddle)
http://sqlfiddle.com/#!2/86a54d/2
Basically, I have two columns. One is a varchar and contains a name. The other is a datetime and contains a certain date with a time.
I want to select rows where the date in the datetime matches today's date. I have tried things like...
select * from alerts_to_send where date_to_send = now()
select * from alerts_to_send where date_to_send = curdate()
I'm not exactly where to go from here... Any ideas would be greatly appreciated :)
Just to re-clarify, I want to select the rows where today's date matches the date part of my datetime type column.
try this
select * from alerts_to_send
where DATE_FORMAT(date_to_send,'%m-%d-%Y') = DATE_FORMAT(now(),'%m-%d-%Y')
fiddle
You can use the date_format function for mysql
select * from alerts_to_send where date_format(date_to_send, "%m/%d/%Y") = date_format(now(), "%m/%d/%Y")
Here is reference to date_format: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
An alternative to date_format function you can convert the datetime to date:
select * from alerts_to_send where cast(date_to_send as date) = curdate()
It could be even shorter:
select * from alerts_to_send where date(date_to_send) = date(now())
But you will have problem with using index on it so better will be:
select * from alerts_to_send where date_to_send >= date(now()) and date_to_send < date(now()) + INTERVAL 1 DAY

Optimize sql query - select in select

Which is the best method for optimizing the select in select mysql query ?
This is my example:
SELECT count(distinct email)
FROM emails_stats
WHERE DATE_FORMAT(time, '%Y-%m-%d') >= '2012-12-12'
and email in (SELECT email
FROM `reminder`
WHERE DATE_FORMAT(time, '%Y-%m-%d') = '2012-12-12')
My database has over 500k entries.
SELECT count(distinct emails_stats.email)
FROM emails_stats
JOIN reminder ON emails_stats.email= reminder.email
WHERE
emails_stats.time >= CAST('2012-12-12 00:00:00' AS datetime) AND
(reminder.time BETWEEN CAST('2012-12-12 00:00:00' AS datetime) AND CAST('2012-12-12 23:59:59' AS datetime));
If you use date_format() with the table fields, mysql will need to go through each row in the table, because it needs to get the result of that date_format() function to be able to compare the value with your given string. To make it faster, create an index for the 'time' fields and use this query instead. That way mysql can determine which rows it needs just by looking up the index.
Use an exists clause instead:
SELECT count(distinct email)
FROM emails_stats
WHERE DATE_FORMAT(time, '%Y-%m-%d') >= '2012-12-12'
and exists (SELECT 1
FROM `reminder`
WHERE emails_stats.email = `reminder`.email
and DATE_FORMAT(time, '%Y-%m-%d') = '2012-12-12')
the best method is to use join here like
SELECT count(distinct emails_stats.email)
FROM emails_stats
JOIN reminder ON emails_stats.email= reminder.email
WHERE DATE_FORMAT(emails_stats.time, '%Y-%m-%d') >= '2012-12-12';

Mysql - Subquery with date and like

I have a table with a column date (type mysql date : yyyy-mm-dd)
I have done this request:
Select Month(MAX(date)) AS last_month, YEAR(MAX(date)) AS last_year FROM mytable
to get the last year and last month.
I want for this last year and last month select all data in one request.
How can I use something like:
Select * from mytable where date like 'last_year-last_month-%'
this in sub-query ??
Is the table being update continuously?
If so, then you can go without the subqueries since they will slow the query down by quite a lot.
This selects everything from the current month.
SELECT * FROM mytable
WHERE MONTH(date) = MONTH(NOW())
AND YEAR(date) = YEAR(NOW())
ORDER BY date ASC
And this one selects everything from the current and last year.
SELECT * FROM mytable
WHERE YEAR(date) > YEAR(NOW())-1
ORDER BY date ASC
This should do the trick (maybe not the best performing solution though):
SELECT * FROM mytable
WHERE MONTH(date) = (SELECT MONTH(MAX(date) FROM mytable))
AND YEAR(date) = (SELECT YEAR(MAX(date) FROM mytable));
EDIT: Corrected brackets.
Thanks for alls,
here is the good request :
SELECT * FROM mytable
WHERE MONTH(date) = (select Month(MAX(date)) FROM mytable)
AND YEAR(date) = (select YEAR(MAX(date)) FROM mytable)
ORDER BY date ASC