SlideShare a Scribd company logo
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

More Related Content

What's hot

Query
QueryQuery
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 
SQL Views
SQL ViewsSQL Views
SQL Server Views
SQL Server ViewsSQL Server Views
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
AnusAhmad
 
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
Tayba Farooqui
 
SQL
SQLSQL
Implementing views
Implementing views Implementing views
Implementing views
sqlschoolgr
 
Sql DML
Sql DMLSql DML
Sql DML
Vikas Gupta
 
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)
Achmad Solichin
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
ShivaAdasule
 
Chap 7
Chap 7Chap 7
Chap 7
Karan Patil
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
Brian Foote
 
Les08
Les08Les08
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
Belle Wx
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
Amrit Kaur
 
Module 3
Module 3Module 3
Module 3
cs19club
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
Sql ch 13 - sql-views
Sql ch 13 - sql-viewsSql ch 13 - sql-views
Sql ch 13 - sql-views
Mukesh Tekwani
 
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
baabtra.com - No. 1 supplier of quality freshers
 

What's hot (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
 

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

03Constraints - last.pdf
03Constraints - last.pdf03Constraints - last.pdf
03Constraints - last.pdf
ssuserfd620b
 
zekeLabs sql-slides
zekeLabs sql-slideszekeLabs sql-slides
zekeLabs sql-slides
zekeLabs Technologies
 
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
Vibrant Technologies & Computers
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
maxpane
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
SaurabhLokare1
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
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
SHAKIR325211
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai1
 
IR SQLite Session #3
IR SQLite Session #3IR SQLite Session #3
IR SQLite Session #3
InfoRepos Technologies
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
Zaid227349
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
sagaroceanic11
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
ARVIND SARDAR
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
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.pptx
YashaswiniSrinivasan1
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
Achmad Solichin
 
Lab
LabLab
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
PavithSingh
 

Similar to 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
 

Recently uploaded

Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 

Recently uploaded (20)

Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 

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