The error below is the error that you’ll see whenever you’ll violate the constraint which is set for a particular column in a table. VALUES ( 'Anamika', 34,, 'Female') Code language: SQL (Structured Query Language) ( sql ) But in the below example, even though the gender is technically correct still SQL will throw an error because we have allowed ‘F’ for female and no other value. As we have only allowed three input values to the Gender column which are F, M, and T for Female, Male, and Transgender respectively. Let’s see how to write a statement for the same.ĪDD chk_age CHECK (Age >= 18 AND Age <= 65) Code language: SQL (Structured Query Language) ( sql ) Insert data into the table and Check the constraint errorĪs we have created all the necessary CHECK constraints on the Employee table, now whenever we’ll insert data into the table then the constraints will also be checked before the data is inserted into the table by SQL.įor example, if we write the below statement for the employee table then MySQL will throw an error. We need to restrict the age of our employees from 18 to 65. Let’s understand it with an example, we’ll take the employee table which we just created, having the name, age, email, and gender of the employees in which gender already has a check constraint. In cases where the table already exists, and we want to put a constraint over a column then it can be possible by putting a constraint on a column with ALTER Table. In our case, we’ll use the CHECK constraint.īelow is the syntax for creating a CHECK constraint using ALTER table: ALTER TABLE tablenameĪDD constraint_name CHECK (check_constraint) Code language: SQL (Structured Query Language) ( sql ) ) Code language: SQL (Structured Query Language) ( sql ) CHECK constraint using ALTER table statement Out of these four values, we are going to put CHECK constraint on gender, specifically male(M) or female(F), or transgender(T). We’ll create a table as Employee and will have four attributes, such as name, gender, age, and email. ) Code language: SQL (Structured Query Language) ( sql )įor better understanding let’s take an example. CONSTRAINT check_name CHECK ( constraint)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |