SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Temporal Tables
GREG MCMURRAY, NOVEMBER 2017
SLC SQL SERVER USERS GROUP
Traveling Through Time
• JamesWebb SpaceTelescope
• Scheduled Launch in Spring 2019
• Designed to study light from as far
back as 13.5 billion years ago
• TemporalTables in SQL Server
provide a similar look back in time
Introductions: Greg McMurray
• Worked in Aerospace, Branding & Marketing, Energy, Healthcare, Software
• Currently Senior Software Engineer atWECC
• Aritus Computer Services, L.L.C. Owner for 19 years
• Active in many local user groups
• Find me online
• @goyuix
• https://www.linkedin.com/in/goyuix
• https://stackoverflow.com/cv/goyuix - top 3% of users
Introductions: WECC
• Western Electricity Coordinating Council
• Ensure the reliability & security of the western interconnection
• Approved Regional Entity by Federal Energy Regulatory Commission
• Create, monitor & enforce reliability standards
• Publish studies, models and independent perspective
• Covers 14 western states, 2 Canadian provinces and Baja Mexico
• We are hiring! https://www.wecc.biz/careers
Agenda
• What are temporal tables
• Why &When to use them
• How to build and query
• Demos
• Limitations
• Additional Resources
• Q & A
Time Travel References
What Are Temporal Tables
• Special kind of table used to track changes over time
• Called System-Versioned because the system handles them
• Rule ofTwo: 2 tables and 2 new columns
• Two period columns of type datetime2 (SysStartTime and SysEndTime)
• History table with same column definitions
• Availability: All versions of SQL Server starting with 2016
• Additional improvements in 2017 as well
Sample DDL for Creating Temporal Table
CREATE TABLE dbo.Emp (
[EmployeeID] int NOT NULL PRIMARY KEY CLUSTERED
, [Name] nvarchar(100) NOT NULL
, [AnnualSalary] decimal (10,2) NOT NULL
, [StartTime] datetime2 (2) GENERATED ALWAYS AS ROW START
, [EndTime] datetime2 (2) GENERATED ALWAYS AS ROW END
, PERIOD FOR SYSTEM_TIME (StartTime, EndTime)
) WITH
(SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmpHistory)
)
Demo: Create a temporal table
Observations
• Table shows up with a clock icon overlay
• New in 2017 – Start and End columns can be HIDDEN
• History table doesn't show up in schema browser
• Shows up once you expand the source table
• Schema name is required for history table definition
• This also means you can store it in a different schema
• Why would you want to do that? Advantages?
• What happens if you try to drop a table that is system-versioned?
How does this work?
What happens with DML statements?
• INSERT – StartTime set to current UTC time, EndTime set to max
value (9999-12-31)
• UPDATE – Old row is added to history table and EndTime updated to
current UTC time. StartTime in current table is set to current UTC
time, EndTime remains at max value.
• DELETE – Old row is added to history table and EndTime updated to
current UTC time. Row is then removed from current table.
• MERGE – Follows INSERT / UPDATE / DELETE logic as specified
Demo: Insert, Update, Delete
Querying Temporal Data
• So far we have just created a log
• Thinking to yourself: I could have done this with triggers!
• What happens when you add a new column?
• What would a query look like that returns for a specific time?
• This is much easier with someT-SQL syntactic sugar
• And like many fabulous nuggets, it starts with the FOR predicate
• Like FOR XML, FOR JSON, …
• SELECT * FROMTable FOR SYSTEM_TIMEALL
• Internally a UNION happens between temporal / history table
FOR SYSTEM_TIME Predicates
ALL Returns all matching rows from both tables
AS OF '2017-01-01' StartTime <= '2017-01-01’ AND EndTime > '2017-01-01'
BETWEEN '2017-01-01’
AND '2017-12-31'
StartTime < '2017-12-31’ AND EndTime >= '2017-01-01'
FROM '2017-01-01’
TO '2017-12-31'
StartTime <= '2017-12-31’ AND EndTime > '2017-01-01'
CONTAINED IN
('2017-01-01', '2017-01-01')
StartTime >= '2017-01-01’ AND EndTime <= '2017-12-31'
Demo: FOR SYSTEM_TIME Options
Managing Historical Data
• 2016 had not retention period - manage it yourself
• 2017 includes HISTORY_RETENTION_PERIOD policy
• DAYS,WEEKS, MONTHS,YEARS, INFINITE – assumes infinite if not specified
• Fun Idea: Use Stretch Database
• Can stretch the whole table or just part of it
• Another option: UseTABLE PARTITIONS
• Most exciting and user error prone: Custom Cleanup Scripts
• Remember to turn off SYSTEM_VERSIONING
Limitations
• Can’t directly modify the data in the history table
• Source table must have a primary key defined
• FILETABLE & FILESTREAM are not allowed because changes could happen
outside the system and they can’t guarantee versioning
• TRUNCATE isn’t supported while versioning is ON
• CASCADE (delete or update) is not allowed
• INSTEAD OF triggers are not allowed on current or history tables
• AFTER triggers are only allowed on the current table
• Limits on REPLICATION
Resources
• TemporalTables
https://docs.microsoft.com/en-us/sql/relational-
databases/tables/temporal-tables
• Data Exposed on MSDN Channel 9
https://channel9.msdn.com/Shows/Data-Exposed/Temporal-in-SQL-
Server-2016
• BertWagner
https://medium.com/@bertwagner/
https://www.youtube.com/channel/UC6uYLOg8N_NzjkikbJ_vrtg
• Dejan Sarka
https://app.pluralsight.com/profile/author/dejan-sarka
Questions & Answers
• Keep the conversation alive after the meetup
• #SLCSQL hashtag
• Meetup.com has comments for the meeting
• I’d love to connect with you online
• Twitter: @goyuix
• LinkedIn: https://www.linkedin.com/in/goyuix

Weitere ähnliche Inhalte

Ähnlich wie SQL Server Temporal Tables

Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaaPerfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
Cuneyt Goksu
 

Ähnlich wie SQL Server Temporal Tables (20)

Temporal Tables, Transparent Archiving in DB2 for z/OS and IDAA
Temporal Tables, Transparent Archiving in DB2 for z/OS and IDAATemporal Tables, Transparent Archiving in DB2 for z/OS and IDAA
Temporal Tables, Transparent Archiving in DB2 for z/OS and IDAA
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 
BREEZE 3D Analyst for the Advanced AERMOD Modeler
BREEZE 3D Analyst for the Advanced AERMOD ModelerBREEZE 3D Analyst for the Advanced AERMOD Modeler
BREEZE 3D Analyst for the Advanced AERMOD Modeler
 
Do You Have the Time
Do You Have the TimeDo You Have the Time
Do You Have the Time
 
Time Travelling With DB2 10 For zOS
Time Travelling With DB2 10 For zOSTime Travelling With DB2 10 For zOS
Time Travelling With DB2 10 For zOS
 
Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaaPerfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
Perfect trio : temporal tables, transparent archiving in db2 for z_os and idaa
 
Walking down the memory lane with temporal tables
Walking down the memory lane with temporal tablesWalking down the memory lane with temporal tables
Walking down the memory lane with temporal tables
 
Sql 2016 - What's New
Sql 2016 - What's NewSql 2016 - What's New
Sql 2016 - What's New
 
Redefining tables online without surprises
Redefining tables online without surprisesRedefining tables online without surprises
Redefining tables online without surprises
 
Time Series Forecasting Using TBATS Model.pptx
Time Series Forecasting Using TBATS Model.pptxTime Series Forecasting Using TBATS Model.pptx
Time Series Forecasting Using TBATS Model.pptx
 
Cassandra 2012
Cassandra 2012Cassandra 2012
Cassandra 2012
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing It
 
Hello my name is DAX
Hello my name is DAXHello my name is DAX
Hello my name is DAX
 
Informix partitioning interval_rolling_window_table
Informix partitioning interval_rolling_window_tableInformix partitioning interval_rolling_window_table
Informix partitioning interval_rolling_window_table
 
A time Travel with temporal tables
A time Travel with temporal tablesA time Travel with temporal tables
A time Travel with temporal tables
 
SSG_SQLServer2016
SSG_SQLServer2016SSG_SQLServer2016
SSG_SQLServer2016
 
Best Practices for Supercharging Cloud Analytics on Amazon Redshift
Best Practices for Supercharging Cloud Analytics on Amazon RedshiftBest Practices for Supercharging Cloud Analytics on Amazon Redshift
Best Practices for Supercharging Cloud Analytics on Amazon Redshift
 
Case Study Real Time Olap Cubes
Case Study Real Time Olap CubesCase Study Real Time Olap Cubes
Case Study Real Time Olap Cubes
 
Geek Sync I Polybase and Time Travel (Temporal Tables)
Geek Sync I Polybase and Time Travel (Temporal Tables)Geek Sync I Polybase and Time Travel (Temporal Tables)
Geek Sync I Polybase and Time Travel (Temporal Tables)
 
Oracle 12c SQL: Date Ranges
Oracle 12c SQL: Date RangesOracle 12c SQL: Date Ranges
Oracle 12c SQL: Date Ranges
 

Mehr von Greg McMurray

Mehr von Greg McMurray (11)

Power Platform Introduction - Utah PowerApps and Flow User Group
Power Platform Introduction - Utah PowerApps and Flow User GroupPower Platform Introduction - Utah PowerApps and Flow User Group
Power Platform Introduction - Utah PowerApps and Flow User Group
 
SharePoint Search - August 2019 at Utah SharePoint User Group
SharePoint Search - August 2019 at Utah SharePoint User GroupSharePoint Search - August 2019 at Utah SharePoint User Group
SharePoint Search - August 2019 at Utah SharePoint User Group
 
PowerShell Basics for Office Apps and Servers
PowerShell Basics for Office Apps and ServersPowerShell Basics for Office Apps and Servers
PowerShell Basics for Office Apps and Servers
 
Introduction to SQL Server Graph DB
Introduction to SQL Server Graph DBIntroduction to SQL Server Graph DB
Introduction to SQL Server Graph DB
 
Power BI Streaming Datasets - San Diego BI Users Group
Power BI Streaming Datasets - San Diego BI Users GroupPower BI Streaming Datasets - San Diego BI Users Group
Power BI Streaming Datasets - San Diego BI Users Group
 
Dynamics 365 Web API - CRMUG April 2018
Dynamics 365 Web API - CRMUG April 2018Dynamics 365 Web API - CRMUG April 2018
Dynamics 365 Web API - CRMUG April 2018
 
Sql Server 2016 and JSON
Sql Server 2016 and JSONSql Server 2016 and JSON
Sql Server 2016 and JSON
 
Power BI Streaming Datasets
Power BI Streaming DatasetsPower BI Streaming Datasets
Power BI Streaming Datasets
 
Introduction to Microsoft Teams
Introduction to Microsoft TeamsIntroduction to Microsoft Teams
Introduction to Microsoft Teams
 
CRMUG Presentation on Dynamics CRM integration with SharePoint
CRMUG Presentation on Dynamics CRM integration with SharePointCRMUG Presentation on Dynamics CRM integration with SharePoint
CRMUG Presentation on Dynamics CRM integration with SharePoint
 
Real World Power Query for Excel and Power BI - SQL Saturday #576
Real World Power Query for Excel and Power BI - SQL Saturday #576Real World Power Query for Excel and Power BI - SQL Saturday #576
Real World Power Query for Excel and Power BI - SQL Saturday #576
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

SQL Server Temporal Tables

  • 1. Temporal Tables GREG MCMURRAY, NOVEMBER 2017 SLC SQL SERVER USERS GROUP
  • 2. Traveling Through Time • JamesWebb SpaceTelescope • Scheduled Launch in Spring 2019 • Designed to study light from as far back as 13.5 billion years ago • TemporalTables in SQL Server provide a similar look back in time
  • 3. Introductions: Greg McMurray • Worked in Aerospace, Branding & Marketing, Energy, Healthcare, Software • Currently Senior Software Engineer atWECC • Aritus Computer Services, L.L.C. Owner for 19 years • Active in many local user groups • Find me online • @goyuix • https://www.linkedin.com/in/goyuix • https://stackoverflow.com/cv/goyuix - top 3% of users
  • 4. Introductions: WECC • Western Electricity Coordinating Council • Ensure the reliability & security of the western interconnection • Approved Regional Entity by Federal Energy Regulatory Commission • Create, monitor & enforce reliability standards • Publish studies, models and independent perspective • Covers 14 western states, 2 Canadian provinces and Baja Mexico • We are hiring! https://www.wecc.biz/careers
  • 5. Agenda • What are temporal tables • Why &When to use them • How to build and query • Demos • Limitations • Additional Resources • Q & A
  • 7. What Are Temporal Tables • Special kind of table used to track changes over time • Called System-Versioned because the system handles them • Rule ofTwo: 2 tables and 2 new columns • Two period columns of type datetime2 (SysStartTime and SysEndTime) • History table with same column definitions • Availability: All versions of SQL Server starting with 2016 • Additional improvements in 2017 as well
  • 8. Sample DDL for Creating Temporal Table CREATE TABLE dbo.Emp ( [EmployeeID] int NOT NULL PRIMARY KEY CLUSTERED , [Name] nvarchar(100) NOT NULL , [AnnualSalary] decimal (10,2) NOT NULL , [StartTime] datetime2 (2) GENERATED ALWAYS AS ROW START , [EndTime] datetime2 (2) GENERATED ALWAYS AS ROW END , PERIOD FOR SYSTEM_TIME (StartTime, EndTime) ) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmpHistory) )
  • 9. Demo: Create a temporal table
  • 10. Observations • Table shows up with a clock icon overlay • New in 2017 – Start and End columns can be HIDDEN • History table doesn't show up in schema browser • Shows up once you expand the source table • Schema name is required for history table definition • This also means you can store it in a different schema • Why would you want to do that? Advantages? • What happens if you try to drop a table that is system-versioned?
  • 11. How does this work?
  • 12. What happens with DML statements? • INSERT – StartTime set to current UTC time, EndTime set to max value (9999-12-31) • UPDATE – Old row is added to history table and EndTime updated to current UTC time. StartTime in current table is set to current UTC time, EndTime remains at max value. • DELETE – Old row is added to history table and EndTime updated to current UTC time. Row is then removed from current table. • MERGE – Follows INSERT / UPDATE / DELETE logic as specified
  • 14. Querying Temporal Data • So far we have just created a log • Thinking to yourself: I could have done this with triggers! • What happens when you add a new column? • What would a query look like that returns for a specific time? • This is much easier with someT-SQL syntactic sugar • And like many fabulous nuggets, it starts with the FOR predicate • Like FOR XML, FOR JSON, … • SELECT * FROMTable FOR SYSTEM_TIMEALL • Internally a UNION happens between temporal / history table
  • 15. FOR SYSTEM_TIME Predicates ALL Returns all matching rows from both tables AS OF '2017-01-01' StartTime <= '2017-01-01’ AND EndTime > '2017-01-01' BETWEEN '2017-01-01’ AND '2017-12-31' StartTime < '2017-12-31’ AND EndTime >= '2017-01-01' FROM '2017-01-01’ TO '2017-12-31' StartTime <= '2017-12-31’ AND EndTime > '2017-01-01' CONTAINED IN ('2017-01-01', '2017-01-01') StartTime >= '2017-01-01’ AND EndTime <= '2017-12-31'
  • 17. Managing Historical Data • 2016 had not retention period - manage it yourself • 2017 includes HISTORY_RETENTION_PERIOD policy • DAYS,WEEKS, MONTHS,YEARS, INFINITE – assumes infinite if not specified • Fun Idea: Use Stretch Database • Can stretch the whole table or just part of it • Another option: UseTABLE PARTITIONS • Most exciting and user error prone: Custom Cleanup Scripts • Remember to turn off SYSTEM_VERSIONING
  • 18. Limitations • Can’t directly modify the data in the history table • Source table must have a primary key defined • FILETABLE & FILESTREAM are not allowed because changes could happen outside the system and they can’t guarantee versioning • TRUNCATE isn’t supported while versioning is ON • CASCADE (delete or update) is not allowed • INSTEAD OF triggers are not allowed on current or history tables • AFTER triggers are only allowed on the current table • Limits on REPLICATION
  • 19. Resources • TemporalTables https://docs.microsoft.com/en-us/sql/relational- databases/tables/temporal-tables • Data Exposed on MSDN Channel 9 https://channel9.msdn.com/Shows/Data-Exposed/Temporal-in-SQL- Server-2016 • BertWagner https://medium.com/@bertwagner/ https://www.youtube.com/channel/UC6uYLOg8N_NzjkikbJ_vrtg • Dejan Sarka https://app.pluralsight.com/profile/author/dejan-sarka
  • 20. Questions & Answers • Keep the conversation alive after the meetup • #SLCSQL hashtag • Meetup.com has comments for the meeting • I’d love to connect with you online • Twitter: @goyuix • LinkedIn: https://www.linkedin.com/in/goyuix