Sometimes we need to get our past records from the PostgreSQL database. These records are usually used for crucial purposes such as for analysis, reporting, etc. This data seems to be very beneficial for the e-commerce platforms to track sales of their products and to understand their activity in the market.
In this article, we will learn how to fetch table records from the last 24 hours in Postgres.
How to Get/Fetch Table Data From the Last 24 Hours in Postgres?
We can get our data records from the last 24 hours by using the now() function and specifying the interval for which we want to retrieve the data.
Example: Getting Records From Last 24 Hours in Postgres
Let’s suppose we had the following database table named “store_sales_details”:
SELECT * FROM store_sales_details;
Now if we want to get sales of the last 24 hours, we will have to run the following query:
SELECT * from store_sales_details WHERE Time_and_date_of_order > now() - interval '24 hours';
In the above query:
- We used a PostgreSQL function “NOW()”. This function gets the current DateTime at that instance.
- Another clause used is the “INTERVAL” clause. This clause is used to select the rows where the “order_data” falls in the past 24 hours.
- The entire query will certainly retrieve all the data that has been inserted into the database over the past 24 hours. The resulting output is given below:
That’s all about fetching records from the last 24 hours in PostgreSQL.
Conclusion
To retrieve records from the last 24 hours in PostgreSQL, execute the "SELECT * " command and set a condition to subtract "24 hours" from the current DateTime. Use the Postgres’ NOW() function to get the current DateTime at that instance. The fetched records can be used to analyze the sales and gain more insights. This write-up has explained a detailed guide on getting records from the last 24 hours in Postgres.