LiveEn
LiveEn

Reputation: 3253

SQL query to select values for a current or specific month in a given date/time format

I have saved the date in the database (mysql) as (d-m-Y H:i:s)

How can write a sql query to select all the values that are only for the current month or a specific month ?

Upvotes: 1

Views: 24558

Answers (3)

Festim
Festim

Reputation: 201

SELECT *
FROM table
WHERE DATE_FORMAT(date_field,'%m-%Y') = '07-2012';

Upvotes: 6

Zagor23
Zagor23

Reputation: 1963

SELECT * FROM `your_table` WHERE MONTH(`your_date_column`)=6 
AND YEAR(`your_date_column`)=2012

Gets everything from June 2012.

Upvotes: 2

Sherlock
Sherlock

Reputation: 7597

Store your dates in MySQL DATE format and use the following query:

SELECT 
        * 
    FROM 
        table 
    WHERE 
        MONTH(date_field) = MONTH(CURRENT_DATE) 
    AND 
        YEAR(date_field) = YEAR(CURRENT_DATE)

Storing dates as a string/varchar is a very bad idea.

Upvotes: 3

Related Questions