MySQL is a very famous and widely used open-source RDBMS. It is used to store, retrieve, and manage structured data efficiently. It is used in both types of applications i.e. large and small scale applications. In MySQL, the CHECK constraint enforces a condition on the column(s) of a table. It makes sure that a specific type of data only gets inserted into the table.
In this article, we are going to explore various use cases of MYSQL check constraints. We are going to cover all the basic points with clear and concise examples along with their explanations.
MYSQL CHECK Constraint
In MYSQL, the Check constraint is used to impose conditions on what type of data to be inserted into our table. It helps in maintaining the accuracy and consistency of the data. It helps in avoiding the entry of data that does not follow our specified conditions.
NOTE :- MySQL does not support check constraints before version 8.0.16. All the versions prior to 8.0.16 , will throw you an error on applying CHECK constraint on the table.
Creating a table with CHECK Constraint
In this, we are heading to create a table in our database. We will create a table named 'geeksforgeeks'. We will apply a check constraint on two of its columns.
Query:
CREATE TABLE geeksforgeeks(
id int PRIMARY KEY,
name varchar(100),
questions int,
rank int,
CONSTRAINT CHK_validEntry CHECK (rank <= 100 and questions >100)
);
Explanation : After executing this query, we will have a table in our database. Any row inserted into the table will have to follow check constraint condition i.e. rank should be less than or equal to 100 and questions should be grater than 100. If any rows fails to satisfy any of the mentioned condition, then this will throw an error.
Now lets insert data to our table and display them.
Query:
--Data Insertion
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(01,'Vishu',150,10);
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(02,'Sumit',145,15);
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(03,'Aayush',140,20);
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(04,'Neeraj',120,40);
-- Displaying our table's data
SELECT * from geeksforgeeks;
Output:
Table - geeksforgeeks
Explanation : In the above example, we can notice that all the above records follow the condition imposed by check constraint. All the records have questions grater than 100 and rank less than or equal to 100. Therefore all the records are successfully added to the table.
Examples of CHECK Constraints
In this, we are going to explore how check constraint actually works in MYSQL. We will see how it will behave if have try to enter any records which do not follow its imposed condition.
Example 1: Inserting a Row with Rank Grater than 100
In this example, we are going to see how check constraint will handle an insertion of record which do not follow its imposed condition.
Query:
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(05,'Vivek',150,120);
Output:
rank > 100Explanation: In the above image, we can clearly see than an error appeared. It because we have tried to enter a row with rank 120, which is grater than 100. Therefore failing to satisfy the check constraint condition will result in an error.
Example 2: Inserting a Row with Questions Less than 100
In this example, we will try to insert a row with questions less than 100. Like in the previous example, this will us an error too. In order to insert a row successfully into our table, we need to satisfy both the conditions.
Query:
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(05,'Vivek',15,12);
Output:
question < 100Explanation: In the above image, we can clearly notice an error. This error is caused as we try to enter a row with question less than 100 which is against our imposed condition. Therefore it throws us an error, just like in did in the previous example.
Drop the CHECK constraint
In order to drop CHECK constraint from our existing table, we will be using ALTER and DROP clause. ALTER Clause is used to modify the structure of the table and DROP Clause is used remove a database object.
Query:
ALTER TABLE geeksforgeeks
DROP CONSTRAINT CHK_validEntry;
After successfully executing this query we can add any type of rows to our table. Lets try one of the above example, which was previous throwing us an error.
Query:
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(05,'Vivek',150,120);
--Displaying table's data
SELECT * FROM geeksforgeeks;
Output:
Drop the check constraintExplanation: We have used the same query from 'example 1'. Previously, this query throw us an error but now we have removed the check constraint, we can clearly see that it executed successfully and row has been inserted into out table.
Adding CHECK Constraints to an Existing Table
We are going to add a CHECK constraint to our existing table. As our table have no check constraint, we add one with the below query.
Query:
ALTER TABLE geeksforgeeks
ADD CONSTRAINT CHK_validEntry
CHECK (rank < 500);
Now if we try to enter any row with rank grater than 500 will throw us an error.
Query:
INSERT INTO geeksforgeeks(id,name,questions,rank)
VALUES(06,'Harsh',150,560);
Output:
rank > 500Explanation: In the above image, we can clearly notice an error. This is due to our newly imposed check constraint condition i.e. rank should be less than 500. We can clearly see that we are trying to enter a new row with rank as '560' which is clearly not following our condition.
Conclusion
Overall, check constraint is use to impose a condition on the data which are going to be inserted into our table. We can clearly prevent on adding irrelevant data to our table. We have seen many examples related to check constraints, how to remove check constraint from existing table and adding check constraint to the existing table. Now you can write all the queries related to check constraint with ease can can get the desired output.
Similar Reads
PL/SQL Tutorial Explore this PL/SQL tutorial to effortlessly learn PL/SQL â It is perfect for beginners and experienced ones. Whether you're new to it or diving deep, this interactive guide simplifies database programming.Learn hands-on with practical examples, making your journey fun and effective. Learn PL/SQL's
8 min read
PL/SQL Fundamentals
PL/SQL Control & Loops
Decision Making in PL/SQLPL/SQL (Procedural Language/Structured Query Language) is Oracle's extension to SQL that allows for procedural programming within databases. It features various conditional statements to control the flow of execution based on specific conditions.In this article, We will learn about the various PL/SQ
5 min read
PL/SQL LoopsPL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. It is a block-structured language that
5 min read
PL/SQL For LoopPL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. With PL/SQL, you can fetch data from the table, add data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries. To fetch records, process dat
4 min read
PL/SQL While LoopOracle PL/SQL provides various loop structures that help developers execute a block of code multiple times based on certain conditions. The main loop structures include LOOP ... END LOOP, WHILE ... END LOOP, and FOR ... END LOOP. In this article, we will explore the WHILE loop in detail, including i
5 min read
PL/SQL Queries & Clauses
PL/SQL SELECT INTO Existing TablePL/SQL is a programming language that is used alongside SQL for writing procedural code such as stored procedures, functions, triggers, and packages within the Oracle Database. It was developed by Oracle Corporation and is widely used in database programming.PL/SQL is a programming language that has
5 min read
PL/SQL INSERT StatementThe PL/SQL INSERT statement is vital for adding new records to a database table. By specifying the table's name and providing values for its columns, users can populate their database with essential information. This functionality enables efficient data entry and ensures the completeness of datasets
3 min read
PL/SQL UPDATE StatementThe UPDATE statement in the PL/SQL(Procedural Language/ Structural Query Language) is the powerful SQL (Structured Query Language) command used to modify the existing data in the database table. In this article, we will explain the PL/SQL UPDATE Statement, its syntax, and examples in detail.PL/SQL U
6 min read
PL/SQL DELETE StatementIn PL/SQL(Procedural Language/Structured Query Language), the DELETE statement is the powerful command used to remove one or more records from the database table. It is an essential part of database management and enables the users to efficiently manage and maintain the data integrity by selectively
6 min read
PL/SQL WHERE ClauseThe WHERE clause in PL/SQL is essential for filtering records based on specified conditions. It is used in SELECT, UPDATE, and DELETE statements to limit the rows affected or retrieved, allowing precise control over data manipulation and retrieval.In this article, We will learn about the WHERE Claus
3 min read
PL/SQL ORDER BY ClauseIn PL/SQL, the ORDER BY clause is a vital tool that allows for the sorting of query results by one or more columns, either in ascending or descending order. In this article, We will learn about ORDER BY clause in PL/SQL, its syntax, functionality, and practical usage through examples.Understanding O
7 min read
PL/SQL GROUP BY ClauseThe GROUP BY clause in PL/SQL is a powerful tool used to organize data into aggregated groups based on one or more columns. It is essential for performing summary operations on large datasets, enabling efficient data analysis by grouping rows that share common values.In this article, We will learn a
7 min read
PL/SQL Operators
PLSQL : || OperatorThe string in PL/SQL is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. The || Operator in PLSQL is used to concatenate 2 or more strings together. The result of concatenating two char
2 min read
PL/SQL AND OperatorThe PL/SQL AND operator is used to combine multiple conditions in a WHERE clause of an SQL query. It allows you to refine your query by ensuring that all specified conditions are met. AND queries which help in filtering data more precisely and can be crucial for retrieving accurate results from a da
7 min read
PL/SQL LIKE OperatorThe PL/SQL LIKE operator is a powerful tool used in SQL queries to search for patterns in character data. It allows you to match strings based on specific patterns defined by wildcards. This operator is commonly used in SELECT, UPDATE, and DELETE statements to filter records based on partial or comp
6 min read
PL/SQL NOT OperatorPL/SQL, an extension of SQL in Oracle, offers various operators that allow us to perform logical operations on data. One such operator is the NOT operator, which is used to negate a condition, meaning it will return true if the condition is false and vice versa.The NOT operator is commonly used in c
6 min read
PL/SQL IS NULL OperatorThe IS NULL operator is a fundamental tool in PL/SQL used to determine the presence of NULL values in database columns. Understanding how to effectively use the IS NULL operator is crucial for database management, as it allows developers and analysts to identify and handle records with missing or un
4 min read
PL/SQL CASE StatementPL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. The PL/SQL CASE statement is a powerfu
4 min read
PL/SQL Program Units
PL/SQL Data Structures & Error Handling
Index in PL/SQLPL/SQL, Oracle's extension to SQL, combines SQL with procedural programming features like loops, conditionals, and exception handling. It enables developers to create stored procedures, functions, triggers, and other database applications. As a block-structured language, PL/SQL allows seamless integ
5 min read
Exception Handling in PL/SQLAn exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the exception block which raises the exception thus helping the programmer to find out the fault and resolve it. There are two types of exceptions defined in PL/SQL User defined exception. System defi
7 min read
PL/SQL RecordsPL/SQL stands for Procedural Language/Structured Query Language. It is an extension of the Structured Query Language (SQL). A core feature of PL/SQL is its ability to work with complex data types, including PL/SQL records. PL/SQL records enable developers to group related data elements, creating a s
10 min read
Cursors in PL/SQLA Cursor in PL/SQL is a pointer to a context area that stores the result set of a query. PL/SQL CursorsThe cursor is used to retrieve data one row at a time from the results set, unlike other SQL commands that operate on all rows at once. Cursors update table records in a singleton or row-by-row man
3 min read