SlideShare a Scribd company logo
1 of 31
Download to read offline
MariaDB Temporal Tables
Federico Razzoli
$ whoami
Hi, I’m Federico Razzoli from Vettabase Ltd
Database consultant, open source supporter,
long time MariaDB and MySQL user
● vettabase.com
● Federico-Razzoli.com
Temporal Tables Implementations
Proprietary DBMSs
● Oracle 11g (2007)
● Db2 (2012)
● SQL Server 2016
● Snowflake
In Db2, a temporal table can use system-period or application-period
Open source databases
● PostgreSQL has a temporal_tables extension
○ not available from the main cloud vendors
● CockroachDB
○ with limitations
● CruxDB (NoSQL)
● HBase stores old row versions and you can retrieve them
MariaDB
MariaDB supports both types of Temporal Tables:
● MariaDB 10.3: system_time
● MariaDB 10.4: application_time
Tables are bitemporal
Application Time
Example
CREATE OR REPLACE TABLE ticket (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL
DEFAULT 'OPEN',
summary VARCHAR(200) NOT NULL,
description TEXT NOT NULL
)
ENGINE InnoDB
;
● We want to start to track changes to bugs over time
Making the table Application-Timed
ALTER TABLE ticket
LOCK = SHARED,
ALGORITHM = COPY,
ADD COLUMN valid_from DATETIME NOT NULL,
ADD COLUMN valid_to DATETIME NOT NULL,
ADD PERIOD FOR time_period (valid_from, valid_to) ;
We can use...
● Any temporal data type that includes a date (DATE, DATETIME, TIMESTAMP)
● Any storage engine
Inserting rows
MariaDB [test]> INSERT INTO ticket (summary, description) VALUES
-> ('I cannot login', 'Why is this happening to me?');
ERROR 1364 (HY000): Field 'valid_from' doesn't have a default value
MariaDB [test]> INSERT INTO ticket (summary, description,valid_from, valid_to)
VALUES
-> ('I cannot login', 'Why is this happening to me?',
-> '1994-01-01', '2010-01-01');
Query OK, 1 row affected (0.003 sec)
A better Application-Timed table
CREATE TABLE ticket_tmp LIKE ticket;
ALTER TABLE ticket_tmp
ADD COLUMN valid_from DATETIME NOT NULL
DEFAULT NOW(),
ADD COLUMN valid_to DATETIME NOT NULL
DEFAULT '2038-01-19 03:14:07.999999' ,
ADD INDEX idx_valid_from (valid_from),
ADD INDEX idx_valid_to (valid_to),
ADD PERIOD FOR time_period(valid_from, valid_to);
A better Application-Timed table
ALTER TABLE ticket_tmp
DROP PRIMARY KEY,
ADD PRIMARY KEY (id, valid_to)
;
-- populate the table
RENAME TABLE ticket TO ticket_old, ticket_tmp TO ticket;
● You will need to do similar operations with UNIQUE indexes
● RENAME TABLE is an atomic operation
Reading rows
MariaDB [test]> SELECT id, summary, valid_from, valid_to FROM ticket;
+----+----------------+---------------------+---------------------+
| id | summary | valid_from | valid_to |
+----+----------------+---------------------+---------------------+
| 1 | I cannot login | 1994-01-01 00:00:00 | 2010-01-01 00:00:00 |
+----+----------------+---------------------+---------------------+
1 row in set (0.001 sec)
MariaDB [test]> SELECT id, summary, valid_from, valid_to FROM ticket
-> WHERE NOW() BETWEEN valid_from AND valid_to;
Empty set (0.001 sec)
Deleting rows properly
CREATE OR REPLACE PROCEDURE ticket_delete(p_id INT)
MODIFIES SQL DATA
COMMENT 'Makes a row obsolete by changing its timestamp'
BEGIN
UPDATE ticket
SET valid_to = NOW()
WHERE id = p_id AND valid_to > NOW();
END;
Deleting rows properly
MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket WHERE id = 1;
+----+---------------------+---------------------+
| id | valid_from | valid_to |
+----+---------------------+---------------------+
| 1 | 2020-08-23 14:32:22 | 2038-01-19 03:14:07 |
+----+---------------------+---------------------+
MariaDB [test]> CALL ticket_delete(1);
MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket WHERE id = 1;
+----+---------------------+---------------------+
| id | valid_from | valid_to |
+----+---------------------+---------------------+
| 1 | 2020-08-23 14:32:22 | 2020-08-23 14:32:34 |
+----+---------------------+---------------------+
Deleting/updating periods
MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket;
+----+---------------------+---------------------+
| id | valid_from | valid_to |
+----+---------------------+---------------------+
| 1 | 1994-01-01 00:00:00 | 2010-01-01 00:00:00 |
+----+---------------------+---------------------+
MariaDB [test]> DELETE FROM ticket
-> FOR PORTION OF time_period FROM '1990-01-01' TO '2000-01-01'
-> WHERE id = 1;
MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket;
+----+---------------------+---------------------+
| id | valid_from | valid_to |
+----+---------------------+---------------------+
| 2 | 2000-01-01 00:00:00 | 2010-01-01 00:00:00 |
+----+---------------------+---------------------+
System Versioning
Back to our example...
CREATE OR REPLACE TABLE ticket (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL
DEFAULT 'OPEN',
summary VARCHAR(200) NOT NULL,
description TEXT NOT NULL
)
ENGINE InnoDB
;
Making the table System-Versioned
ALTER TABLE ticket
LOCK = SHARED,
ALGORITHM = COPY,
ADD SYSTEM VERSIONING;
Making the table System-Versioned
ALTER TABLE ticket
LOCK = SHARED,
ALGORITHM = COPY,
ADD COLUMN inserted_at TIMESTAMP(6) GENERATED ALWAYS AS ROW START INVISIBLE,
ADD COLUMN deleted_at TIMESTAMP(6) GENERATED ALWAYS AS ROW END INVISIBLE,
ADD PERIOD FOR SYSTEM_TIME(inserted_at, deleted_at),
ADD SYSTEM VERSIONING;
Limitations:
● Temporal columns don’t have to be INVISIBLE, if they’re often needed
● MDEV-15968: System versioning and CONNECT engine don't work well
together: current data is not returned
● MDEV-17448: Support DATETIME(6) for ROW START, ROW END
Querying a Sysver Table
-- get current version of the rows
-- without the temporal columns (they’re INVISIBLE)
SELECT * FROM ticket;
-- get current version of the rows
-- with the temporal columns
SELECT *, inserted_at, deleted_at FROM ticket;
-- all current and old data
SELECT *, inserted_at, deleted_at
FROM ticket FOR SYSTEM_TIME ALL;
Get old versions of the rows
-- get deleted rows
SELECT *, inserted_at, deleted_at
FROM ticket FOR SYSTEM_TIME
FROM '1970-00-00' TO NOW() - 1 MICROSECOND;
SELECT *, inserted_at, deleted_at
FROM ticket FOR SYSTEM_TIME
BETWEEN '1970-00-00' AND NOW() - 1 MICROSECOND;
SELECT *, inserted_at, deleted_at
FROM ticket FOR SYSTEM_TIME ALL
WHERE deleted_at < NOW();
History of a row
SELECT id, state, inserted_at, deleted_at
FROM ticket FOR SYSTEM_TIME ALL
WHERE id = 3
ORDER BY deleted_at;
Read a row from a specific point in time
SELECT id, state
FROM ticket FOR SYSTEM_TIME AS OF TIMESTAMP'2020-08-22 08:52:36'
WHERE id = 3;
SELECT id, state
FROM ticket FOR SYSTEM_TIME ALL
WHERE id = 3 AND
'2020-08-22 08:52:36' BETWEEN inserted_at AND deleted_at;
Temporal JOINs
-- rows that were present on 07/01
-- whose state did not change after one month
SELECT t1.id, t1.inserted_at, t1.deleted_at
FROM ticket FOR SYSTEM_TIME ALL AS t1
LEFT JOIN ticket FOR SYSTEM_TIME ALL AS t2
ON
t1.id = t2.id
AND t1.state = t2.state
WHERE
'2020-07-01 00:00:00' BETWEEN t1.inserted_at AND t1.deleted_at
AND '2020-08-01 00:00:00' BETWEEN t2.inserted_at AND t2.deleted_at
AND t2.id IS NULL
ORDER BY t1.id;
Indexes
The ROW END column is automatically appended to:
● The Primary Key;
● All UNIQUE indexes.
Queries can use a whole index of its leftmost part,
so once a regular table becomes System Versioned queries performance will not
degrade.
For Application Timed tables, indexes remain unchanged.
The power of [bi]Temporal Tables
Hints about things you can do
● A table can be both system-versioned and application-timed (bitemporal)
● Stats on added/deleted rows by year, month, weekday, day, daytime…
● Stats on rows lifetime
● Get rows that never changed
● Get rows that change too often, or change at “strange” times
● Examine history of a row to find problems
● ...
Hints about things that you should do
● PK should never change, or tracking rows history will be impossible
○ If necessary, use a trigger that throws an error if OLD.id != NEW.id
● Application Time tables: no hard deletions/updates
● If you have to drop a column, move it to a new table to avoid losing the history
● If you have to add a column that is not often read/written, consider putting it
into a new table
● If you run stats or complex queries involving temporal columns, add
PERSISTENT columns and indexes on them to make queries faster
What we left out
This was a short introductory session, so we left out some features:
● ALTER TABLEs
○ They may erase or change parts of the history, so they’re disabled by default
● Partitioning
○ You can record the history in a separate partition, or multiple partitions
● Backups
○ Check the docs for problems with Sysver Tables and mysqldump
● Replication / binlog
○ Check the documentation for possible problems with Sysver Tables
○ MariaDB can be a replica of a MySQL server, and make use of Temporal Tables to
let analysts run certain analyses that they couldn’t run on MySQL
Thanks for attending!
Question time :-)

More Related Content

What's hot

Spring Bootの本当の理解ポイント #jjug
Spring Bootの本当の理解ポイント #jjugSpring Bootの本当の理解ポイント #jjug
Spring Bootの本当の理解ポイント #jjugMasatoshi Tada
 
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐Andrew Wu
 
java.lang.OutOfMemoryError #渋谷java
java.lang.OutOfMemoryError #渋谷javajava.lang.OutOfMemoryError #渋谷java
java.lang.OutOfMemoryError #渋谷javaYuji Kubota
 
Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門Motonori Shindo
 
MySQL Index勉強会外部公開用
MySQL Index勉強会外部公開用MySQL Index勉強会外部公開用
MySQL Index勉強会外部公開用CROOZ, inc.
 
SQLアンチパターン(インデックスショットガン)
SQLアンチパターン(インデックスショットガン)SQLアンチパターン(インデックスショットガン)
SQLアンチパターン(インデックスショットガン)Tomoaki Uchida
 
MongoDBが遅いときの切り分け方法
MongoDBが遅いときの切り分け方法MongoDBが遅いときの切り分け方法
MongoDBが遅いときの切り分け方法Tetsutaro Watanabe
 
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukLaravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukShohei Okada
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askCarlos Abalde
 
決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話Ryosuke Uchitate
 
基本に戻ってInnoDBの話をします
基本に戻ってInnoDBの話をします基本に戻ってInnoDBの話をします
基本に戻ってInnoDBの話をしますyoku0825
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationmysqlops
 
これからLDAPを始めるなら 「389-ds」を使ってみよう
これからLDAPを始めるなら 「389-ds」を使ってみようこれからLDAPを始めるなら 「389-ds」を使ってみよう
これからLDAPを始めるなら 「389-ds」を使ってみようNobuyuki Sasaki
 
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話Daichi Koike
 
Apache Kafka 0.11 の Exactly Once Semantics
Apache Kafka 0.11 の Exactly Once SemanticsApache Kafka 0.11 の Exactly Once Semantics
Apache Kafka 0.11 の Exactly Once SemanticsYoshiyasu SAEKI
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB
 
Your first ClickHouse data warehouse
Your first ClickHouse data warehouseYour first ClickHouse data warehouse
Your first ClickHouse data warehouseAltinity Ltd
 

What's hot (20)

Redis
RedisRedis
Redis
 
Spring Bootの本当の理解ポイント #jjug
Spring Bootの本当の理解ポイント #jjugSpring Bootの本当の理解ポイント #jjug
Spring Bootの本当の理解ポイント #jjug
 
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐
微服務資料管理的天堂路 - CQRS / Event Sourcing 的應用與實踐
 
java.lang.OutOfMemoryError #渋谷java
java.lang.OutOfMemoryError #渋谷javajava.lang.OutOfMemoryError #渋谷java
java.lang.OutOfMemoryError #渋谷java
 
Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門
 
MySQL Index勉強会外部公開用
MySQL Index勉強会外部公開用MySQL Index勉強会外部公開用
MySQL Index勉強会外部公開用
 
SQLアンチパターン(インデックスショットガン)
SQLアンチパターン(インデックスショットガン)SQLアンチパターン(インデックスショットガン)
SQLアンチパターン(インデックスショットガン)
 
Spring Boot on Kubernetes : Yahoo!ズバトク事例 #jjug_ccc
Spring Boot on Kubernetes : Yahoo!ズバトク事例 #jjug_cccSpring Boot on Kubernetes : Yahoo!ズバトク事例 #jjug_ccc
Spring Boot on Kubernetes : Yahoo!ズバトク事例 #jjug_ccc
 
MongoDBが遅いときの切り分け方法
MongoDBが遅いときの切り分け方法MongoDBが遅いときの切り分け方法
MongoDBが遅いときの切り分け方法
 
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukLaravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to ask
 
決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話
 
基本に戻ってInnoDBの話をします
基本に戻ってInnoDBの話をします基本に戻ってInnoDBの話をします
基本に戻ってInnoDBの話をします
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimization
 
これからLDAPを始めるなら 「389-ds」を使ってみよう
これからLDAPを始めるなら 「389-ds」を使ってみようこれからLDAPを始めるなら 「389-ds」を使ってみよう
これからLDAPを始めるなら 「389-ds」を使ってみよう
 
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話
OpenAPI 3.0でmicroserviceのAPI定義を試みてハマった話
 
Apache Kafka 0.11 の Exactly Once Semantics
Apache Kafka 0.11 の Exactly Once SemanticsApache Kafka 0.11 の Exactly Once Semantics
Apache Kafka 0.11 の Exactly Once Semantics
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDB
 
Your first ClickHouse data warehouse
Your first ClickHouse data warehouseYour first ClickHouse data warehouse
Your first ClickHouse data warehouse
 

Similar to MariaDB Temporal Tables: Track Data Changes Over Time

Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfFederico Razzoli
 
M|18 Querying Data at a Previous Point in Time
M|18 Querying Data at a Previous Point in TimeM|18 Querying Data at a Previous Point in Time
M|18 Querying Data at a Previous Point in TimeMariaDB plc
 
11thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp0111thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp01Karam Abuataya
 
11 Things About11g
11 Things About11g11 Things About11g
11 Things About11gfcamachob
 
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-KompatibilitätMariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-KompatibilitätMariaDB plc
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesSaiful
 
Performance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingPerformance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingSveta Smirnova
 
What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3MariaDB plc
 
Advanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and AnalysisAdvanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and AnalysisMYXPLAIN
 
Performance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingPerformance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingSveta Smirnova
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationFederico Razzoli
 
Introduction To Lamp P2
Introduction To Lamp P2Introduction To Lamp P2
Introduction To Lamp P2Amzad Hossain
 
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)Valeriy Kravchuk
 
Need for Speed: MySQL Indexing
Need for Speed: MySQL IndexingNeed for Speed: MySQL Indexing
Need for Speed: MySQL IndexingMYXPLAIN
 
How to Avoid Pitfalls in Schema Upgrade with Galera
How to Avoid Pitfalls in Schema Upgrade with GaleraHow to Avoid Pitfalls in Schema Upgrade with Galera
How to Avoid Pitfalls in Schema Upgrade with GaleraSveta Smirnova
 
How to use histograms to get better performance
How to use histograms to get better performanceHow to use histograms to get better performance
How to use histograms to get better performanceMariaDB plc
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performanceSergey Petrunya
 

Similar to MariaDB Temporal Tables: Track Data Changes Over Time (20)

Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdf
 
5 Cool Things About SQL
5 Cool Things About SQL5 Cool Things About SQL
5 Cool Things About SQL
 
M|18 Querying Data at a Previous Point in Time
M|18 Querying Data at a Previous Point in TimeM|18 Querying Data at a Previous Point in Time
M|18 Querying Data at a Previous Point in Time
 
11thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp0111thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp01
 
11 Things About11g
11 Things About11g11 Things About11g
11 Things About11g
 
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-KompatibilitätMariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 Features
 
Performance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingPerformance Schema for MySQL Troubleshooting
Performance Schema for MySQL Troubleshooting
 
What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3
 
Advanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and AnalysisAdvanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and Analysis
 
Performance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingPerformance Schema for MySQL Troubleshooting
Performance Schema for MySQL Troubleshooting
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstration
 
Introduction To Lamp P2
Introduction To Lamp P2Introduction To Lamp P2
Introduction To Lamp P2
 
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
 
Need for Speed: MySQL Indexing
Need for Speed: MySQL IndexingNeed for Speed: MySQL Indexing
Need for Speed: MySQL Indexing
 
SAV
SAVSAV
SAV
 
How to Avoid Pitfalls in Schema Upgrade with Galera
How to Avoid Pitfalls in Schema Upgrade with GaleraHow to Avoid Pitfalls in Schema Upgrade with Galera
How to Avoid Pitfalls in Schema Upgrade with Galera
 
How to use histograms to get better performance
How to use histograms to get better performanceHow to use histograms to get better performance
How to use histograms to get better performance
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performance
 

More from Federico Razzoli

Webinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBWebinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBFederico Razzoli
 
MariaDB Security Best Practices
MariaDB Security Best PracticesMariaDB Security Best Practices
MariaDB Security Best PracticesFederico Razzoli
 
A first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themFederico Razzoli
 
MariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedFederico Razzoli
 
Recent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeRecent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeFederico Razzoli
 
Automate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleAutomate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleFederico Razzoli
 
Creating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBCreating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBFederico Razzoli
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresFederico Razzoli
 
Playing with the CONNECT storage engine
Playing with the CONNECT storage enginePlaying with the CONNECT storage engine
Playing with the CONNECT storage engineFederico Razzoli
 
Database Design most common pitfalls
Database Design most common pitfallsDatabase Design most common pitfalls
Database Design most common pitfallsFederico Razzoli
 
JSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesJSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesFederico Razzoli
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2Federico Razzoli
 
MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)Federico Razzoli
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Federico Razzoli
 
MySQL Query Optimisation 101
MySQL Query Optimisation 101MySQL Query Optimisation 101
MySQL Query Optimisation 101Federico Razzoli
 
How MySQL can boost (or kill) your application
How MySQL can boost (or kill) your applicationHow MySQL can boost (or kill) your application
How MySQL can boost (or kill) your applicationFederico Razzoli
 

More from Federico Razzoli (17)

Webinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBWebinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDB
 
MariaDB Security Best Practices
MariaDB Security Best PracticesMariaDB Security Best Practices
MariaDB Security Best Practices
 
A first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
 
MariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
 
Recent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeRecent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy life
 
Automate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleAutomate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with Ansible
 
Creating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBCreating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDB
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructures
 
Playing with the CONNECT storage engine
Playing with the CONNECT storage enginePlaying with the CONNECT storage engine
Playing with the CONNECT storage engine
 
Database Design most common pitfalls
Database Design most common pitfallsDatabase Design most common pitfalls
Database Design most common pitfalls
 
MySQL and MariaDB Backups
MySQL and MariaDB BackupsMySQL and MariaDB Backups
MySQL and MariaDB Backups
 
JSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesJSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB Databases
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2
 
MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)
 
MySQL Query Optimisation 101
MySQL Query Optimisation 101MySQL Query Optimisation 101
MySQL Query Optimisation 101
 
How MySQL can boost (or kill) your application
How MySQL can boost (or kill) your applicationHow MySQL can boost (or kill) your application
How MySQL can boost (or kill) your application
 

Recently uploaded

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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 2024The Digital Insurer
 
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 WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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?Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

MariaDB Temporal Tables: Track Data Changes Over Time

  • 2. $ whoami Hi, I’m Federico Razzoli from Vettabase Ltd Database consultant, open source supporter, long time MariaDB and MySQL user ● vettabase.com ● Federico-Razzoli.com
  • 4. Proprietary DBMSs ● Oracle 11g (2007) ● Db2 (2012) ● SQL Server 2016 ● Snowflake In Db2, a temporal table can use system-period or application-period
  • 5. Open source databases ● PostgreSQL has a temporal_tables extension ○ not available from the main cloud vendors ● CockroachDB ○ with limitations ● CruxDB (NoSQL) ● HBase stores old row versions and you can retrieve them
  • 6. MariaDB MariaDB supports both types of Temporal Tables: ● MariaDB 10.3: system_time ● MariaDB 10.4: application_time Tables are bitemporal
  • 8. Example CREATE OR REPLACE TABLE ticket ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL DEFAULT 'OPEN', summary VARCHAR(200) NOT NULL, description TEXT NOT NULL ) ENGINE InnoDB ; ● We want to start to track changes to bugs over time
  • 9. Making the table Application-Timed ALTER TABLE ticket LOCK = SHARED, ALGORITHM = COPY, ADD COLUMN valid_from DATETIME NOT NULL, ADD COLUMN valid_to DATETIME NOT NULL, ADD PERIOD FOR time_period (valid_from, valid_to) ; We can use... ● Any temporal data type that includes a date (DATE, DATETIME, TIMESTAMP) ● Any storage engine
  • 10. Inserting rows MariaDB [test]> INSERT INTO ticket (summary, description) VALUES -> ('I cannot login', 'Why is this happening to me?'); ERROR 1364 (HY000): Field 'valid_from' doesn't have a default value MariaDB [test]> INSERT INTO ticket (summary, description,valid_from, valid_to) VALUES -> ('I cannot login', 'Why is this happening to me?', -> '1994-01-01', '2010-01-01'); Query OK, 1 row affected (0.003 sec)
  • 11. A better Application-Timed table CREATE TABLE ticket_tmp LIKE ticket; ALTER TABLE ticket_tmp ADD COLUMN valid_from DATETIME NOT NULL DEFAULT NOW(), ADD COLUMN valid_to DATETIME NOT NULL DEFAULT '2038-01-19 03:14:07.999999' , ADD INDEX idx_valid_from (valid_from), ADD INDEX idx_valid_to (valid_to), ADD PERIOD FOR time_period(valid_from, valid_to);
  • 12. A better Application-Timed table ALTER TABLE ticket_tmp DROP PRIMARY KEY, ADD PRIMARY KEY (id, valid_to) ; -- populate the table RENAME TABLE ticket TO ticket_old, ticket_tmp TO ticket; ● You will need to do similar operations with UNIQUE indexes ● RENAME TABLE is an atomic operation
  • 13. Reading rows MariaDB [test]> SELECT id, summary, valid_from, valid_to FROM ticket; +----+----------------+---------------------+---------------------+ | id | summary | valid_from | valid_to | +----+----------------+---------------------+---------------------+ | 1 | I cannot login | 1994-01-01 00:00:00 | 2010-01-01 00:00:00 | +----+----------------+---------------------+---------------------+ 1 row in set (0.001 sec) MariaDB [test]> SELECT id, summary, valid_from, valid_to FROM ticket -> WHERE NOW() BETWEEN valid_from AND valid_to; Empty set (0.001 sec)
  • 14. Deleting rows properly CREATE OR REPLACE PROCEDURE ticket_delete(p_id INT) MODIFIES SQL DATA COMMENT 'Makes a row obsolete by changing its timestamp' BEGIN UPDATE ticket SET valid_to = NOW() WHERE id = p_id AND valid_to > NOW(); END;
  • 15. Deleting rows properly MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket WHERE id = 1; +----+---------------------+---------------------+ | id | valid_from | valid_to | +----+---------------------+---------------------+ | 1 | 2020-08-23 14:32:22 | 2038-01-19 03:14:07 | +----+---------------------+---------------------+ MariaDB [test]> CALL ticket_delete(1); MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket WHERE id = 1; +----+---------------------+---------------------+ | id | valid_from | valid_to | +----+---------------------+---------------------+ | 1 | 2020-08-23 14:32:22 | 2020-08-23 14:32:34 | +----+---------------------+---------------------+
  • 16. Deleting/updating periods MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket; +----+---------------------+---------------------+ | id | valid_from | valid_to | +----+---------------------+---------------------+ | 1 | 1994-01-01 00:00:00 | 2010-01-01 00:00:00 | +----+---------------------+---------------------+ MariaDB [test]> DELETE FROM ticket -> FOR PORTION OF time_period FROM '1990-01-01' TO '2000-01-01' -> WHERE id = 1; MariaDB [test]> SELECT id, valid_from, valid_to FROM ticket; +----+---------------------+---------------------+ | id | valid_from | valid_to | +----+---------------------+---------------------+ | 2 | 2000-01-01 00:00:00 | 2010-01-01 00:00:00 | +----+---------------------+---------------------+
  • 18. Back to our example... CREATE OR REPLACE TABLE ticket ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL DEFAULT 'OPEN', summary VARCHAR(200) NOT NULL, description TEXT NOT NULL ) ENGINE InnoDB ;
  • 19. Making the table System-Versioned ALTER TABLE ticket LOCK = SHARED, ALGORITHM = COPY, ADD SYSTEM VERSIONING;
  • 20. Making the table System-Versioned ALTER TABLE ticket LOCK = SHARED, ALGORITHM = COPY, ADD COLUMN inserted_at TIMESTAMP(6) GENERATED ALWAYS AS ROW START INVISIBLE, ADD COLUMN deleted_at TIMESTAMP(6) GENERATED ALWAYS AS ROW END INVISIBLE, ADD PERIOD FOR SYSTEM_TIME(inserted_at, deleted_at), ADD SYSTEM VERSIONING; Limitations: ● Temporal columns don’t have to be INVISIBLE, if they’re often needed ● MDEV-15968: System versioning and CONNECT engine don't work well together: current data is not returned ● MDEV-17448: Support DATETIME(6) for ROW START, ROW END
  • 21. Querying a Sysver Table -- get current version of the rows -- without the temporal columns (they’re INVISIBLE) SELECT * FROM ticket; -- get current version of the rows -- with the temporal columns SELECT *, inserted_at, deleted_at FROM ticket; -- all current and old data SELECT *, inserted_at, deleted_at FROM ticket FOR SYSTEM_TIME ALL;
  • 22. Get old versions of the rows -- get deleted rows SELECT *, inserted_at, deleted_at FROM ticket FOR SYSTEM_TIME FROM '1970-00-00' TO NOW() - 1 MICROSECOND; SELECT *, inserted_at, deleted_at FROM ticket FOR SYSTEM_TIME BETWEEN '1970-00-00' AND NOW() - 1 MICROSECOND; SELECT *, inserted_at, deleted_at FROM ticket FOR SYSTEM_TIME ALL WHERE deleted_at < NOW();
  • 23. History of a row SELECT id, state, inserted_at, deleted_at FROM ticket FOR SYSTEM_TIME ALL WHERE id = 3 ORDER BY deleted_at;
  • 24. Read a row from a specific point in time SELECT id, state FROM ticket FOR SYSTEM_TIME AS OF TIMESTAMP'2020-08-22 08:52:36' WHERE id = 3; SELECT id, state FROM ticket FOR SYSTEM_TIME ALL WHERE id = 3 AND '2020-08-22 08:52:36' BETWEEN inserted_at AND deleted_at;
  • 25. Temporal JOINs -- rows that were present on 07/01 -- whose state did not change after one month SELECT t1.id, t1.inserted_at, t1.deleted_at FROM ticket FOR SYSTEM_TIME ALL AS t1 LEFT JOIN ticket FOR SYSTEM_TIME ALL AS t2 ON t1.id = t2.id AND t1.state = t2.state WHERE '2020-07-01 00:00:00' BETWEEN t1.inserted_at AND t1.deleted_at AND '2020-08-01 00:00:00' BETWEEN t2.inserted_at AND t2.deleted_at AND t2.id IS NULL ORDER BY t1.id;
  • 26. Indexes The ROW END column is automatically appended to: ● The Primary Key; ● All UNIQUE indexes. Queries can use a whole index of its leftmost part, so once a regular table becomes System Versioned queries performance will not degrade. For Application Timed tables, indexes remain unchanged.
  • 27. The power of [bi]Temporal Tables
  • 28. Hints about things you can do ● A table can be both system-versioned and application-timed (bitemporal) ● Stats on added/deleted rows by year, month, weekday, day, daytime… ● Stats on rows lifetime ● Get rows that never changed ● Get rows that change too often, or change at “strange” times ● Examine history of a row to find problems ● ...
  • 29. Hints about things that you should do ● PK should never change, or tracking rows history will be impossible ○ If necessary, use a trigger that throws an error if OLD.id != NEW.id ● Application Time tables: no hard deletions/updates ● If you have to drop a column, move it to a new table to avoid losing the history ● If you have to add a column that is not often read/written, consider putting it into a new table ● If you run stats or complex queries involving temporal columns, add PERSISTENT columns and indexes on them to make queries faster
  • 30. What we left out This was a short introductory session, so we left out some features: ● ALTER TABLEs ○ They may erase or change parts of the history, so they’re disabled by default ● Partitioning ○ You can record the history in a separate partition, or multiple partitions ● Backups ○ Check the docs for problems with Sysver Tables and mysqldump ● Replication / binlog ○ Check the documentation for possible problems with Sysver Tables ○ MariaDB can be a replica of a MySQL server, and make use of Temporal Tables to let analysts run certain analyses that they couldn’t run on MySQL