views:

193

answers:

3

How would I write a SQLite query to select all records from a specific month? My dates are stored as Unix timestamps.

PHP code is allowed in your solution if it's required. SQLite2-compatible queries only, please. :)

+4  A: 

If you want an efficient query then you should use BETWEEN:

SELECT *
FROM Table1
WHERE date BETWEEN $start AND $end

Where start and end are the unix timestamps for the start of the month and the end of the month. These can be calculated in PHP using mktime and sent as parameters.

Mark Byers
Well, it's not working, but I'll have to blame my script here, because the query (and my time-finding code) seems to be correct.
soren121
And it was my script. Fixed the bug in MY code and it worked fine. Thanks!
soren121
+1  A: 

Use:

SELECT *
  FROM TABLE 
 WHERE DATETIME(your_unix_timestamp_col, 'unixepoch') BETWEEN YYYY-MM-DD 
                                                          AND YYYY-MM-DD

Replace the YYYY-MM-DD with the dates you desire. See the reference page for other supported formats.

Reference:

OMG Ponies
+1  A: 

Without calculating last day in month

SELECT * 
  FROM table 
 WHERE strftime('%Y-%m',date(unix_timestamp,'unixepoch','localtime')) = '2010-03'
dev-null-dweller