Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select rows with date like

In MySQL I have this query

SELECT DISTINCT date, descr FROM book ORDER BY date

Date is in format yyyy-mm-dd

I want to select only the the books from January 2012. I have tried to use like but that does not work.

Any ideas?

like image 382
Axxess Avatar asked Aug 31 '12 13:08

Axxess


People also ask

How do I select a specific date in MySQL?

You can use DATE() from MySQL to select records with a particular date. The syntax is as follows. SELECT *from yourTableName WHERE DATE(yourDateColumnName)='anyDate'; To understand the above syntax, let us first create a table.

How do I select a row in a date range in SQL?

Select rows with date range using DATE() function Date() function will extract the date part from the datetime expression in MySQL.

How do I query between two dates using MySQL?

select *from yourTableName where yourColumnName between 'yourStartingDate' and curdate().


1 Answers

Using DATE_FORMAT function

SELECT DISTINCT date, descr FROM book 
WHERE DATE_FORMAT(date, '%Y %m') = DATE_FORMAT('2012-01-01', '%Y %m')
ORDER BY date

Or using MONTH and YEAR functions

SELECT DISTINCT date, descr FROM book 
WHERE Month(date) = Month('2012-01-01')
AND Year(date) = Year('2012-01-01')
ORDER BY date;

Or using BETWEEN functions

SELECT DISTINCT date, descr FROM book 
WHERE date BETWEEN '2012-01-01'
AND '2012-01-31'
ORDER BY date;

Or using <= and >= operators

SELECT DISTINCT date, descr FROM book 
WHERE date >= '2012-01-01'
AND date <= '2012-01-31'
ORDER BY date;

See this SQLFiddle

like image 156
Himanshu Jansari Avatar answered Oct 04 '22 22:10

Himanshu Jansari