Constraints in SQL Are Not Mandatory to Use While Creating the Table
Constraints in SQL Are Not Mandatory to Use While Creating the Table
………
);
………
Types of SQL Constraints:
There are mainly six different constraints that are used in SQL:
NOT NULL
Applied only on the column level
);
In the above example, the columns Student_ID and Roll_No of the Student table can’t have a
NULL value.
UNIQUE
This applies on both table and column level
);
In the above example, the columns Student_ID and Roll_No of the Student table don’t have any
duplicate values.
Note: Primary Keys are always unique, but the constraint columns may or may not be Primary
Keys.
DEFAULT
This applies on both table and column level
);
The above table contains three columns: Product ID, Product Name, and Country of Origin. In
the third column, if some entries are left out, then the entries are filled with India.
CHECK
This applies on both table and column level
);
PRIMARY KEY
This applies on both table and column level
The primary Key constraint is a combination of both UNIQUE and NOT NULL constraints.
It helps to retrieve query results from the table.
Only one PRIMARY KEY can be created per table
Example:
CREATE TABLE Employee
);
Two employees of the same name may be working in the same department, but every employee
must have an employee ID, which should always be unique. So, in the above table, the Employee
ID column is a unique identifier for a row.
FOREIGN KEY
This applies on both table and column level
It is used to relate two or more tables and prevents the operation that destroys the link between
the tables.
A foreign key can be a primary key if the table is connected by a one-to-one relationship, not
a one-to-many relationship.
Multiple foreign keys can be created per table
Example:
CREATE TABLE Order
);
Here, the value of Product ID in the order table must be a value from the ID column of a Product
table.
Importance of SQL Constraints
It is not mandatory to define the constraints but
It maintains the accuracy, reliability, and integrity of the data during the operations performed
on the table.
Helps to enforce the limit on the input so that operations performed after defining the
constraint can’t be aborted
Constraints in SQL are a set of rules or restrictions defined on columns of a table in a relational
database to control the data or data type that can be input or stored in a column. These rules or
restrictions ensure the accuracy and reliability of the input data. After the constraint is defined, if
any operation in the database violates the specified rule, the particular operation is aborted.
What are the different types of constraints in SQL?
Primary Key, Foreign Key, NOT NULL, UNIQUE, CHECK, DEFAULT, INDEX are the
different types of constraints in SQL.
How can you add a constraint to a SQL table?
Constraints can be added during the creation of a table using the CREATE TABLE statement or
after the table is created using the ALTER TABLE statement.
How do you remove a constraint from a SQL table?
Constraints can be removed from a SQL table using the ALTER TABLE command. However,
you need to know the name of the constraint.
What is a Primary Key Constraint?
A Primary Key constraint ensures that each row in a table has a unique identifier. It cannot
contain NULL values and is used to uniquely identify each record.
How does a Foreign Key Constraint work?
A Foreign Key constraint is used to create a link between the columns in two tables. It ensures
referential integrity by referencing a primary or unique key in another table.
What is the purpose of a Check Constraint?
A Check constraint is used to define a specific condition that each row must satisfy. For instance,
it can ensure that a column only contains values for adults (e.g., CHECK (Age>=18)).
How does the Default Constraint function?
The Default constraint sets a default value for a column when no value is specified. If a record is
inserted without a value for this column, the default value is automatically assigned.
Can I use a Unique Constraint on multiple columns?
Yes, you can apply the Unique constraint to multiple columns. This ensures that the combination
of values in these columns is unique across all rows in the table.
What happens if a constraint is violated during an INSERT or UPDATE operation?
If a constraint is violated, the SQL operation (INSERT or UPDATE) will fail, and the database
will return an error message. This ensures data integrity and adherence to the defined rules.
The SQL WHERE clause is an optional clause that can be used with a SELECT statement. Its
purpose is to filter out specific records from a dataset or table .Here, we will be exploring how to
use the WHERE clause with a set of examples.
WHERE conditions;
Now let’s have some examples to better understand the WHERE clause.
For example, we will use an Employee Dataset that contains Employee ID, Name, Gender,
Department, Education, Month of Joining, and Salary (CTC).
CT
Mon
Emp Ge C(i
Na Depar Educ th of
loye nd n
me tment ation Joini
e ID er La
ng
cs)
Aja Engin Docto Janu
1001 M 25
y eering ral ary
Ba
Engin Febr
1002 blo M UG 23
eering uary
o
Ch
Marc
1003 hav F HR PG 15
h
i
Dh
Janu
1004 eer M HR UG 12
ary
aj
Evi Marke Marc
1005 F UG 16
na ting h
Fre Dece
1006 M Sales UG 10
dy mber
Ga
Marc
1007 rim F Sales PG 10
h
a
Nov
Ha Admi
1008 M PG emb 8
ns n
er
Inter
Iva Admi
1009 F media April 7
nka n
te
Dece
1010 Jai M Peon 4
mber
FROM Employee
FROM Employee
FROM Employee
FROM Employee
FROM Employee
Employee CTC(in
Name Department
ID Lacs)
1001 Ajay Engineering 25
1002 Babloo Engineering 23
1003 Chhavi HR 15
1005 Evina Marketing 16
FROM Employee
WHERE CTC > AVG (CTC);
PatientsCheckup Table
Patient ID BP Weight ConsultationFees
01 121/80 67 300
02 142/76 78 400
03 151/75 55 300
04 160/81 61 550
05 143/67 78 700
Q1. Find the Nth highest consultation fees from the PatientsCheckup table with and
without using the TOP/LIMIT keywords.
The Nth highest consultation fees from the PatientsCheckup table with using the TOP keywords
SELECT TOP 1 ConsultationFees
FROM(
SELECT TOP N ConsultationFees
FROM PatientsCheckup
ORDER BY ConsultationFees DESC) AS FEES
ORDER BY ConsultationFees ASC;
The Nth highest consultation fees from the PatientsCheckup table using the LIMIT keywords.
SELECT ConsultationFees
FROM PatientsCheckup
ORDER BY ConsultationFees DESC LIMIT N-1,1;
Nth highest consultation fees from the PatientsCheckup table without using the TOP/LIMIT
keywords.
SELECT ConsultationFees
FROM PatientsCheckup F1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( F2.ConsultationFees ) )
FROM PatientsCheckup F2
WHERE F2.ConsultationFees > F1.ConsultationFees );
Q2. Write a SQL query to fetch the first and last record of the Patients table.
–FETCH FIRST RECORD
SELECT * FROM Patients WHERE PatientID = (SELECT MIN(PatientID) FROM
Patients);