How to do Query in Postgres SQL based on time [duplicate] - sql

This question already has answers here:
How to add a variable number of hours to a date in PostgreSQL?
(5 answers)
Closed 8 years ago.
I would like to do a query in postgres which should bring count of records that updated previous one hour
For example 9AM-10AM records updated is 100 means I should get 100.
10AM-11AM records update is 200 means I should get 200(not 300).
Sample time stamp in updated column 2011-02-03 09:00:00
I have tried like this
select count(*) from customer where updated>=now()-1 and updated<now()
I know now()-1 will take yesterday. I dont know how to minus one hour from now

This should be doable using the date/time related functions and operations provided by Postgres:
where updated between
(date_trunc('hour',current_timestamp) - interval '1 hour')
and
(date_trunc('hour',current_timestamp))
Explanation:
date_trunc('hour',current_timestamp)
Gives the current time with minutes, seconds and milliseconds set to 0, and
- interval '1 hour'
subtracts one hour from a given timestamp.
Combine those to create the range you want ( between )

Related

Trying to accommodate relative defined date, such as 5 days ago, into my fixed date condition in PostgreSQL

I'm trying to condition my WHERE clause to accommodate relatively defined dates into my date filter. I'm pretty confused what type I need to use, if it's CONVERT or TO_DATE function, or if I need to put a CASE WHEN statement into my code.
This is the code that I have written so far:
WHERE event_create_verified_user_success.created_at_utc_date
BETWEEN DATE '2021-11-29' AND DATE '2021-12-05'
And this is the condition of the activity I need to finish:
If the desired date-period is not set manually using fixed dates like from “2021-11-29”
to “2021-12-05”, how would you change the where-clause to consider all data from relative
defined dates: “consider messages created between 10 days and 5 days ago (inclusive)”
I've only started PostgreSQL yesterday and the last time I've handle SQL was probably 4 years ago so I'm pretty confused at how much SQL has changed since then.
Thank you so much for helping!
The basic syntax hasn't really changed in the last 4 years (or even 15 years).
You can use current_date to obtain "today's date". You can subtract days from that
where ... between current_date - 10 and current_date - 5
If created_at_utc_date is a timestamp (= date and time) rather than a date (=date without time) it's better to use a range query though:
where created_at_utc_date >= current_date - 10
and created_at_utc_date < current_date - 4
Note the < combined with the next day you want to compare with.

Compare a datetime field within 2 hours [duplicate]

This question already has answers here:
SQL: Get records created in time range for specific dates
(3 answers)
Closed 8 years ago.
I have a table with the field ENTERED_ON (with both date and time value). I want to write a query that return records that have ENTERED_ON value that is past 2 hours comparing to current date time.
For example, if entered_on is 2014-05-06 11:00AM, and currently it's 2014-05-06 2:00PM, I would like to return all records that past the 2 hours when comparing to current date time.
You can write query using INTERVAL. It will looks like
SELECT * FROM Table WHERE `ENTERED_ON` > DATE_ADD(NOW(), INTERVAL -2 HOUR)

Working out elapsed time from two columns in ORACLE SQL [duplicate]

This question already has answers here:
Calculate difference between 2 date / times in Oracle SQL
(21 answers)
Closed 8 years ago.
I have two rows stored in a table called client_booking. These are called start_time and end_time. I need to create a text box in ORACLE APEX which generates the elapsed time through an SQL query.
Time difference being in days, let us multiply it by no of hours 24 and no of minutes 60. Assuming they are of DATE or TIMESTAMP datatypes
select (
to_date('01-01-2014 '|| end_time ||'00','DD-MM-YYYY HHMISS') -
to_date('01-01-2014 '|| start_time||'00','DD-MM-YYYY HHMISS')
) * 24 * 60 as time_elapsed_in_mins
from your_table;

Get timestamp of one month ago in PostgreSQL

I have a PostgreSQL database in which one table rapidly grows very large (several million rows every month or so) so I'd like to periodically archive the contents of that table into a separate table.
I'm intending to use a cron job to execute a .sql file nightly to archive all rows that are older than one month into the other table.
I have the query working fine, but I need to know how to dynamically create a timestamp of one month prior.
The time column is stored in the format 2013-10-27 06:53:12 and I need to know what to use in an SQL query to build a timestamp of exactly one month prior. For example, if today is October 27, 2013, I want the query to match all rows where time < 2013-09-27 00:00:00
Question was answered by a friend in IRC:
'now'::timestamp - '1 month'::interval
Having the timestamp return 00:00:00 wasn't terrible important, so this works for my intentions.
select date_trunc('day', NOW() - interval '1 month')
This query will return date one month ago from now and round time to 00:00:00.
When you need to query for the data of previous month, then you need to query for the respective date column having month values as (current_month-1).
SELECT *
FROM {table_name}
WHERE {column_name} >= date_trunc('month', current_date-interval '1' month)
AND {column_name} < date_trunc('month', current_date)
The first condition of where clause will search the date greater than the first day (00:00:00 Day 1 of Previous Month)of previous month and second clause will search for the date less than the first day of current month(00:00:00 Day 1 of Current Month).
This will includes all the results where date lying in previous month.

date_trunc 5 minute interval in PostgreSQL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the fastest way to truncate timestamps to 5 minutes in Postgres?
Postgresql SQL GROUP BY time interval with arbitrary accuracy (down to milli seconds)
I want to aggregate data at 5 minute intervals in PostgreSQL. If I use the date_trunc() function, I can aggregate data at an hourly, monthly, daily, weekly, etc. interval but not a specific interval like 5 minute or 5 days.
select date_trunc('hour', date1), count(*) from table1 group by 1;
How can we achieve this in PostgreSQL?
SELECT date_trunc('hour', date1) AS hour_stump
, (extract(minute FROM date1)::int / 5) AS min5_slot
, count(*)
FROM table1
GROUP BY 1, 2
ORDER BY 1, 2;
You could GROUP BY two columns: a timestamp truncated to the hour and a 5-minute-slot.
The example produces slots 0 - 11. Add 1 if you prefer 1 - 12.
I cast the result of extract() to integer, so the division / 5 truncates fractional digits. The result:
minute 0 - 4 -> slot 0
minute 5 - 9 -> slot 1
etc.
This query only returns values for those 5-minute slots where values are found. If you want a value for every slot or if you want a running sum over 5-minute slots, consider this related answer:
PostgreSQL: running count of rows for a query 'by minute'
Here's a simple query you can either wrap in a function or cut and paste all over the place:
select now()::timestamp(0), (extract(epoch from now()::timestamptz(0)-date_trunc('d',now()))::int)/60;
It'll give you the current time, and a number from 0 to the n-1 where n=60 here. To make it every 5 minutes, make that number 300 and so on. It groups by the seconds since the start of the day. To make it group by seconds since year begin, hour begin, or whatever else, change the 'd' in the date_trunc.