Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get month from date in mysql

I want to be able to fetch results from mysql with a statement like this:

SELECT *    FROM table   WHERE amount > 1000  

But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:

SELECT *    FROM table   WHERE amount > 1000     AND dateStart = MONTH('$m')    

...$m being a month but it gave error.

In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?

like image 455
netrox Avatar asked Jan 11 '10 03:01

netrox


People also ask

What does the month () return in MySQL?

MONTH() function in MySQL is used to find a month from the given date. It returns 0 when the month part for the date is 0 otherwise it returns month value between 1 and 12. date : The date or DateTime from which we want to extract the month.

How do I convert a date to a month in SQL?

To get a month from a date field in SQL Server, use the MONTH() function. This function takes only one argument – the date. This can be a date or date and time data type.

Is month MySQL function?

MySQL - MONTH() Function The MYSQL MONTH() function is used to retrieve and return the MONTH of the given date or, date time expression. This function returns a numerical value ranging from 1 to 12 representing the month (January to December).

How do I get data from a specific month in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function. The syntax is as follows. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):

SELECT *    FROM table   WHERE amount > 1000     AND MONTH(dateStart) = {$m} 

Caveats:


  • Mind that you are using mysql_escape_string or you risk SQL injection attacks.
  • Function calls on columns means that an index, if one exists, can not be used

Alternatives:


Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:

WHERE startdate BETWEEN STR_TO_DATE([start_date], [format])                      AND STR_TO_DATE([end_date], [format]) 

See the documentation for formatting syntax.

Reference:


  • MONTH
  • YEAR
  • BETWEEN
  • STR_TO_DATE
like image 107
OMG Ponies Avatar answered Oct 02 '22 20:10

OMG Ponies


Use the month() function.

select month(now()); 
like image 32
Gattster Avatar answered Oct 02 '22 18:10

Gattster