Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select current months records mysql from timestamp column

I have a mysql DB that has a TIMESTAMP field titled date. How can I select all fields where the month is the current month?

Thanks in advance!

like image 852
rodzilla Avatar asked May 11 '13 18:05

rodzilla


People also ask

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.

How do I select a specific record of a particular month in SQL?

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

What is MySQL month function?

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. Syntax : MONTH(date)

How do I select a specific record in MySQL?

MySQL SELECT specific rows When a user wants to retrieve some individual rows from a table, a WHERE clause has to be added with the SELECT statement immediately followed by a condition. Here * indicates all columns.


2 Answers

UPDATE

A much better index-friendly way to query your data for a range of dates

SELECT id, FROM_UNIXTIME(timestampfield) timestamp 
  FROM table1
 WHERE timestampfield >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
   AND timestampfield <  UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY);

Note: You don't apply any function to your column data, but rather do all necessary calculations on the right side of the conditions (which are constants and are evaluated only once post-execution). This way you allow MySQL to benefit from index(es) that you might have on the timestampfield column.

Original answer:

SELECT id, FROM_UNIXTIME(timestampfield) timestamp 
  FROM table1
 WHERE MONTH(FROM_UNIXTIME(timestampfield)) = MONTH(CURDATE())
   AND YEAR(FROM_UNIXTIME(timestampfield)) = YEAR(CURDATE())

Note: Although this query produces the correct results it effectively invalidates the proper usage of the index(es) that you might have on the timestampfield column (meaning MySQL will be forced to perform a fullscan)

Here is SQLFiddle demo

like image 148
peterm Avatar answered Sep 22 '22 13:09

peterm


Use this query may this help you,

Query = "SELECT * FROM <table_name> WHERE MONTH(date_entered) = MONTH(CURDATE())";
like image 39
Bhaveshkumar Patel Avatar answered Sep 21 '22 13:09

Bhaveshkumar Patel