Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select lines whose date-field is in a given month and year

My SQL table looks like this:

id (int) | date (date) | text1 (varchar) | text2 (varchar)

I want to select the lines whose date suits a given month and year, regardless of the day. Both month and year are given in the select-statement as integers. So the missing thing is the where-clause. Perhaps extract() is the thing I'm looking for, but I don't know how to use it with the two integers, e.g. 2011 and 02.

like image 540
oriander Avatar asked Feb 19 '11 18:02

oriander


People also ask

How do I select month and year from date in SQL?

To get the year and the month columns, use the EXTRACT(part FROM date) function. In this solution, the part argument is replaced by YEAR and MONTH to get the year and the month separately, each in its own column. You can learn more about EXTRACT() in the official MySQL documentation.

How do I select data by month in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function.

How do I get current month data in SQL query?

We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.

How do I select just the year from a date in SQL?

Use SQL Server's YEAR() function if you want to get the year part from a date. This function takes only one argument – a date, in one of the date and time or date data types. (In our example, the column BirthDate is a date data type). The argument can be a column name or an expression.


1 Answers

You can use extract:

SELECT * FROM yourtable
WHERE EXTRACT(month FROM "date") = 2
AND EXTRACT(year FROM "date") = 2011

But in this case you could also do this:

SELECT * FROM yourtable
WHERE "date" >= '2011-02-01' AND "date" < '2011-03-01'
like image 200
Mark Byers Avatar answered Oct 10 '22 16:10

Mark Byers