SQL in 60 Seconds is a series where I share SQL tips and tricks that you can learn and start using in less than a minute.
Have you ever copied and pasted a query into SQL Server Management Studio and been annoyed that the list of column names in the SELECT statement were all on one line?
SELECT Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9,Col10,Col11,Col12,Col13,Col14,Col15,Col16,Col17,Col18,Col19,Col20,Col21,Col22,Col23,Col24,Col25,Col26,Col27,Col28,Col29,Col30 FROM dbo.MyTable
You can make the query easier to read by putting each column name onto its own line.
Simply open the Find and Replace window (CTRL + H) and type in ,(:Wh)* for the Find value and ,nt for the Replace value (in some versions of SSMS you may have better luck using ,(:Wh|t| )* in the Find field). Make sure “Use Regular Expressions” is checked and press Replace All:
To get our current inventory of rental cars, all we have to do is query the temporal table:
SELECT *FROM dbo.CarInventory
I know this query seems lame — it’s just a SELECT FROM statement. There are no FOR SYSTEM TIME clauses, WHERE statements, and no other interesting T-SQL features.
But that’s the point! Have you ever had to get the “current” rows out of a table that is keeping track of all transactions? I’m sure it involved some GROUP BY statements, some window functions, and more than a few cups of coffee.
Temporal tables automatically manage your transaction history, providing the most current records in one table (dbo.CarInventory) and all of the historical transactions in another (dbo.CarInventoryHistory). No need for complicated queries.
Business Problem #2 — “How many miles on average do our customers drive each of our cars?”
In this example, we use FOR SYSTEM_TIME ALL and a plain old GROUP BY to get the data we need:
dbo.CarInventory FORSYSTEM_TIME ALL
InLot=1--The car has been successfully returned toour lot
ANDSysStartTime>'2017-05-13 08:00:00.0000000'--Ignore our initial car purchase
FOR SYSTEM_TIME ALL returns all rows from both the temporal and history table. It’s equivalent to:
SELECT *FROM dbo.CarInventory
SELECT *FROM dbo.CarInventoryHistory
Once again, there isn’t anything too fancy going on here — but that’s the point. With temporal tables, your data is organized to make analysis easier.
Business Problem #3 — “How many cars do we rent out week over week?”
Here at Wagner Car Rentals we want to figure out how often our cars are being rented and see how those numbers change from week to week.
In this query, we are using FOR SYSTEM_TIME FOR/TO on our temporal table to specify what data we want in our “CurrentWeek” and “PreviousWeek” subqueries.
FOR/TO returns any records that were active during the specified range(BETWEEN/AND does the same thing, but its upper bound datetime2 value is inclusive instead of exclusive).
Business Problem #4 — “What color cars are rented most often?”
We’re thinking of expanding our fleet of rental vehicles and want to purchase cars in the most popular colors so we can keep customers happy (and get more of their business!). How can we tell which color cars get rented most often?
COUNT(*)/2ASRentalCount--Divide by2because transactions are doublecounted(rental andreturndates)
Here we use CONTAINED IN because we want to get precise counts of how many cars were rented and returned in a specific date range (if a car wasn’t returned — stolen, wrecked and totaled, etc… — we don’t want to purchase more of those colors in the future).
Business Problem #5 — “Jerry broke it. FIX IT!”
The computer systems that we use at Wagner Car Rentals are a little…dated.
Instead of scanning a bar code to return a car back into our system, our employees need to manually type in the car details. The problem here is that some employees (like Jerry) can’t type, and often makes typos:
SELECT *FROM dbo.CarInventory FORSYSTEM_TIME ALL WHERE CarId=4
Having inconsistent data makes our reporting much more difficult, but fortunately since we have our temporal table tracking row-level history, we can easily correct Jerry’s typos by pulling the correct values from a previous record:
SELECT ROW_NUMBER()OVER(PARTITION BY CarId ORDER BY SysStartTime DESC)ASRN,*
FROM dbo.CarInventory FORSYSTEM_TIME ALL WHERE CarId=4
--SELECT *FROM InventoryHistory
/*Update current row by using N-th row version from history (default is 1 - i.e. last version)*/
INNER JOIN InventoryHistoryh
Although we could have fixed this issue without using a temporal table, it shows how having all of the row-level transaction history makes it possible to repair incorrect data in more difficult scenarios. For even hairier situations, you can even roll-back your temporal table data.
Temporal tables are easy to setup and make writing analytical queries a cinch.
Hopefully writing queries against temporal tables will prevent you from having to stay late in the office the next time your manager asks you to run some ad-hoc analysis.