0% found this document useful (0 votes)
21 views11 pages

SQL 4

Uploaded by

jincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views11 pages

SQL 4

Uploaded by

jincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Constraints are the rules that we can apply on the type of data in a table.

That is, we can specify the


limit on the type of data that can be stored in a particular column in a table using constraints. In a
database table, we can add rules to a column known as constraints. These rules control the data that
can be stored in a column.

The available constraints in SQL are:

NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is
specified as NOT NULL then we will not be able to store null in this particular column any more.

UNIQUE: This constraint when specified with a column, tells that all the values in the column must
be unique. That is, the values in any row of a column must not be repeated.

PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.

FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And
this constraint is used to specify a field as Foreign key.

CHECK: This constraint helps to validate the values of a column to meet a particular condition. That
is, it helps to ensure that the value stored in a column meets a specific condition.

DEFAULT: This constraint specifies a default value for the column when no value is specified by the
user.

How to specify constraints?


We can specify constraints at the time of creating the table using CREATE TABLE statement. We can
also specify the constraints after creating a table using ALTER TABLE statement.

Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the
table.

CREATE TABLE sample_table

column1 data_type(size) constraint_name,

column2 data_type(size) constraint_name,

column3 data_type(size) constraint_name,

....

);

sample_table: Name of the table to be created.

data_type: Type of data that can be stored in the field.


constraint_name: Name of the constraint. for example- NOT NULL, UNIQUE, PRIMARY KEY etc.

Let us see each of the constraint in detail.

NOT NULL –
If we specify a field in a table to be NOT NULL. Then the field will never accept null value. That is, you
will be not allowed to insert a new row in the table without specifying any value to this field. NOT
NULL Constraint

The NOT NULL constraint in a column means that the column cannot store NULL values. For example,

CREATE TABLE Colleges (

college_id INT NOT NULL,

college_code VARCHAR(20) NOT NULL,

college_name VARCHAR(50)

);

Here, the college_id and the college_code columns of the Colleges table won't
allow NULL values.

Remove NOT NULL Constraint


We can also remove the NOT NULL constraint if that is no longer needed. For example,

ALTER TABLE Colleges

MODIFY COLUMN college_name VARCHAR(50) NULL;

The SQL code ALTER TABLE Colleges MODIFY COLUMN college_name


VARCHAR(50) NULL; is used to modify the structure of the Colleges table
by changing the data type and nullability constraint of the college_name
column.

Let's break down the code step by step:

ALTER TABLE Colleges : This part of the code indicates that you want to
make changes to the Colleges table.
MODIFY COLUMN college_name : This specifies that you want to modify the
college_name column.
VARCHAR(50): This is the new data type you want to assign to the
college_name column. It sets the data type to VARCHAR (variable-length
character string) with a maximum length of 50 characters.
NULL: This keyword indicates that you want to allow NULL values in the
college_name column. By setting it to NULL, the column will be able to
store both empty values (NULL) and non-empty values.

The purpose of this SQL statement is to alter the college_name column in


the Colleges table to be able to store strings of up to 50 characters in
length and allow NULL values. Before executing this statement, it's
essential to ensure that the table and column names are correct and that
the modification aligns with your intended database design. Additionally,
if there are existing records i n the college_name column, changing it to
allow NULLs may affect any constraints or queries relying on non-NULL
values, so you should consider the implications of this modification
carefully.

For example, the below query creates a table Student with the fields ID and NAME as NOT NULL.
That is, we are bound to specify values for these two fields every time we wish to insert a new row.

PRIMARY KEY –
Primary Key is a field which uniquely identifies each row in the table. If a field in a table as primary
key, then the field will not be able to contain NULL values as well as all the rows should have unique
values for this field. So, in other words we can say that this is combination of NOT NULL and UNIQUE
constraints.
The PRIMARY KEY constraint is simply a combination of NOT NULL and UNIQUE constraints. It means
that the column value is used to uniquely identify the row. For example,

Imagine you have a table called "Students" in a database to store information about students. Each
student has a unique ID assigned to them, and you want to ensure that no two students have the
same ID. This unique ID will help you identify each student uniquely and allow you to avoid any
confusion or duplication.

The Primary Key is a special column or a combination of columns in a database table that serves this
purpose. It uniquely identifies each row (record) in the table and ensures that there are no duplicate
values. In other words, it guarantees the uniqueness and integrity of each record in the table.

Let's create the "Students" table with a primary key called "student_id":

CREATE TABLE Students ( student_id INT PRIMARY KEY, first_name VARCHAR(50), last_name
VARCHAR(50), age INT );

In this example, the student_id column is declared as the primary key for the "Students" table. It
means that each value in the student_id column must be unique, and it cannot be NULL. Whenever
you insert a new student into the table, you must provide a unique student_id.

Here's an example of how you might insert data into the "Students" table:

INSERT INTO Students (student_id, first_name, last_name, age) VALUES (1, 'John', 'Doe', 20);
INSERT INTO Students (student_id, first_name, last_name, age) VALUES (2, 'Jane', 'Smith', 19);

Now, let's say you accidentally try to insert a student with the same student_id:

INSERT INTO Students (student_id, first_name, last_name, age) VALUES (1, 'Mike', 'Johnson', 22);

Since student_id is the primary key, the database will reject this insertion and raise an error because
the value 1 is already used by the first student (John Doe). This prevents any duplicate student IDs
and maintains the uniqueness of each student record.

In summary, the Primary Key is a crucial concept in database design. It provides a way to uniquely
identify each record in a table, ensures data integrity, and helps in establishing relationships with
other tables in the database. It plays a fundamental role in maintaining the accuracy and consistency
of data within the database.

A table can have only one field as primary key.

FOREIGN KEY –
Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this
field points to primary key of another table. This usually creates a kind of link between the tables.
Consider the two tables as shown below:

In SQL, the FOREIGN KEY constraint is used to create a relationship between two tables. A foreign
key is defined using the FOREIGN KEY and REFERENCES keywords.
Referencing Columns in Another Table with FOREIGN KEY

The FOREIGN KEY constraint in SQL establishes a relationship between two tables by linking columns
in one table to those in another. For example,

Imagine you have two tables in a database:

Table: Students
Columns:
student_id (Primary Key)
student_name
student_age
student_grade
Table: Courses
Columns:
course_id (Primary Key)
course_name
course_teacher

Now, let's say you want to create a relationship between these two tables,
such that each student can enroll in multiple courses, and each course
can have multiple students enrolled. This relationship is known as a "one-
to-many" relationship because one student can enroll in many courses,
but each course can have only one teacher.

To establish this relationship, you would use a "foreign key." In the


Courses table, you would add a new column called student_id (or any
other suitable name) to store the ID of the student who enrolled in the
course.

Sure! Below is the SQL code to create both the Students and
Courses tables, along with the foreign key relationship between
them:

Create the Students table

CREATE TABLE Students ( student_id INT PRIMARY KEY,


student_name VARCHAR(50), student_age INT,
student_grade VARCHAR(2) );
Create the Courses table

CREATE TABLE Courses ( course_id INT PRIMARY KEY,


course_name VARCHAR(50), course_teacher VARCHAR(50),
student_id INT, FOREIGN KEY (student_id) REFERENCES
Students(student_id) );

Explanation:

The first block of code creates the Students table. It has four
columns: student_id, student_name, student_age, and student_grade.
The student_id column is set as the primary key using the PRIMARY
KEY constraint. The primary key uniquely identifies each student
in the table.
The second block of code creates the Courses table. It has four
columns: course_id, course_name, course_teacher, and student_id.
The course_id column is set as the primary key using the PRIMARY
KEY constraint. The primary key uniquely identifies each course in
the table.
The student_id column in the Courses table is designated as a
foreign key using the FOREIGN KEY constraint. This establishes the
relationship between the Courses table and the Students table.
REFERENCES Students(student_id) : This specifies that the student_id
column in the Courses table references the student_id column in the
Students table. It means that the values in the Courses.student_id
column must match the values present in the Students.student_id
column.

With these two tables and the foreign key constraint, you have
created a simple one-to-many relationship between the Students
and Courses tables. Each course in the Courses table can be
associated with a single student from the Students table. The
foreign key ensures that the student_id in the Courses table points
to valid student_id values in the Students table.
Below is the SQL code to insert sample data into the Students and Courses tables:

Insert data into the Students table

INSERT INTO Students (student_id, student_name, student_age, student_grade)


VALUES (1, 'John', 20, 'A'), (2, 'Mary', 19, 'B'), (3, 'Alice', 22, 'C'), (4, 'Bob', 18, 'A');

Insert data into the Courses table

INSERT INTO Courses (course_id, course_name, course_teacher, student_id)


VALUES (101, 'Math', 'Mr. Smith', 1), (102, 'Science', 'Mrs. Johnson', 2), (103,
'History', 'Mr. Brown', 1), (104, 'English', 'Mrs. White', NULL), (105, 'Physics', 'Mr.
Adams', 3);

Explanation:

The first INSERT statement inserts data into the Students table. It specifies the columns to
which data is being inserted (student_id, student_name, student_age, and student_grade)
and then provides multiple sets of values to be inserted using the VALUES clause. Each set
of values corresponds to a separate row in the table.

The second INSERT statement inserts data into the Courses table. It specifies the columns
to which data is being inserted (course_id, course_name, course_teacher, and student_id)
and then provides multiple sets of values to be inserted using the VALUES clause. Each set
of values corresponds to a separate row in the table.

In the example data provided:

The Students table has four rows representing different students with their respective details.

The Courses table has five rows representing different courses with their respective details
and an additional row where no student is enrolled (NULL value).
With this data insertion, the Students and Courses tables now have sample data, and the
foreign key relationship ensures that the student_id values in the Courses table match valid
student_id values from the Students table.

Please note that the primary key values (student_id and course_id) are unique identifiers,
and each should be unique within its respective table. In a real-world scenario, you would
likely have a more sophisticated method for generating unique primary key values, such as
using auto-incrementing integers or other mechanisms to ensure uniqueness.

 Explanation:
 Students Table:
 The Students table has four rows representing different students with their respective details.
 Each row corresponds to a student with a unique student_id.
 The student_id column is the primary key of the table, ensuring its uniqueness.
 Courses Table:
 The Courses table has five rows representing different courses with their respective details.
 Each row corresponds to a course with a unique course_id.
 The course_id column is the primary key of the table, ensuring its uniqueness.
 The student_id column is a foreign key that establishes a relationship with the Students table. It
references the student_id column in the Students table.
 Course with course_id 104 has no student enrolled (NULL value in the student_id column).
 With this data insertion, both tables are now populated, and the foreign key relationship
between the Students and Courses tables ensures that the student_id values in the Courses
table match valid student_id values from the Students table.

What are Check Constraints?

Check constraints are a feature in relational database management systems (RDBMS) that allow you
to specify conditions that data must meet when inserted or updated in a column.

o Check constraint is validation or a rule which is applied on the column of a table.

o When we apply check constraint to any column, it checks for specific values while inserting any
record.
The check constraints are the rule or set of rules that help to check the inserted (or updated) data
values to tables based on a certain condition.

The check constraint ensures that only valid data, adhering to the specified conditions, is allowed in
the column. It acts as a rule or condition that the data must satisfy, providing an additional layer of
data integrity.

Creating Check Constraints:

To create a check constraint, you include it as part of the column definition when creating a table.
Here's the basic syntax:

CREATE TABLE table_name ( column_name data_type [CONSTRAINT constraint_name] CHECK


(condition) );

table_name: The name of the table you're creating.

column_name: The name of the column you want to apply the check constraint to.

data_type: The data type of the column.

CONSTRAINT constraint_name (optional): Allows you to give a specific name to the constraint for
easier management. If omitted, the database system will generate a name for you.

CHECK (condition): The condition you want to enforce on the data in the column. It's an expression
that evaluates to true or false.

Examples of Check Constraints:

Let's look at a few examples to illustrate how check constraints work:

Example: Age Check Constraint

Suppose we want to create a table named Employees to store information about employees. We
want to enforce a check constraint that ensures the age of employees is between 18 and 60 years.

Step 1: Creating the Table with Check Constraint

sqlCopy code

CREATE TABLE Employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(50), age INT
CHECK (age BETWEEN 18 AND 60), position VARCHAR(50) );

Explanation:

In this SQL code, we create the Employees table with four columns: employee_id, employee_name,
age, and position.

The employee_id column is set as the primary key, uniquely identifying each employee.

The age column has a check constraint (CHECK (age BETWEEN 18 AND 60)) that ensures only ages
between 18 and 60 (inclusive) are allowed.
Step 2: Inserting Data into the Table

Now, let's insert some data into the Employees table:

sqlCopy code

INSERT INTO Employees (employee_id, employee_name, age, position) VALUES (1, 'John Smith', 28,
'Manager'), (2, 'Alice Johnson', 22, 'Assistant'), (3, 'Bob Brown', 61, 'Intern');

Explanation:

We use the INSERT INTO statement to add data to the Employees table.

In the VALUES clause, we provide multiple sets of values, each representing a row to be inserted into
the table.

The first two rows (employees 1 and 2) have valid ages within the specified range (18 to 60) and will
be inserted successfully.

However, the third row (employee 3) has an age of 61, which violates the check constraint. Since the
age is outside the allowed range, the insertion for this row will fail, and an error will be thrown.

Handling Check Constraint Violation

If you attempt to insert data that violates the check constraint, the database will prevent the
insertion and raise an error. For example, when inserting the data above, you might receive the
following error message:

sqlCopy code

Error Code: 3819. Check constraint 'employees_chk_1' is violated.

To avoid such errors, you need to ensure that the data you insert into the Employees table adheres
to the check constraint rules. In this example, ages must be between 18 and 60 to be inserted
successfully.

Check constraints play a crucial role in maintaining data integrity by preventing the insertion of
invalid or inappropriate data into your database tables. They allow you to enforce business rules and
data quality standards, contributing to a more reliable and accurate database.

Gender Constraint:

sqlCopy code

CREATE TABLE Students ( student_id INT PRIMARY KEY, student_name VARCHAR(50), gender
CHAR(1) CHECK (gender IN ('M', 'F')), course VARCHAR(50) );

In this example, the check constraint (gender IN ('M', 'F')) restricts the gender column to accept only
the values 'M' (male) or 'F' (female).

Email Format Constraint:


sqlCopy code

CREATE TABLE Contacts ( contact_id INT PRIMARY KEY, contact_name VARCHAR(50), email
VARCHAR(100) CHECK (email LIKE '%@%.%'), phone_number VARCHAR(20) );

In this example, the check constraint (email LIKE '%@%.%') ensures that the email column must
contain the "@" symbol and at least one dot ("."), indicating a valid email format.

---.

You might also like