SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
MariaDB Temporal Tables
Federico Razzoli
€ whoami
● Federico Razzoli
● Freelance consultant
● Writing SQL since MySQL 2.23
● info@federico-razzoli.com
● I love open source, sharing,
Collaboration, win-win, etc
● I love MariaDB, MySQL, Postgres, etc
○ Even Db2, somehow
Methods for
Versioning Data
Data versioning… why?
Several reasons:
● Auditing
● Travel back in time
○ Which / how many products were we selling in Dec 2016?
● Track a row’s history
○ History of the relationship with a customer
● Compare today’s situation with 6 month ago
○ How many EU employees did we lose because of Brexit?
● Statistics on data changes
○ Sales trends
● Find correlations
○ Sales decrease because we invest less in web marketing
Example
SELECT * FROM users WHERE id = 24 G
*************************** 1. row
id: 24
first_name: Jody
last_name: Whittaker
email: first_lady@doctorwho.co.uk
gender: F
birth_date: NULL
1 row in set (0.00 sec)
Method 1: track row versions
SELECT * FROM user_changes G
*************************** 1. row
id: 1
first_name: Jody
last_name: Whittaker
email: first_lady@doctorwho.co.uk
gender: F
valid_from: 2018-10-07
valid_to: NULL
1 row in set (0.00 sec)
Method 1: track row versions
What we can do (easily):
● Undo a column change
● Undo an UPDATE/DELETE
● Get the full state of a row at a given time
● See how often a row changes
Harder to do:
● Audit changes
● See how often a value changed over time
Method 2: track field changes
SELECT * FROM user_changes G
*************************** 1. row
id: 1
user_id: 24
field: email
old_value: jody@gmail.com
new_value: first_lady@doctorwho.co.uk
valid_from: 2018-10-07
valid_to: NULL
1 row in set (0.00 sec)
Method 2: track field changes
What we can do (easily):
● Undo a column change
● Audit changes
● See how a certain value changed over time
Harder to do:
● Undo an UPDATE/DELETE
● Get/restore an old row version
● See how often a row changes over time
System-Versioned Tables
They automagically implement the Keep Row Changes method
● You INSERT, DELETE, UPDATE and SELECT data, getting the same
results you would get with a regular table
● Old versions of the rows are stored in the same (logical) table
● To get old data, you need to use a special syntaxes, like:
SELECT … AS OF TIMESTAMP '2018/01/01 16:30:00';
System-Versioned Tables
Implementations
Where are sysver tables implemented?
In the proprietary DBMS world:
● Oracle 11g (2007)
● Db2 (2012)
● SQL Server 2016
Sometimes they are called Temporal Tables
In Db2, a temporal table can use system-period or application-period
Where are sysver tables implemented?
In the open source world:
● PostgreSQL, as an extension
● CockroachDB
● MariaDB 10.3
PostgreSQL and CockroachDB implementations have important
limitations
Where are sysver tables implemented?
In the NoSQL world:
● In HBase, rows have a version property
System-Versioned Tables
In MariaDB
Overview
● Implemented in MariaDB 10.3 (stable since Apr 2017)
● You must have row-start and row-end Generated Columns
○ Type: TIMESTAMP(6) or DATETIME(6)
○ You decide the names
○ These are Invisible Columns (10.3 feature)
● Any storage engine
○ Except CONNECT (MDEV-15968)
ALTER TABLE
● Forbidden by default
○ Changes that only affect metadata also forbidden
○ system_versioning_alter_history='KEEP’
● ADD COLUMN adds a column that is set to the current DEFAULT value
or NULL for all old version rows
○ When was the column added?
● DROP COLUMN also affects old versions of the rows
○ The column’s history is lost
● CHANGE COLUMN also affects old versions of the rows
○ The column’s history is modified
Example
CREATE OR REPLACE TABLE employee (
...
valid_from TIMESTAMP(6)
GENERATED ALWAYS AS ROW START
COMMENT ‘When the row was INSERTed',
valid_to TIMESTAMP(6)
GENERATED ALWAYS AS ROW END
COMMENT 'When row was DELETEd or UPDATEd',
PERIOD FOR SYSTEM_TIME (valid_from, valid_to)
)
WITH SYSTEM VERSIONING,
ENGINE InnoDB;
Adding versioning to an existing table
ALTER TABLE employee
LOCK = SHARED,
ALGORITHM = COPY,
ADD COLUMN valid_from TIMESTAMP(6) GENERATED ALWAYS AS ROW START,
ADD COLUMN valid_to TIMESTAMP(6) GENERATED ALWAYS AS ROW END,
ADD PERIOD FOR SYSTEM_TIME(valid_from, valid_to),
ADD SYSTEM VERSIONING
;
● Notice ALGORITHM=COPY and LOCK=SHARED
Querying historical data: point in time
SELECT * FROM my_table FOR SYSTEM_TIME
● AS OF TIMESTAMP'2018-10-01 12:00:00'
● FROM '2018-10-01 00:00:00' TO '2018-11-01 00:00:00'
● BETWEEN (NOW() - INTERVAL 1 YEAR) AND NOW() ALL
SELECT * FROM my_table FOR SYSTEM_TIME ALL
WHERE valid_from < @end AND valid_to > @start;
Querying historical data: point in time
SELECT * FROM my_table FOR SYSTEM_TIME
● AS OF TIMESTAMP'2018-10-01 12:00:00'
● AS OF (SELECT valid_from FROM employee WHERE id=50)
● AS OF @some_event_timestamp
Querying historical data: time range
SELECT * FROM my_table FOR SYSTEM_TIME
● FROM '2018-10-01 00:00:00' TO '2018-11-01 00:00:00'
● FROM (SELECT ...) TO (SELECT ...)
● FROM @some_event TO @another_event
Querying historical data: time range
SELECT * FROM my_table FOR SYSTEM_TIME
● BETWEEN '2018-10-01 00:00:00' AND '2018-11-01 00:00:00'
● BETWEEN (NOW() - INTERVAL 1 YEAR) AND NOW()
● BETWEEN @some_event AND (SELECT ...)
Querying historical data: example
INSERT INTO customer (id, first_name, last_name, email) VALUES
(1, 'William', 'Hartnell', 'the_first@gmail.com'),
(2, 'Tom', 'Baker', 'tom.baker@gmail.com');
SET @beginning_of_time := NOW(6);
DELETE FROM customer WHERE id = 1;
UPDATE customer SET email = 'tom.baker@hotmail.com' WHERE id=2;
INSERT INTO customer (id, first_name, last_name, email) VALUES
(3, 'Peter', 'Capaldi', 'capaldi.petey@gmail.com');
SET @twelve_regeneration := NOW(6);
INSERT INTO customer (id, first_name, last_name, email) VALUES
(4, 'Jody', 'Wittaker', 'jody@gmail.com');
Querying historical data: example
SELECT id, first_name, last_name, valid_from, valid_to
FROM customer
FOR SYSTEM_TIME
BETWEEN @beginning_of_time AND @twelve_regeneration;
+----+------------+-----------+----------------------------+----------------------------+
| id | first_name | last_name | valid_from | valid_to |
+----+------------+-----------+----------------------------+----------------------------+
| 1 | William | Hartnell | 2018-11-04 13:50:33.627753 | 2018-11-04 13:50:33.633414 |
| 2 | Tom | Baker | 2018-11-04 13:50:33.627753 | 2018-11-04 13:50:33.638419 |
| 2 | Tom | Baker | 2018-11-04 13:50:33.638419 | 2038-01-19 03:14:07.999999 |
| 3 | Peter | Capaldi | 2018-11-04 13:50:33.644880 | 2038-01-19 03:14:07.999999 |
+----+------------+-----------+----------------------------+----------------------------+
Partitions
● By default, the history is stored together with current data
● You can put the history on separate partitions
● And limit them:
○ By rows number
○ By time
Indexes
● The ROW END column is appended to UNIQUE indexes and the PK
● Other indexes are untouched
○ You may consider adding ROW END to some of your indexes
○ This is a good reason to define temporal columns explicitly
Practical
Use Cases
Basic Examples
● First examples take advantage of temporal columns to identify INSERTs,
DELETEs and UPDATEs
Get DELETEd rows
● Get canceled orders:
SET @eot := '2038-01-19 03:14:07.999999';
SELECT * FROM `order` FOR SYSTEM_TIME ALL
WHERE valid_to < @eot;
● Get orders canceled today:
SELECT COUNT(*)
FROM `order` FOR SYSTEM_TIME
WHERE valid_to = @
AND valid_from
DATE(NOW()) AND (DATE(NOW()) + INTERVAL 1 DAY);
Get INSERTed rows
● Get orders generated today:
SELECT id, MIN(valid_from) AS insert_time
FROM `order` FOR SYSTEM_TIME ALL
GROUP BY id
HAVING DATE(MIN(valid_from)) = DATE(NOW())
ORDER BY MIN(valid_from);
Get UPDATEd rows
● How many times orders were modified:
SELECT
-- exclude the INSERTions
id, (COUNT(*) – 1) AS how_many_edits
FROM `order` FOR SYSTEM_TIME ALL
-- exclude DELETions
WHERE valid_to < @eot
GROUP BY id
ORDER BY how_many_edits;
Debug mistakes in a single row
● Wrong data has been found in a row. The original version of the row was
correct, so we want to know when the mistake (or malicious change)
happened
Debug mistakes in a single row
● Find all versions of a row:
SELECT id, status, valid_from, valid_to
FROM `order` FOR SYSTEM_TIME ALL
WHERE id = 24;
Debug mistakes in a single row
● When an order was blocked:
SELECT DATE(MIN(valid_from)) AS block_date
FROM `order` FOR SYSTEM_TIME ALL
WHERE status = 'BLOCKED'
AND id = 24;
Debug mistakes in a single row
● Status is wrong. To find out how the problem happened, we want to check the
INSERT and all following status changes:
SELECT id, status, valid_from, valid_to
FROM (
SELECT
NOT (status <=> @prev_status) AS status_changed,
@prev_status := status,
id, status, valid_from, valid_to
FROM `order` FOR SYSTEM_TIME ALL
WHERE id = 24
) t
WHERE status_changed = 1;
Debug mistakes in a single row
● We want to know if the status is the same as one month ago:
SELECT
present.id,
present.status AS current_status,
past.status AS past_status
FROM `order` present
INNER JOIN `order`
FOR SYSTEM_TIME AS OF TIMESTAMP
NOW() - INTERVAL 1 MONTH
AS past
ON present.id = past.id
ORDER BY present.id;
Stats on data changes
SELECT
AVG(amount), STDDEV(amount),
MAX(amount), MIN(amount),
COUNT(amount)
FROM account FOR SYSTEM_TIME ALL
WHERE customer_id = 24
AND valid_from BETWEEN '2016-00-00' AND NOW()
GROUP BY customer_id;
Questions?

Mais conteúdo relacionado

Mais procurados

Performance Tuning of .NET Application
Performance Tuning of .NET ApplicationPerformance Tuning of .NET Application
Performance Tuning of .NET ApplicationMainul Islam, CSM®
 
NoSQL Data Modeling 101
NoSQL Data Modeling 101NoSQL Data Modeling 101
NoSQL Data Modeling 101ScyllaDB
 
Hardware Assisted Latency Investigations
Hardware Assisted Latency InvestigationsHardware Assisted Latency Investigations
Hardware Assisted Latency InvestigationsScyllaDB
 
Change Data Feed in Delta
Change Data Feed in DeltaChange Data Feed in Delta
Change Data Feed in DeltaDatabricks
 
Batch and Stream Graph Processing with Apache Flink
Batch and Stream Graph Processing with Apache FlinkBatch and Stream Graph Processing with Apache Flink
Batch and Stream Graph Processing with Apache FlinkVasia Kalavri
 
Oracle High Availabiltity for application developers
Oracle High Availabiltity for application developersOracle High Availabiltity for application developers
Oracle High Availabiltity for application developersAlexander Tokarev
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent EventTencent
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Optimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversOptimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversScyllaDB
 
Anti-Debugging - A Developers View
Anti-Debugging - A Developers ViewAnti-Debugging - A Developers View
Anti-Debugging - A Developers ViewTyler Shields
 
Running Scylla on Kubernetes with Scylla Operator
Running Scylla on Kubernetes with Scylla OperatorRunning Scylla on Kubernetes with Scylla Operator
Running Scylla on Kubernetes with Scylla OperatorScyllaDB
 
Postgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to KnowPostgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to KnowEDB
 
Prometheus and Thanos
Prometheus and ThanosPrometheus and Thanos
Prometheus and ThanosCloudOps2005
 
Scylla Summit 2022: Scylla 5.0 New Features, Part 1
Scylla Summit 2022: Scylla 5.0 New Features, Part 1Scylla Summit 2022: Scylla 5.0 New Features, Part 1
Scylla Summit 2022: Scylla 5.0 New Features, Part 1ScyllaDB
 
Scylla Summit 2022: Making Schema Changes Safe with Raft
Scylla Summit 2022: Making Schema Changes Safe with RaftScylla Summit 2022: Making Schema Changes Safe with Raft
Scylla Summit 2022: Making Schema Changes Safe with RaftScyllaDB
 
Timeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaTimeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaOCoderFest
 
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...confluent
 
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdf
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdfDeep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdf
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdfMiguel Araújo
 

Mais procurados (20)

Performance Tuning of .NET Application
Performance Tuning of .NET ApplicationPerformance Tuning of .NET Application
Performance Tuning of .NET Application
 
NoSQL Data Modeling 101
NoSQL Data Modeling 101NoSQL Data Modeling 101
NoSQL Data Modeling 101
 
Hardware Assisted Latency Investigations
Hardware Assisted Latency InvestigationsHardware Assisted Latency Investigations
Hardware Assisted Latency Investigations
 
Multi Stage Docker Build
Multi Stage Docker Build Multi Stage Docker Build
Multi Stage Docker Build
 
Change Data Feed in Delta
Change Data Feed in DeltaChange Data Feed in Delta
Change Data Feed in Delta
 
Batch and Stream Graph Processing with Apache Flink
Batch and Stream Graph Processing with Apache FlinkBatch and Stream Graph Processing with Apache Flink
Batch and Stream Graph Processing with Apache Flink
 
Oracle High Availabiltity for application developers
Oracle High Availabiltity for application developersOracle High Availabiltity for application developers
Oracle High Availabiltity for application developers
 
Apache flink
Apache flinkApache flink
Apache flink
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Optimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversOptimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database Drivers
 
Anti-Debugging - A Developers View
Anti-Debugging - A Developers ViewAnti-Debugging - A Developers View
Anti-Debugging - A Developers View
 
Running Scylla on Kubernetes with Scylla Operator
Running Scylla on Kubernetes with Scylla OperatorRunning Scylla on Kubernetes with Scylla Operator
Running Scylla on Kubernetes with Scylla Operator
 
Postgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to KnowPostgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to Know
 
Prometheus and Thanos
Prometheus and ThanosPrometheus and Thanos
Prometheus and Thanos
 
Scylla Summit 2022: Scylla 5.0 New Features, Part 1
Scylla Summit 2022: Scylla 5.0 New Features, Part 1Scylla Summit 2022: Scylla 5.0 New Features, Part 1
Scylla Summit 2022: Scylla 5.0 New Features, Part 1
 
Scylla Summit 2022: Making Schema Changes Safe with Raft
Scylla Summit 2022: Making Schema Changes Safe with RaftScylla Summit 2022: Making Schema Changes Safe with Raft
Scylla Summit 2022: Making Schema Changes Safe with Raft
 
Timeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaTimeseries - data visualization in Grafana
Timeseries - data visualization in Grafana
 
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...
Performance Tuning RocksDB for Kafka Streams' State Stores (Dhruba Borthakur,...
 
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdf
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdfDeep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdf
Deep Dive into MySQL InnoDB Cluster Read Scale-out Capabilities.pdf
 

Semelhante a MariaDB Temporal Tables

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
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationFederico Razzoli
 
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
 
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
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesSaiful
 
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried Färber
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried FärberTrivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried Färber
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried FärberTrivadis
 
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Valerii Kravchuk
 
How Database Convergence Impacts the Coming Decades of Data Management
How Database Convergence Impacts the Coming Decades of Data ManagementHow Database Convergence Impacts the Coming Decades of Data Management
How Database Convergence Impacts the Coming Decades of Data ManagementSingleStore
 
Back to the future - Temporal Table in SQL Server 2016
Back to the future - Temporal Table in SQL Server 2016Back to the future - Temporal Table in SQL Server 2016
Back to the future - Temporal Table in SQL Server 2016Stéphane Fréchette
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)Dave Stokes
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
sql_server_2016_history_tables
sql_server_2016_history_tablessql_server_2016_history_tables
sql_server_2016_history_tablesarthurjosemberg
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performanceSergey Petrunya
 
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
 

Semelhante a MariaDB Temporal Tables (20)

MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 
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
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstration
 
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
 
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
 
Do You Have the Time
Do You Have the TimeDo You Have the Time
Do You Have the Time
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 Features
 
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried Färber
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried FärberTrivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried Färber
Trivadis TechEvent 2017 SQL Server 2016 Temporal Tables by Willfried Färber
 
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
 
Sql analytic queries tips
Sql analytic queries tipsSql analytic queries tips
Sql analytic queries tips
 
How Database Convergence Impacts the Coming Decades of Data Management
How Database Convergence Impacts the Coming Decades of Data ManagementHow Database Convergence Impacts the Coming Decades of Data Management
How Database Convergence Impacts the Coming Decades of Data Management
 
Back to the future - Temporal Table in SQL Server 2016
Back to the future - Temporal Table in SQL Server 2016Back to the future - Temporal Table in SQL Server 2016
Back to the future - Temporal Table in SQL Server 2016
 
Overview of Oracle database12c for developers
Overview of Oracle database12c for developersOverview of Oracle database12c for developers
Overview of Oracle database12c for developers
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
sql_server_2016_history_tables
sql_server_2016_history_tablessql_server_2016_history_tables
sql_server_2016_history_tables
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performance
 
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
 

Mais de 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
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsFederico 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
 

Mais de Federico Razzoli (18)

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
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAs
 
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
 

Último

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 

Último (20)

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 

MariaDB Temporal Tables

  • 2. € whoami ● Federico Razzoli ● Freelance consultant ● Writing SQL since MySQL 2.23 ● info@federico-razzoli.com ● I love open source, sharing, Collaboration, win-win, etc ● I love MariaDB, MySQL, Postgres, etc ○ Even Db2, somehow
  • 4. Data versioning… why? Several reasons: ● Auditing ● Travel back in time ○ Which / how many products were we selling in Dec 2016? ● Track a row’s history ○ History of the relationship with a customer ● Compare today’s situation with 6 month ago ○ How many EU employees did we lose because of Brexit? ● Statistics on data changes ○ Sales trends ● Find correlations ○ Sales decrease because we invest less in web marketing
  • 5. Example SELECT * FROM users WHERE id = 24 G *************************** 1. row id: 24 first_name: Jody last_name: Whittaker email: first_lady@doctorwho.co.uk gender: F birth_date: NULL 1 row in set (0.00 sec)
  • 6. Method 1: track row versions SELECT * FROM user_changes G *************************** 1. row id: 1 first_name: Jody last_name: Whittaker email: first_lady@doctorwho.co.uk gender: F valid_from: 2018-10-07 valid_to: NULL 1 row in set (0.00 sec)
  • 7. Method 1: track row versions What we can do (easily): ● Undo a column change ● Undo an UPDATE/DELETE ● Get the full state of a row at a given time ● See how often a row changes Harder to do: ● Audit changes ● See how often a value changed over time
  • 8. Method 2: track field changes SELECT * FROM user_changes G *************************** 1. row id: 1 user_id: 24 field: email old_value: jody@gmail.com new_value: first_lady@doctorwho.co.uk valid_from: 2018-10-07 valid_to: NULL 1 row in set (0.00 sec)
  • 9. Method 2: track field changes What we can do (easily): ● Undo a column change ● Audit changes ● See how a certain value changed over time Harder to do: ● Undo an UPDATE/DELETE ● Get/restore an old row version ● See how often a row changes over time
  • 10. System-Versioned Tables They automagically implement the Keep Row Changes method ● You INSERT, DELETE, UPDATE and SELECT data, getting the same results you would get with a regular table ● Old versions of the rows are stored in the same (logical) table ● To get old data, you need to use a special syntaxes, like: SELECT … AS OF TIMESTAMP '2018/01/01 16:30:00';
  • 12. Where are sysver tables implemented? In the proprietary DBMS world: ● Oracle 11g (2007) ● Db2 (2012) ● SQL Server 2016 Sometimes they are called Temporal Tables In Db2, a temporal table can use system-period or application-period
  • 13. Where are sysver tables implemented? In the open source world: ● PostgreSQL, as an extension ● CockroachDB ● MariaDB 10.3 PostgreSQL and CockroachDB implementations have important limitations
  • 14. Where are sysver tables implemented? In the NoSQL world: ● In HBase, rows have a version property
  • 16. Overview ● Implemented in MariaDB 10.3 (stable since Apr 2017) ● You must have row-start and row-end Generated Columns ○ Type: TIMESTAMP(6) or DATETIME(6) ○ You decide the names ○ These are Invisible Columns (10.3 feature) ● Any storage engine ○ Except CONNECT (MDEV-15968)
  • 17. ALTER TABLE ● Forbidden by default ○ Changes that only affect metadata also forbidden ○ system_versioning_alter_history='KEEP’ ● ADD COLUMN adds a column that is set to the current DEFAULT value or NULL for all old version rows ○ When was the column added? ● DROP COLUMN also affects old versions of the rows ○ The column’s history is lost ● CHANGE COLUMN also affects old versions of the rows ○ The column’s history is modified
  • 18. Example CREATE OR REPLACE TABLE employee ( ... valid_from TIMESTAMP(6) GENERATED ALWAYS AS ROW START COMMENT ‘When the row was INSERTed', valid_to TIMESTAMP(6) GENERATED ALWAYS AS ROW END COMMENT 'When row was DELETEd or UPDATEd', PERIOD FOR SYSTEM_TIME (valid_from, valid_to) ) WITH SYSTEM VERSIONING, ENGINE InnoDB;
  • 19. Adding versioning to an existing table ALTER TABLE employee LOCK = SHARED, ALGORITHM = COPY, ADD COLUMN valid_from TIMESTAMP(6) GENERATED ALWAYS AS ROW START, ADD COLUMN valid_to TIMESTAMP(6) GENERATED ALWAYS AS ROW END, ADD PERIOD FOR SYSTEM_TIME(valid_from, valid_to), ADD SYSTEM VERSIONING ; ● Notice ALGORITHM=COPY and LOCK=SHARED
  • 20. Querying historical data: point in time SELECT * FROM my_table FOR SYSTEM_TIME ● AS OF TIMESTAMP'2018-10-01 12:00:00' ● FROM '2018-10-01 00:00:00' TO '2018-11-01 00:00:00' ● BETWEEN (NOW() - INTERVAL 1 YEAR) AND NOW() ALL SELECT * FROM my_table FOR SYSTEM_TIME ALL WHERE valid_from < @end AND valid_to > @start;
  • 21. Querying historical data: point in time SELECT * FROM my_table FOR SYSTEM_TIME ● AS OF TIMESTAMP'2018-10-01 12:00:00' ● AS OF (SELECT valid_from FROM employee WHERE id=50) ● AS OF @some_event_timestamp
  • 22. Querying historical data: time range SELECT * FROM my_table FOR SYSTEM_TIME ● FROM '2018-10-01 00:00:00' TO '2018-11-01 00:00:00' ● FROM (SELECT ...) TO (SELECT ...) ● FROM @some_event TO @another_event
  • 23. Querying historical data: time range SELECT * FROM my_table FOR SYSTEM_TIME ● BETWEEN '2018-10-01 00:00:00' AND '2018-11-01 00:00:00' ● BETWEEN (NOW() - INTERVAL 1 YEAR) AND NOW() ● BETWEEN @some_event AND (SELECT ...)
  • 24. Querying historical data: example INSERT INTO customer (id, first_name, last_name, email) VALUES (1, 'William', 'Hartnell', 'the_first@gmail.com'), (2, 'Tom', 'Baker', 'tom.baker@gmail.com'); SET @beginning_of_time := NOW(6); DELETE FROM customer WHERE id = 1; UPDATE customer SET email = 'tom.baker@hotmail.com' WHERE id=2; INSERT INTO customer (id, first_name, last_name, email) VALUES (3, 'Peter', 'Capaldi', 'capaldi.petey@gmail.com'); SET @twelve_regeneration := NOW(6); INSERT INTO customer (id, first_name, last_name, email) VALUES (4, 'Jody', 'Wittaker', 'jody@gmail.com');
  • 25. Querying historical data: example SELECT id, first_name, last_name, valid_from, valid_to FROM customer FOR SYSTEM_TIME BETWEEN @beginning_of_time AND @twelve_regeneration; +----+------------+-----------+----------------------------+----------------------------+ | id | first_name | last_name | valid_from | valid_to | +----+------------+-----------+----------------------------+----------------------------+ | 1 | William | Hartnell | 2018-11-04 13:50:33.627753 | 2018-11-04 13:50:33.633414 | | 2 | Tom | Baker | 2018-11-04 13:50:33.627753 | 2018-11-04 13:50:33.638419 | | 2 | Tom | Baker | 2018-11-04 13:50:33.638419 | 2038-01-19 03:14:07.999999 | | 3 | Peter | Capaldi | 2018-11-04 13:50:33.644880 | 2038-01-19 03:14:07.999999 | +----+------------+-----------+----------------------------+----------------------------+
  • 26. Partitions ● By default, the history is stored together with current data ● You can put the history on separate partitions ● And limit them: ○ By rows number ○ By time
  • 27. Indexes ● The ROW END column is appended to UNIQUE indexes and the PK ● Other indexes are untouched ○ You may consider adding ROW END to some of your indexes ○ This is a good reason to define temporal columns explicitly
  • 29. Basic Examples ● First examples take advantage of temporal columns to identify INSERTs, DELETEs and UPDATEs
  • 30. Get DELETEd rows ● Get canceled orders: SET @eot := '2038-01-19 03:14:07.999999'; SELECT * FROM `order` FOR SYSTEM_TIME ALL WHERE valid_to < @eot; ● Get orders canceled today: SELECT COUNT(*) FROM `order` FOR SYSTEM_TIME WHERE valid_to = @ AND valid_from DATE(NOW()) AND (DATE(NOW()) + INTERVAL 1 DAY);
  • 31. Get INSERTed rows ● Get orders generated today: SELECT id, MIN(valid_from) AS insert_time FROM `order` FOR SYSTEM_TIME ALL GROUP BY id HAVING DATE(MIN(valid_from)) = DATE(NOW()) ORDER BY MIN(valid_from);
  • 32. Get UPDATEd rows ● How many times orders were modified: SELECT -- exclude the INSERTions id, (COUNT(*) – 1) AS how_many_edits FROM `order` FOR SYSTEM_TIME ALL -- exclude DELETions WHERE valid_to < @eot GROUP BY id ORDER BY how_many_edits;
  • 33. Debug mistakes in a single row ● Wrong data has been found in a row. The original version of the row was correct, so we want to know when the mistake (or malicious change) happened
  • 34. Debug mistakes in a single row ● Find all versions of a row: SELECT id, status, valid_from, valid_to FROM `order` FOR SYSTEM_TIME ALL WHERE id = 24;
  • 35. Debug mistakes in a single row ● When an order was blocked: SELECT DATE(MIN(valid_from)) AS block_date FROM `order` FOR SYSTEM_TIME ALL WHERE status = 'BLOCKED' AND id = 24;
  • 36. Debug mistakes in a single row ● Status is wrong. To find out how the problem happened, we want to check the INSERT and all following status changes: SELECT id, status, valid_from, valid_to FROM ( SELECT NOT (status <=> @prev_status) AS status_changed, @prev_status := status, id, status, valid_from, valid_to FROM `order` FOR SYSTEM_TIME ALL WHERE id = 24 ) t WHERE status_changed = 1;
  • 37. Debug mistakes in a single row ● We want to know if the status is the same as one month ago: SELECT present.id, present.status AS current_status, past.status AS past_status FROM `order` present INNER JOIN `order` FOR SYSTEM_TIME AS OF TIMESTAMP NOW() - INTERVAL 1 MONTH AS past ON present.id = past.id ORDER BY present.id;
  • 38. Stats on data changes SELECT AVG(amount), STDDEV(amount), MAX(amount), MIN(amount), COUNT(amount) FROM account FOR SYSTEM_TIME ALL WHERE customer_id = 24 AND valid_from BETWEEN '2016-00-00' AND NOW() GROUP BY customer_id;