0% found this document useful (0 votes)
4 views

Constraints in SQL Are Not Mandatory to Use While Creating the Table

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Constraints in SQL Are Not Mandatory to Use While Creating the Table

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Constraints in SQL are not mandatory to use while creating the table.

Still, they are very helpful


in maintaining the accuracy, reliability, and integrity of the data during the operations performed
on the table in a relational database. In this article, we will briefly discuss different SQL
constraints.

What are SQL Constraints?


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,
the particular operation is aborted if any operation in the database violates the specified rule.
In SQL, constraints are broadly divided into two types:
 Column Level Constraints: It refers to a single column in the table and does not specify
the column's name except the CHECK constraints.
 Table Level Constraints: It refers to one or more columns in the table and specify the
column name in which they apply.
Syntax
In SQL, constraints are applied during the creation of the table using the CREATE TABLE
command or after the creation of the table using the ALTER TABLE command.
Syntax-1:
CREATE TABLE table_name

column_name_1 data_type (size) constraint_name,

column_name_2 data_type (size) constraint_name,

column_name_3 data_type (size) constraint_name,

………

);

ALTER TABLE table_name

MODIFY column_name_1 data_type (size) constraint_name,

MODIFY column_name_2 data_type (size) constraint_name,

MODIFY column_name_3 data_type (size) constraint_name,

………
Types of SQL Constraints:
There are mainly six different constraints that are used in SQL:
NOT NULL
 Applied only on the column level

 By default, any column can have a NULL values


 It restricts the columns in a table from having NULL values
 Example:
CREATE TABLE Student

Student_ID INT NOT NULL,

Roll_No INT NOT NULL,

Name VARCHAR (100)

);

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

 It ensures that the column has only unique values


 Example
CREATE TABLE Student

Student_ID INT UNIQUE,

Roll_No INT UNIQUE,

Name VARCHAR (100)

);

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

 It provides a default value for a column if no value is assigned


Example:
CREATE TABLE Product

Product_ID VARCHAR (50) NOT NULL,

Product_Name VARCHAR (50) UNIQUE,

Country of Origin VARCHAR (70) DEFAULT ‘India’

);

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

 It is used to restrict the value of a column between a range


 It is similar to data validation in Excel
 Example
CREATE TABLE Student

Name VARCHAR(100) NOT NULL,

Age INT(2) CHECK (Age >= 21)

);

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

Employee ID INT PRIMARY KEY,

Employee Name VARCHAR (55),

Department VARCHAR (55) NOT NULL

);

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

Order ID INT PRIMARY KEY,

Product ID INT REFERENCES Products (ID)

);

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

What are constraints in SQL?

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.

How to Use WHERE Clause in SQL

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.

What is the Where Clause?


The WHERE clause filters out the records or specifies a condition while extracting the records
from a single table or joining multiple tables. It follows the SELECT and FROM clause.
The conditions in the WHERE clause must be evaluated to TRUE for a row to be returned as a
result.
Note:
 WHERE clause is an optional clause to use with the SELECT clause, i.e., a SELECT clause
can have an optional WHERE clause.
 WHERE clause is used with UPDATE, DELETE, or SELECT a particular data set.

SELECT column names

FROM table name

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

Example 1: Find the complete details of the employee named Fredy.


Query
SELECT *

FROM Employee

WHERE Name = ‘Fredy’;

Employee Gende Month of CTC(in


Name Department Education
ID r Joining Lacs)
1006 Fredy M Sales UG December 10
Example 2: Select all the Employee ID, Name, and Department who are female using the
employee table.
Query
SELECT Employee ID, Name, Department

FROM Employee

WHERE Gender = ‘F’;

Employee ID Name Department


1003 Chhavi HR
1005 Evina Marketing
1007 Garima Sales
1009 Ivanka Admin
WHERE with the LIKE operator
Example 3: Find the Details of all the employees where the department is ending with ing.
Query
SELECT *

FROM Employee

WHERE Department LIKE ‘%ing’;

Employee ID Name Gender Department Education CTC(in Lacs)


1001 Ajay M Engineering Doctoral 25
1002 Babloo M Engineering UG 23
1005 Evina F Marketing UG 16

WHERE clause with Multiple Conditions


Example 4: Find the records of the employees who are working in marketing and are
undergraduates.
Query
SELECT *

FROM Employee

WHERE department = ‘Marketing’ AND Education = ‘UG’;

Employee ID Name Gender Department Education CTC(in Lacs)


1005 Evina F Marketing UG 16

WHERE clause with Subquery


Example 5: Find the Employee ID, Name, department, and CTC where CTC is greater
than or equal to the average CTC.
Query
SELECT Employee ID, Name, Department, CTC

FROM Employee

WHERE CTC >= (SELECT AVG (CTC) 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

Operators in the WHERE clause


Here is the list of operators that can be used with the WHERE clause.
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or Equal
<= Less than or Equal
<> Not equal
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values in a particular column

Limitation of Where Clause


It can’t be used with an aggregate function directly. Because where clauses are evaluated row-
by-row, where an aggregate function works on multiple rows to return a single result.

Let’s take an example to check this:


Example 6: Without using the sub-query, find the employee ID, name, department, and
CTC where CTC is greater than AVG CTC.
Query

SELECT Employee ID, Name, Department, CTC

FROM Employee
WHERE CTC > AVG (CTC);

The above query will throw an Error.


Conclusion
The WHERE clause in SQL is a powerful tool that filters data in database queries. It specifies the
conditions for rows to be included in the result set. The syntax is simple yet versatile, allowing
for various conditions. We explored different types of operators like comparison, logical, and
range operators. The WHERE clause has limitations, like its inability to filter aggregated data.
Mastering the WHERE clause is vital for anyone working with SQL to retrieve required data
precisely and efficiently.
FAQs on How to Use WHERE Clause in SQL?
How do I use comparison operators in a WHERE clause?
You can use operators like =, !=, <, <=, >, >= to compare column values. For instance, SELECT
* FROM salespeople WHERE salary > 50000; fetches all salespeople with a salary greater than
50000.
Can I use the WHERE clause with string values?
Yes, comparison operators work with strings, but they are ordered and compared alphabetically.
Remember to use quotation marks around string literals in conditions.
What is the BETWEEN operator, and how do I use it?
The BETWEEN operator is used to filter the result set within a certain range. It is inclusive,
meaning it includes the boundary values. For example, SELECT * FROM table WHERE age
BETWEEN 25 AND 30; retrieves records where age is between 25 and 30, including both 25
and 30.
How can I combine multiple conditions in a WHERE clause?
Use the AND, OR operators to combine multiple conditions. For instance, SELECT * FROM
employees WHERE department = 'Sales' AND salary > 50000; gets all sales employees with
salaries above 50000.
Can I use the WHERE clause with the IN operator?
Yes, the IN operator allows you to specify a list of values to compare in the WHERE clause. For
example, SELECT * FROM employees WHERE department IN ('Sales', 'HR'); fetches
employees in either Sales or HR departments.
What is the EXISTS operator, and how is it used?
EXISTS is used to test for the existence of any record in a subquery. It’s useful for checking if
rows in a table match rows from another table based on certain criteria. For example, to check if
there are any sales in a specific region, you might use: SELECT * FROM sales WHERE
EXISTS (SELECT * FROM regions WHERE sales.region_id = regions.id);.
How do I handle NULL values in a WHERE clause?
Use IS NULL or IS NOT NULL to filter records with or without NULL values in a specific
column. For instance, SELECT * FROM employees WHERE commission IS NULL; retrieves
all employees who do not have a commission value.
Can the WHERE clause be used with Joins?
Yes, you can filter records based on conditions that involve multiple tables when using JOINs.
For instance, SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id
WHERE customers.country = 'USA'; retrieves orders from U.S. customers.
How do I use the LIKE operator in a WHERE clause?
LIKE is used for pattern matching in string columns. For example, SELECT * FROM products
WHERE name LIKE 'Apple%'; fetches products whose names start with "Apple".
Understanding Subqueries in SQL
Nested & Subqueries in SQL
Nested queries have outer queries and inner sub queries. Multiple subqueries can be nested
inside another query by using the SELECT, INSERT, UPDATE, and DELETE commands.
Nested queries are most commonly used when you have to retrieve specific data from multiple
tables, along with additional criteria.
Refer to the image below:
Note:
 Inner Query is executed first

 You can have any number of subqueries in the nested queries


 The performance of the query might be affected if nested way too much
 SELECT in subqueries can only retrieve a single column
 Use indentation while writing queries to make it easy for the users to understand
 You can use subqueries for calculations as well
Top Interview Questions on Nested Queries
In this article, I am going to consider the following tables to explain to you the most asked
interview questions.
Patients Table
Patien Patient Se Ag Postal Countr DoctorI
Address State RegDate
t ID Name x e Code y D
Flat no
201, Vasavi 50002 03/03/202
01 Sheela F 23 Telangana India 142
Heights, 3 0
Yakutapura
02 Rehan M 21 Building no 56006 Karnataka India 13/11/202 211
2, 3 0
Yelahanka
H No 1, 13214 12/12/202
03 Anay M 56 Haryana India 142
Panipat 0 1
House no
Mahir 12, 38242 28/01/202
04 F 42 Gujarat India 345
a Gandhinag 1 2
ar
Sunflower
Nishan 40008 Maharashtr 05/01/202
05 M 12 Heights, India 131
t 0 a 2
Thane

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);

–FETCH LAST RECORD


SELECT * FROM Patients WHERE PatientID = (SELECT MAX(PatientID) FROM
Patients);
Q3. Write a query to find those patients who have paid consultation fees between 200 to
300.
SELECT * FROM Patients WHERE PatientID IN
(SELECT PatientID FROM PatientsCheckup WHERE Salary BETWEEN '200' AND '300');
Q4. Write a SQL query to retrieve the last 4 records from the Patients table.
SELECT * FROM Patients WHERE
PatientID <=4 UNION SELECT * FROM
(SELECT * FROM Patients P ORDER BY P.PatientID DESC)
AS P1 WHERE P1.PatientID <=4;

Q5. Write a query to fetch PatientIDs:


a. Which are present in both tables
b. Which are present in one of the table. Let us say, patients present in Patients and not in
the PatientsCheckup table.
–Present IN BOTH TABLES
SELECT PatientId FROM Patients
WHERE PatientId IN
(SELECT PatientId FROM PatientsCheckup);

– Present IN one OF the TABLE


SELECT PatientId FROM Patients
WHERE PatientId NOT IN
(SELECT PatientId FROM PatientsCheckup);
Q6. Write a query to fetch even and odd rows from a table by diving by 2.
Fetch even rows in SQL Server
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER(ORDER BY PatientId) AS RowNumber
FROM Patients
)P
WHERE P.RowNumber % 2 = 0;
Fetch even rows in MySQL
SELECT * FROM (
SELECT *, @rowNumber := @rowNumber+ 1 rn
FROM Patients
JOIN (SELECT @rowNumber:= 0) r
)p
WHERE rn % 2 = 0;
In case you wish to find the odd rows, then the remainder when divided by 2 should be 1
Fetch odd rows in SQL Server
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER(ORDER BY PatientId) AS RowNumber
FROM Patients
)P
WHERE P.RowNumber % 2 = 1;
Fetch odd rows in MySQL
SELECT * FROM (
SELECT *, @rowNumber := @rowNumber+ 1 rn
FROM Patients
JOIN (SELECT @rowNumber:= 0) r
)p
WHERE rn % 2 = 1;
Q7. Write a SQL query to fetch 50% records from the PatientsCheckup table.
SELECT *
FROM PatientsCheckup WHERE
PatientID <= (SELECT COUNT(PatientD)/2 FROM PatientsCheckup);
Q8. Write a query to retrieve two minimum and maximum consultation fees from the
PatientsCheckup Table.
– TWO MINIMUM ConsultationFees
SELECT DISTINCT ConsultationFees FROM PatientsCheckup P1
WHERE 2 >= (SELECT COUNT(DISTINCT ConsultationFees)FROM PatientsCheckup P2
WHERE P1.ConsultationFees >= P2.ConsultationFees) ORDER BY P1.ConsultationFees
DESC;

– TWO MAXIMUM ConsultationFees


SELECT DISTINCT ConsultationFees FROM PatientsCheckup P1
WHERE 2 >= (SELECT COUNT(DISTINCT ConsultationFees)FROM PatientsCheckup P2
WHERE P1.ConsultationFees <= P2.ConsultationFees) ORDER BY P1.ConsultationFees
DESC;
Q9. Write a query to remove duplicate rows in SQL.
DELETE FROM Patients WHERE PatientID IN (
SELECT
ID, COUNT(PatientID)
FROM Patients
GROUP BY PatientID
HAVING
COUNT (PatientID) > 1);
Q10. Write a SQL query to retrieve patient details from Patients table who have a weight
in the PatientsCheckup table.
SELECT * FROM Patients P
WHERE EXISTS
(SELECT * FROM PatientsCheckup C WHERE P.PatientID = C.PatientID);
With this, we end this article on the subqueries in SQL. We hope you found it informative.

You might also like