SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Future-Proof Your Business
with Oracle Cloud Apps
Steve Miranda
Executive Vice President
Applications & Product Development
Agenda
• Check Constraints on a High Level
• Creating Check Constraints
• Check Constraints Evaluation
• Check Constraint Expressions
• Altering/Dropping Check Constraints
• INFORMATION_SCHEMA Tables
Check Constraint on a High Level ...
• Is a type of table integrity constraint (similar to PRIMARY KEY, FOREIGN KEY,
UNIQUE and NOT NULL)
• Specifies requirement to be met by each row
– As a boolean expression
– Can refer a single or multiple columns
– Result can be TRUE/FALSE and UNKNOWN (if NULLs are involved)
– Constraint is satisfied if result is TRUE or UNKNOWN
A Bit of History
Wait, but aren’t Check Constraints supported by MySQL before 8.0?
• Before 8.0 syntax is accepted but ignored!
• Proper support starting from 8.0.16
– Improvements in 8.0.19
Basic example:
CREATE TABLE employees (
id INT PRIMARY KEY CHECK(id > 0),
name VARCHAR(255) NOT NULL,
hire_date DATE NOT NULL,
end_date DATE,
CHECK(end_date > hire_date)
);
Column constraint
can refer only to its column
For current employees
end_date is NULL,
expression is UNKNOWN,
thus constraint is satisfied
Typical Use Scenarios
• Limit value range
• Allow only certain
values/values that match
pattern
• Enforce relations
between columns of a
same row
CREATE TABLE employees (
id INT PRIMARY KEY CHECK(id > 0),
name VARCHAR(255) NOT NULL,
age INT CHECK (age > 18),
hire_date DATE NOT NULL,
end_date DATE,
country VARCHAR(10),
zip VARCHAR(10),
CHECK(country <> “RUS” OR LENGTH(zip) = 6),
CHECK(end_date > hire_date)
);
Creating Check Constraints: Syntax
CREATE TABLE supports the following SQL-standard syntax in column definition and
table definition:
[ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ]
CREATE TABLE employees (
id INT PRIMARY KEY CONSTRAINT id_check CHECK(id > 0),
name VARCHAR(255) NOT NULL,
hire_date DATE NOT NULL,
end_date DATE,
CONSTRAINT end_date_check CHECK(end_date > hire_date)
);
Naming
[ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ]
• CONSTRAINT [symbol] clause is optional
• Generated names format: <table_name>_chk_<ordinal_number>
• Separate namespace from UNIQUE and FOREIGN KEY constraints (non-
standard)
Naming Example
CREATE TABLE employees (
id INT PRIMARY KEY
CONSTRAINT id_check CHECK(id > 0),
name VARCHAR(255) NOT NULL,
hire_date DATE NOT NULL,
end_date DATE,
CHECK(end_date > hire_date)
);
SHOW CREATE TABLE employeesG
....
Create Table: CREATE TABLE `employees` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`hire_date` date NOT NULL,
`end_date` date DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `employees_chk_1` CHECK
((`end_date` > `hire_date`)),
CONSTRAINT `id_check` CHECK ((`id` > 0))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci
[NOT] ENFORCED clause
[ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ]
• Optional clause which allows to control whether constraint is enforced or not
• ENFORCED is default
• Add NOT ENFORCED to create check constraint which won’t be enforced
• Can be changed later using ALTER TABLE
Adding check constraints to existing tables
• ALTER TABLE allows to add column check constraints as part of definition of
column which is added:
ALTER TABLE <table_name> ADD COLUMN <symbol> <col definition>
[CONSTRAINT [symbol]] CHECK (condition) [[NOT] ENFORCED]
• ALTER TABLE supports addition of table check constraints with syntax:
ALTER TABLE <table_name>
ADD [CONSTRAINT [symbol]] CHECK (condition) [[NOT] ENFORCED]
When Check Constraints are Evaluated?
• For DML statements that insert or modify data:
– INSERT
– UPDATE
– REPLACE
– LOAD DATA/XML
• For some of DDL statements:
– CREATE TABLE … SELECT
– ALTER TABLE
How Check Constraints are Evaluated?
• For each row
• Constraints in NOT ENFORCED state are skipped
• Constraint violation is reported as error
• With IGNORE clause in DML statements that error becomes a
warning and offending row is skipped
• Evaluation happens after execution of BEFORE triggers but before
passing row to storage engine
Check Constraints Evaluation: Example
mysql> INSERT INTO employees VALUES (1, "Alice", "1996-06-20", "2011-07-16");
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO employees VALUES (2, "Bob", "1996-06-20", NULL);
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO employees VALUES (3, "Charles", "1996-06-20", "1995-07-16");
ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated.
mysql> INSERT IGNORE INTO employees VALUES (3, "Charles", "1996-06-20", "1995-07-16");
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> SHOW WARNINGS;
+---------+------+-------------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------------+
| Warning | 3819 | Check constraint 'employees_chk_1' is violated. |
+---------+------+-------------------------------------------------+
1 row in set (0.00 sec)
Check Constraint Expressions
Permitted constructs
•
References to base and generated columns
•
Literals, operators and deterministic built-in
functions (ABS(), LENGTH(), TIMEDIFF(),
ISNULL(),...)
Prohibited constructs
• AUTO_INCREMENT columns
• Non-deterministic and set functions
(RAND(), AVG(),...)
• Sub-queries
• Environment variables (CURRENT_USER,
CURRENT_TIME,…)
• System, user and stored program variables
• Stored functions and UDFs
• Implicit type conversion occurs if operand types mismatch
• Expressions are kept always valid by prohibiting renaming and dropping of participating
columns (auto-dropping constraints with single column reference being exception)
Altering Check Constraints
ALTER TABLE clauses to change check constraint enforcement state:
ALTER TABLE <table_name> ALTER CHECK symbol [NOT] ENFORCED
– Supported since 8.0.16
– Non-standard
– Applies to check constraints only
ALTER TABLE <table_name> ALTER CONSTRAINT symbol [NOT] ENFORCED
– Supported since 8.0.19
– Standard
– In future might apply to other constraint types
Dropping Check Constraints
ALTER TABLE clauses to drop check constraints:
ALTER TABLE <table_name> DROP CHECK symbol
– Supported since 8.0.16
– Non-standard
– Applies to check constraints only
ALTER TABLE <table_name> DROP CONSTRAINT symbol
– Supported since 8.0.19
– Standard
– Also applies to other constraint types (emits error in case ambiguity)
Also dropping column automatically drops constraint if its condition references
that and only that column.
Check Constraints in INFORMATION_SCHEMA
New table - INFORMATION_SCHEMA.CHECK_CONSTRAINTS
Rows for Check Constraints in existing INFORMATION_SCHEMA.TABLE_CONSTRAINTS
More Information on Check Constraints
MySQL documentation on check constraints:
https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
Blogpost on check constraint:
https://mysqlserverteam.com/mysql-8-0-16-introducing-check-constraint/
MySQL documentation on CREATE TABLE and ALTER TABLE syntax:
https://dev.mysql.com/doc/refman/8.0/en/create-table.html
https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
MySQL documentation on INFORMATION_SCHEMA tables:
https://dev.mysql.com/doc/refman/8.0/en/check-constraints-table.html
https://dev.mysql.com/doc/refman/8.0/en/table-constraints-table.html
MySQL documentation on SHOW table:
https://dev.mysql.com/doc/refman/8.0/en/show-create-table.html
Thank You

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Query
QueryQuery
Query
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL Server Views
SQL Server ViewsSQL Server Views
SQL Server Views
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
 
Designing and Creating Views, Inline Functions, and Synonyms
 Designing and Creating Views, Inline Functions, and Synonyms Designing and Creating Views, Inline Functions, and Synonyms
Designing and Creating Views, Inline Functions, and Synonyms
 
SQL
SQLSQL
SQL
 
Implementing views
Implementing views Implementing views
Implementing views
 
Sql DML
Sql DMLSql DML
Sql DML
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
 
Chap 7
Chap 7Chap 7
Chap 7
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Les08
Les08Les08
Les08
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Module 3
Module 3Module 3
Module 3
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Sql ch 13 - sql-views
Sql ch 13 - sql-viewsSql ch 13 - sql-views
Sql ch 13 - sql-views
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 

Ähnlich wie Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020

03Constraints - last.pdf
03Constraints - last.pdf03Constraints - last.pdf
03Constraints - last.pdfssuserfd620b
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsmaxpane
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systemsSHAKIR325211
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleFarhan Aslam
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai1
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro projectARVIND SARDAR
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxYashaswiniSrinivasan1
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)Achmad Solichin
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 

Ähnlich wie Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020 (20)

03Constraints - last.pdf
03Constraints - last.pdf03Constraints - last.pdf
03Constraints - last.pdf
 
zekeLabs sql-slides
zekeLabs sql-slideszekeLabs sql-slides
zekeLabs sql-slides
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
IR SQLite Session #3
IR SQLite Session #3IR SQLite Session #3
IR SQLite Session #3
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptx
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Lab
LabLab
Lab
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 

Kürzlich hochgeladen

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
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
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 

Kürzlich hochgeladen (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).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
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 

Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020

  • 1. Future-Proof Your Business with Oracle Cloud Apps Steve Miranda Executive Vice President Applications & Product Development
  • 2. Agenda • Check Constraints on a High Level • Creating Check Constraints • Check Constraints Evaluation • Check Constraint Expressions • Altering/Dropping Check Constraints • INFORMATION_SCHEMA Tables
  • 3. Check Constraint on a High Level ... • Is a type of table integrity constraint (similar to PRIMARY KEY, FOREIGN KEY, UNIQUE and NOT NULL) • Specifies requirement to be met by each row – As a boolean expression – Can refer a single or multiple columns – Result can be TRUE/FALSE and UNKNOWN (if NULLs are involved) – Constraint is satisfied if result is TRUE or UNKNOWN
  • 4. A Bit of History Wait, but aren’t Check Constraints supported by MySQL before 8.0? • Before 8.0 syntax is accepted but ignored! • Proper support starting from 8.0.16 – Improvements in 8.0.19
  • 5. Basic example: CREATE TABLE employees ( id INT PRIMARY KEY CHECK(id > 0), name VARCHAR(255) NOT NULL, hire_date DATE NOT NULL, end_date DATE, CHECK(end_date > hire_date) ); Column constraint can refer only to its column For current employees end_date is NULL, expression is UNKNOWN, thus constraint is satisfied
  • 6. Typical Use Scenarios • Limit value range • Allow only certain values/values that match pattern • Enforce relations between columns of a same row CREATE TABLE employees ( id INT PRIMARY KEY CHECK(id > 0), name VARCHAR(255) NOT NULL, age INT CHECK (age > 18), hire_date DATE NOT NULL, end_date DATE, country VARCHAR(10), zip VARCHAR(10), CHECK(country <> “RUS” OR LENGTH(zip) = 6), CHECK(end_date > hire_date) );
  • 7. Creating Check Constraints: Syntax CREATE TABLE supports the following SQL-standard syntax in column definition and table definition: [ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ] CREATE TABLE employees ( id INT PRIMARY KEY CONSTRAINT id_check CHECK(id > 0), name VARCHAR(255) NOT NULL, hire_date DATE NOT NULL, end_date DATE, CONSTRAINT end_date_check CHECK(end_date > hire_date) );
  • 8. Naming [ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ] • CONSTRAINT [symbol] clause is optional • Generated names format: <table_name>_chk_<ordinal_number> • Separate namespace from UNIQUE and FOREIGN KEY constraints (non- standard)
  • 9. Naming Example CREATE TABLE employees ( id INT PRIMARY KEY CONSTRAINT id_check CHECK(id > 0), name VARCHAR(255) NOT NULL, hire_date DATE NOT NULL, end_date DATE, CHECK(end_date > hire_date) ); SHOW CREATE TABLE employeesG .... Create Table: CREATE TABLE `employees` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `hire_date` date NOT NULL, `end_date` date DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `employees_chk_1` CHECK ((`end_date` > `hire_date`)), CONSTRAINT `id_check` CHECK ((`id` > 0)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
  • 10. [NOT] ENFORCED clause [ CONSTRAINT [symbol] ] CHECK (condition) [ [ NOT ] ENFORCED ] • Optional clause which allows to control whether constraint is enforced or not • ENFORCED is default • Add NOT ENFORCED to create check constraint which won’t be enforced • Can be changed later using ALTER TABLE
  • 11. Adding check constraints to existing tables • ALTER TABLE allows to add column check constraints as part of definition of column which is added: ALTER TABLE <table_name> ADD COLUMN <symbol> <col definition> [CONSTRAINT [symbol]] CHECK (condition) [[NOT] ENFORCED] • ALTER TABLE supports addition of table check constraints with syntax: ALTER TABLE <table_name> ADD [CONSTRAINT [symbol]] CHECK (condition) [[NOT] ENFORCED]
  • 12. When Check Constraints are Evaluated? • For DML statements that insert or modify data: – INSERT – UPDATE – REPLACE – LOAD DATA/XML • For some of DDL statements: – CREATE TABLE … SELECT – ALTER TABLE
  • 13. How Check Constraints are Evaluated? • For each row • Constraints in NOT ENFORCED state are skipped • Constraint violation is reported as error • With IGNORE clause in DML statements that error becomes a warning and offending row is skipped • Evaluation happens after execution of BEFORE triggers but before passing row to storage engine
  • 14. Check Constraints Evaluation: Example mysql> INSERT INTO employees VALUES (1, "Alice", "1996-06-20", "2011-07-16"); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO employees VALUES (2, "Bob", "1996-06-20", NULL); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO employees VALUES (3, "Charles", "1996-06-20", "1995-07-16"); ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated. mysql> INSERT IGNORE INTO employees VALUES (3, "Charles", "1996-06-20", "1995-07-16"); Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> SHOW WARNINGS; +---------+------+-------------------------------------------------+ | Level | Code | Message | +---------+------+-------------------------------------------------+ | Warning | 3819 | Check constraint 'employees_chk_1' is violated. | +---------+------+-------------------------------------------------+ 1 row in set (0.00 sec)
  • 15. Check Constraint Expressions Permitted constructs • References to base and generated columns • Literals, operators and deterministic built-in functions (ABS(), LENGTH(), TIMEDIFF(), ISNULL(),...) Prohibited constructs • AUTO_INCREMENT columns • Non-deterministic and set functions (RAND(), AVG(),...) • Sub-queries • Environment variables (CURRENT_USER, CURRENT_TIME,…) • System, user and stored program variables • Stored functions and UDFs • Implicit type conversion occurs if operand types mismatch • Expressions are kept always valid by prohibiting renaming and dropping of participating columns (auto-dropping constraints with single column reference being exception)
  • 16. Altering Check Constraints ALTER TABLE clauses to change check constraint enforcement state: ALTER TABLE <table_name> ALTER CHECK symbol [NOT] ENFORCED – Supported since 8.0.16 – Non-standard – Applies to check constraints only ALTER TABLE <table_name> ALTER CONSTRAINT symbol [NOT] ENFORCED – Supported since 8.0.19 – Standard – In future might apply to other constraint types
  • 17. Dropping Check Constraints ALTER TABLE clauses to drop check constraints: ALTER TABLE <table_name> DROP CHECK symbol – Supported since 8.0.16 – Non-standard – Applies to check constraints only ALTER TABLE <table_name> DROP CONSTRAINT symbol – Supported since 8.0.19 – Standard – Also applies to other constraint types (emits error in case ambiguity) Also dropping column automatically drops constraint if its condition references that and only that column.
  • 18. Check Constraints in INFORMATION_SCHEMA New table - INFORMATION_SCHEMA.CHECK_CONSTRAINTS Rows for Check Constraints in existing INFORMATION_SCHEMA.TABLE_CONSTRAINTS
  • 19. More Information on Check Constraints MySQL documentation on check constraints: https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html Blogpost on check constraint: https://mysqlserverteam.com/mysql-8-0-16-introducing-check-constraint/ MySQL documentation on CREATE TABLE and ALTER TABLE syntax: https://dev.mysql.com/doc/refman/8.0/en/create-table.html https://dev.mysql.com/doc/refman/8.0/en/alter-table.html MySQL documentation on INFORMATION_SCHEMA tables: https://dev.mysql.com/doc/refman/8.0/en/check-constraints-table.html https://dev.mysql.com/doc/refman/8.0/en/table-constraints-table.html MySQL documentation on SHOW table: https://dev.mysql.com/doc/refman/8.0/en/show-create-table.html