57

How can I select Current Month records from a table of MySql database??

Like now current month is January. I would like to get records of January Month, Where data type of my table column is timestamp.I would like to know the sql query.

Thanks

Saharsh Shah
  • 27,975
  • 8
  • 43
  • 82
Foysal Vai
  • 1,285
  • 3
  • 13
  • 18

3 Answers3

189

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
Aman Aggarwal
  • 16,184
  • 9
  • 53
  • 77
38

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());
Saharsh Shah
  • 27,975
  • 8
  • 43
  • 82
  • 5
    Bad: Will calculate the `MONTH()` for each row. Better try a range comparison on the column. – Sebastian Sep 20 '17 at 08:11
  • 2
    @Sebastian Please, provide an answer – programaths Nov 07 '17 at 10:06
  • 3
    @Sebastian why not provide an answer? – Kishy Nivas Mar 02 '18 at 16:36
  • There are two duplicates linked at the top of the page. Both provide good answers. Why should I add another one? Anyway: Adding answers to duplicate questions isn't possible. – Sebastian Mar 04 '18 at 12:10
  • 3
    select * from t.stuff where date between DATE_FORMAT(NOW(),"%Y-%m-01") and LAST_DAY(NOW()); – Martian2049 Aug 29 '18 at 17:29
  • @Sebastian I am a newbie for SQL. Will you please explain how is this a bad answer? What is meant by Will calculate the MONTH() for each row. Better try a range comparison on the column – Bhaumik Bhatt Nov 27 '19 at 12:36
  • MySQL will walk through the table and calculate MONTH(x) for each row, then check if it's today. @Martian2049's example will allow using an index or at least avoid calculation MONTH() on each row. Imagine a 1.200.000 rows table starting ten yrs. ago: Using an index and no MONTH() will reduce the amount to check to 100k instead if 1,2M. – Sebastian Dec 02 '19 at 09:40
4

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())
hichris123
  • 9,955
  • 15
  • 53
  • 68
ankur
  • 127
  • 1
  • 2
  • 9