Sql query to select from 1 hour ago? - sql

I have this query but I want to change the date to delete everything that is from more than 1 hour ago based on the server time (or if not possible by server time by post date). How do I do that?
DELETE FROM wp_posts
WHERE post_date < '2008-06-06 19:18:00'
AND post_status = 'publish'

Use:
DELETE FROM wp_posts
WHERE post_date < DATE_SUB(NOW(), INTERVAL '1' HOUR)
AND post_status = 'publish'
Reference:
DATE_ADD
DATE_SUB

Or even simpler:
SELECT NOW() - INTERVAL 1 HOUR;
So the query becomes:
DELETE FROM wp_posts
WHERE post_date < NOW() - INTERVAL 1 HOUR
AND post_status = 'publish'

Subdate function works too!
SELECT subdate(current_timestamp, interval 1 hour)

DELETE from table where date_add < NOW() - INTERVAL 1 HOUR;
to see the time run this sql :
select NOW() - INTERVAL 1 HOUR as s1 , NOW() as s2;

Related

Get daily count of rows for a Time

My database table looks like this:
CREATE TABLE record
(
id INT,
status INT,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
And I want to create a generic query to get count of record created after 3 hours of interval in last day
For example, I want to know in last 1 day after 3 hours how many records are created.
What I have so far: with a little help from stackoverflow I am able to create a query to calculate the count for a single full day.
SELECT
DATE(created_at) AS day, COUNT(1)
FROM
record
WHERE
created_at >= current_date - 1
GROUP BY
DATE(created_at)
This is telling me in full day like 24 records are created but I want to get how many are made in interval of 3 hours
If you want the count for the last three hours of data:
select count(*)
from record
where created_at >= now() - interval '3 hour';
If you want the last day minus 3 hours, that would be 21 hours:
select count(*)
from record
where created_at >= now() - interval '21 hour';
EDIT:
You want intervals of 3 hours for the last 24 hours. The simplest method is probably generate_series():
select gs.ts, count(r.created_at)
from generate_series(now() - interval '24 hour', now() - interval '3 hour', interval '3 hour') gs(ts) left join
record r
on r.created_at >= gs.ts and
r.created_at < gs.ts + interval '3 hour'
group by gs.ts
order by gs.ts;

Getting data that is more then or equal to in Postgres SQL query

I'm trying to write a query that uses postgres. My query needs to find the diffrence between the started_at time and now() and then only
select the data where the difference is >= 300 seconds.
Here is what I have so far
SELECT id, (extract(epoch from now()) - extract(epoch from started_at)) completed_time
FROM run_item WHERE started_at IS NOT NULL AND completed_at is NULL;
Have you tried placing this expression the where clause?
SELECT * FROM run_item WHERE
(EXTRACT(EPOCH FROM now()) - EXTRACT(EPOCH FROM started_at)) >= 300;
find the diffrence between the started_at time and now() and then only select the data where the difference is >= 300 seconds
You could do date arithmetics as follows:
select id, started_at - now() diff
from run_item r
where started_at <= now() - interval '5' minutes
In the resultset, diff is a column of interval datatype.

Picking order details from database in an interval

I want to pull orders that have been placed in between (last 5 mins - last 10 mins). For that I am running a query:
$query="SELECT * FROM orders where `orderStatus`='PARTIAL' and `timeCreated` >= date_sub(now(),interval 10 minute)";
However, this query is picking data from between (last 0 mins - last 10 mins).
Can you please help what should I try?
Just add another filtering condition:
SELECT *
FROM orders
WHERE
orderStatus = 'PARTIAL'
AND timeCreated >= date_sub(now(), interval 10 minute)
AND timeCreated < date_sub(now(), interval 5 minute);
Assuming that you are using MySQL (the syntax of your existing query suggests it), you can also phrase the query using the following date arithmetics, which I find more straight-forward:
SELECT *
FROM orders
WHERE
orderStatus = 'PARTIAL'
AND timeCreated >= now() - interval 10 minute
AND timeCreated < now() - interval 5 minute

SQL: Select average value of column for last hour and last day

I have a table like below image. What I need is to get average value of Volume column, grouped by User both for 1 hour and 24 hours ago. How can I use avg with two different date range in single query?
You can do it like:
SELECT user, AVG(Volume)
FROM mytable
WHERE created >= NOW() - interval '1 hour'
AND created <= NOW()
GROUP BY user
Few things to remember, you are executing the query on same server with same time zone. You need to group by the user to group all the values in volume column and then apply the aggregation function like avg to find average. Similarly if you need both together then you could do the following:
SELECT u1.user, u1.average, u2.average
FROM
(SELECT user, AVG(Volume) as average
FROM mytable
WHERE created >= NOW() - interval '1 hour'
AND created <= NOW()
GROUP BY user) AS u1
INNER JOIN
(SELECT user, AVG(Volume) as average
FROM mytable
WHERE created >= NOW() - interval '1 day'
AND created <= NOW()
GROUP BY user) AS u2
ON u1.user = u2.user
Use conditional aggregation. Postgres offers very convenient syntax using the FILTER clause:
SELECT user,
AVG(Volume) FILTER (WHERE created >= NOW() - interval '1 hour' AND created <= NOW()) as avg_1hour,
AVG(Volume) FILTER (WHERE created >= NOW() - interval '1 day' AND created <= NOW()) as avg_1day
FROM mytable
WHERE created >= NOW() - interval '1 DAY' AND
created <= NOW()
GROUP BY user;
This will filter out users who have had no activity in the past day. If you want all users -- even those with no recent activity -- remove the WHERE clause.
The more traditional method uses CASE:
SELECT user,
AVG(CASE WHEN created >= NOW() - interval '1 hour' AND created <= NOW() THEN Volume END) as avg_1hour,
AVG(CASE WHEN created >= NOW() - interval '1 day' AND created <= NOW() THEN Volume END) as avg_1day
. . .
SELECT User, AVG(Volume) , ( IIF(created < DATE_SUB(NOW(), INTERVAL 1 HOUR) , 1 , 0) )IntervalType
WHERE created < DATE_SUB(NOW(), INTERVAL 1 HOUR)
AND created < DATE_SUB(NOW(), INTERVAL 24 HOUR)
GROUP BY User, (IIF(created < DATE_SUB(NOW(), INTERVAL 1 HOUR))
Please Tell me about it's result :)

How to select records from last 24 hours using SQL?

I am looking for a where clause that can be used to retrieve records for the last 24 hours?
In MySQL:
SELECT *
FROM mytable
WHERE record_date >= NOW() - INTERVAL 1 DAY
In SQL Server:
SELECT *
FROM mytable
WHERE record_date >= DATEADD(day, -1, GETDATE())
In Oracle:
SELECT *
FROM mytable
WHERE record_date >= SYSDATE - 1
In PostgreSQL:
SELECT *
FROM mytable
WHERE record_date >= NOW() - '1 day'::INTERVAL
In Redshift:
SELECT *
FROM mytable
WHERE record_date >= GETDATE() - '1 day'::INTERVAL
In SQLite:
SELECT *
FROM mytable
WHERE record_date >= datetime('now','-1 day')
In MS Access:
SELECT *
FROM mytable
WHERE record_date >= (Now - 1)
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
MySQL :
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
The INTERVAL can be in YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
For example, In the last 10 minutes
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
Which SQL was not specified, SQL 2005 / 2008
SELECT yourfields from yourTable WHERE yourfieldWithDate > dateadd(dd,-1,getdate())
If you are on the 2008 increased accuracy date types, then use the new sysdatetime() function instead, equally if using UTC times internally swap to the UTC calls.
in postgres, assuming your field type is a timestamp:
select * from table where date_field > (now() - interval '24 hour');
If the timestamp considered is a UNIX timestamp
You need to first convert UNIX timestamp (e.g 1462567865) to mysql timestamp or data
SELECT * FROM `orders` WHERE FROM_UNIXTIME(order_ts) > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
select ...
from ...
where YourDateColumn >= getdate()-1
SELECT *
FROM tableName
WHERE datecolumn >= dateadd(hour,-24,getdate())
Hello i now it past a lot of time from the original post but i got a similar problem and i want to share.
I got a datetime field with this format YYYY-MM-DD hh:mm:ss, and i want to access a whole day, so here is my solution.
The function DATE(), in MySQL: Extract the date part of a date or datetime expression.
SELECT * FROM `your_table` WHERE DATE(`your_datatime_field`)='2017-10-09'
with this i get all the row register in this day.
I hope its help anyone.
In SQL Server (For last 24 hours):
SELECT *
FROM mytable
WHERE order_date > DateAdd(DAY, -1, GETDATE()) and order_date<=GETDATE()
In Oracle (For last 24 hours):
SELECT *
FROM my_table
WHERE date_column >= SYSDATE - 24/24
In case, for any reason, you have rows with future dates, you can use between, like this:
SELECT *
FROM my_table
WHERE date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE