How to Select records from SQL using time interval
Hi ๐, today I'll share SQL query that is useful to get record from past hours, days or months. I think this is useful for someone who is new to SQL. There is different way to do so on various SQL databases.
I ragularly use mysql db and I have to always search for how to use time interval in sql that's why i wrote this article.
MySQL DB:
SELECT *
FROM actors
WHERE last_update >= NOW() - INTERVAL 2 MONTH
Right now i am working on oracle DB and to get timestamp data use this query. Oracle DB:
SELECT user_id
FROM admin_user
WHERE created_date >= SYSDATE - 1
PostgreSQL DB:
SELECT time_interval
FROM database_table
WHERE updated_time >= NOW() - '3 day'::INTERVAL
SQLite DB:
SELECT *
FROM usertable
WHERE login_date >= datetime('now','-1 day')
MySQL :
// Use any time interval you like to get data ex: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
SELECT new_users
FROM new_signup
WHERE created_time > DATE_SUB(NOW(), INTERVAL 12 HOUR)
SELECT *
FROM sample_table
WHERE timestamps > DATE_SUB(NOW(), INTERVAL 45 MINUTE)