How to implement “as of” queries in PostgreSQL?

In PostgreSQL, you can implement “as of” queries using the SQL standard’s temporal query features, which allow you to query a table as it existed at a specific point in time. There are two main ways to achieve this:

  1. Using PostgreSQL’s built-in temporal features:

PostgreSQL has built-in support for temporal data types and functions, which allow you to store and query data with time-based information. You can use the AS OF clause in a query to specify a point in time to query the table as it existed at that time.

For example, let’s say you have a table called orders that contains order information with a created_at timestamp column. You can query the table as it existed at a specific point in time using the following syntax:

This will return all rows in the orders table as they existed at midnight on February 9th, 2022.

  1. Using a temporal extension:

Alternatively, you can use a PostgreSQL extension that provides additional temporal functionality, such as the pg_temporal extension. This extension provides a set of functions that allow you to query a table as it existed at a specific point in time or within a specific time range.

To use pg_temporal, you first need to install the extension using the following command:

Once the extension is installed, you can use its functions to query the table as it existed at a specific point in time, like this:

This will return all rows in the orders table that were active at any time during February 9th, 2022.

In both cases, it’s important to note that temporal queries can be resource-intensive, especially if you’re querying a large table or querying across a wide time range. To improve performance, you may want to consider creating indexes on the temporal columns you’re querying or using partitioning to split the table into smaller, more manageable pieces.

About Shiv Iyer 437 Articles
Open Source Database Systems Engineer with a deep understanding of Optimizer Internals, Performance Engineering, Scalability and Data SRE. Shiv currently is the Founder, Investor, Board Member and CEO of multiple Database Systems Infrastructure Operations companies in the Transaction Processing Computing and ColumnStores ecosystem. He is also a frequent speaker in open source software conferences globally.