Tutorial: Time travel using T-SQL at statement level
In this article, learn how to time travel in your warehouse at the statement level using T-SQL. This feature allows you to query data as it appeared in the past, within a retention period.
Note
Currently, only the Coordinated Universal Time (UTC) time zone is used for time travel.
Time travel
In this example, we'll update a row, and show how to easily query the previous value using the FOR TIMESTAMP AS OF
query hint.
From the Home tab of the ribbon, select New SQL query.
In the query editor, paste the following code to create the view
Top10CustomerView
. Select Run to execute the query.CREATE VIEW dbo.Top10CustomersView AS SELECT TOP (10) FS.[CustomerKey], DC.[Customer], SUM(FS.TotalIncludingTax) AS TotalSalesAmount FROM [dbo].[dimension_customer] AS DC INNER JOIN [dbo].[fact_sale] AS FS ON DC.[CustomerKey] = FS.[CustomerKey] GROUP BY FS.[CustomerKey], DC.[Customer] ORDER BY TotalSalesAmount DESC;
In the Explorer, verify that you can see the newly created view
Top10CustomersView
by expanding the View node underdbo
schema.Create another new query, similar to Step 1. From the Home tab of the ribbon, select New SQL query.
In the query editor, paste the following code. This updates the
TotalIncludingTax
column value to200000000
for the record which has theSaleKey
value of22632918
. Select Run to execute the query./*Update the TotalIncludingTax value of the record with SaleKey value of 22632918*/ UPDATE [dbo].[fact_sale] SET TotalIncludingTax = 200000000 WHERE SaleKey = 22632918;
In the query editor, paste the following code. The
CURRENT_TIMESTAMP
T-SQL function returns the current UTC timestamp as a datetime. Select Run to execute the query.SELECT CURRENT_TIMESTAMP;
Copy the timestamp value returned to your clipboard.
Paste the following code in the query editor and replace the timestamp value with the current timestamp value obtained from the prior step. The timestamp syntax format is
YYYY-MM-DDTHH:MM:SS[.FFF]
.Remove the trailing zeroes, for example:
2024-04-24T20:59:06.097
.The following example returns the list of top ten customers by
TotalIncludingTax
, including the new value forSaleKey
22632918
. Select Run to execute the query./*View of Top10 Customers as of today after record updates*/ SELECT * FROM [WideWorldImporters].[dbo].[Top10CustomersView] OPTION (FOR TIMESTAMP AS OF '2024-04-24T20:59:06.097');
Paste the following code in the query editor and replace the timestamp value to a time prior to executing the update script to update the
TotalIncludingTax
value. This would return the list of top ten customers before theTotalIncludingTax
was updated forSaleKey
22632918. Select Run to execute the query./*View of Top10 Customers as of today before record updates*/ SELECT * FROM [WideWorldImporters].[dbo].[Top10CustomersView] OPTION (FOR TIMESTAMP AS OF '2024-04-24T20:49:06.097');
For more examples, visit How to: Query using time travel at the statement level.