0% found this document useful (0 votes)
2 views79 pages

SQL NOTES

Uploaded by

Yamini
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)
2 views79 pages

SQL NOTES

Uploaded by

Yamini
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/ 79

SQL NOTES

 SQL stands for Structured Query Language.


 It is used to access and manipulate data in relational databases.

A relational database stores data in tables, which look like spreadsheets:

 Rows = Records
 Columns = Fields/Attributes

 We can create, update, delete, and retrieve data in databases like MySQL, Oracle,
PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.
 SQL is a standard language for storing, manipulating and retrieving data in databases.
 SQL enables users to perform a variety of tasks such as querying data, creating and
modifying database structures, and managing access permissions.
 SQL became a standard of the American National Standards Institute (ANSI) in
1986, and of the International Organization for Standardization (ISO) in 1987

 SQL was invented in 1970s and was first commercially distributed by Oracle.
 The original name was given by IBM as Structured English Query Language,
abbreviated by the acronym SEQUEL.

 Although SQL is an ANSI/ISO standard, there are different versions of the SQL
language.

 However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
 Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!

WHAT SQL CAN DO?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
 SQL can create stored procedures in a database
 What is a Stored Procedure?
 A stored procedure is a precompiled set of SQL statements that you can store in the database
and reuse. It acts like a function: you call it when needed, and it performs the defined actions.

 In MySQL, example:

DELIMITER //

CREATE PROCEDURE GetEmployeeById(IN emp_id INT)


BEGIN
SELECT * FROM Employees WHERE EmployeeID = emp_id;
END //

DELIMITER ;

 IN emp_id INT: This is an input parameter.


 The procedure selects employee data based on the given ID.

You can then call it using:

sql
CopyEdit
CALL GetEmployeeById(101);

What SQL can do?


 When you interact with a database, you typically use SQL commands
to perform these operations.
 These commands are translated into actions by the SQL Engine, the
core component responsible for processing queries. The SQL Engine
parses and compiles SQL queries, optimizing and executing them to
interact with the stored data. The SQL Engine also ensures that data
retrieval and modifications are efficient and consistent.
 Different Databases will have different SQL

Keep in mind that?


 SQL keywords are NOT case sensitive: select is the same as SELECT

 Some database systems require a semicolon at the end of each SQL statement.
 Semicolon is the standard way to separate each SQL statement in database
systems that allow more than one SQL statement to be executed in the same call to
the server.

Rules for Writing SQL Queries

There are certain rules for SQL which would ensure consistency and functionality across
databases. By following these rules, queries will be well formed and well executed in any
database.
 Statement Termination: Every SQL statement ends with a semicolon (;),
signaling the DBMS to execute the command.

 Case Insensitivity: SQL keywords (e.g., SELECT, INSERT) are case-insensitive, but
database names and column names may be case-sensitive depending on the
DBMS.

 Whitespace Flexibility: SQL statements can span multiple lines, but keywords
and identifiers must be separated by at least one space.

 Unique Identifiers: Reserved words (e.g., SELECT, FROM) cannot be used as table
or column names unless enclosed in double quotes (“) or backticks (`), depending
on the DBMS.

• Unique Identifiers: Reserved words (e.g., SELECT, FROM) cannot be used as table or column names
unless enclosed in double quotes (“) or backticks (), depending on the DBMS. this means we can
use them as table names if enclosed in double queotes

ChatGPT said:

Yes, that's correct — reserved words in SQL (like SELECT, FROM, WHERE, etc.) can be used as table or
column names if you enclose them properly, depending on the database system you're using.

Here’s how it works by DBMS:

DBMS Delimiter for identifiers Example using reserved word SELECT as a table name
PostgreSQL Double quotes (") SELECT * FROM "SELECT";
MySQL Backticks (`) SELECT * FROM `SELECT`;
SQL Server Square brackets ([]) SELECT * FROM [SELECT];
Oracle Double quotes (") SELECT * FROM "SELECT";

Important Notes:

 Using reserved words as identifiers (even when quoted) is not recommended for clarity and to avoid
confusion or future issues.
 When using quotes/backticks, case sensitivity may also come into play (especially in PostgreSQL
and Oracle).

Example in PostgreSQL:
sql
CopyEdit
CREATE TABLE "SELECT" (
"FROM" INT,
"WHERE" TEXT
);

SELECT "FROM", "WHERE" FROM "SELECT";


Use -- (two hyphens followed by a space) for maximum compatibility across databases.

 Comments: Comments enhance readability:

o Single-line comments: --
o Multi-line comments: /* … */

 Data Integrity: Constraints like NOT NULL, UNIQUE, and PRIMARY KEY must be
defined correctly to maintain data consistency.

 String Literals: String values must be enclosed in single quotes (‘).

 Valid Identifiers: Table and column names must:

o Begin with an alphabetic character.

o Contain up to 30 characters.

o Avoid special characters except underscores (_).

What are SQL Commands?


 SQL commands are standardized instructions used by developers to interact with
data stored in relational databases.
 SQL commands are instructions you give to a database to perform specific tasks
like retrieving data, inserting new data, updating existing data, or even managing
database structures.
 These commands allow for the creation, manipulation, retrieval, and control of
data, as well as database structures.
 SQL commands are categorized based on their specific functionalities:
1. DDL (Data Definition Language):
 It Define Structure
 Used to create, change, or delete database objects like tables.
1)Create:
It is used to create new objects in a database like:

 Databases
 Tables
 Views
 Indexes
 Stored Procedures
 Functions
 Triggers

i)To create new databases:


>>> CREATE DATABASE SchoolDB;
ii)To create table:
>>> CREATE TABLE table_name (
column1 datatype [constraints],
column2 datatype [constraints],
...
);
iii)to create a view:
>>> CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
iv)to create indexes:
>>> CREATE [UNIQUE] INDEX index_name
ON table_name (column1 [, column2, ...]);
v)to create Stored Process:
>>> CREATE PROCEDURE procedure_name
@parameter1 datatype,
@parameter2 datatype
AS
BEGIN
-- SQL statements
END;
vi)to create functions:
>>> CREATE FUNCTION CalculateSquare (@Number INT)
RETURNS INT
AS
BEGIN
RETURN @Number * @Number;
END;
Usage:
SELECT dbo.CalculateSquare(5) AS SquareResult;
vii)to create triggers:
>>>CREATE TRIGGER trigger_name
ON table_name
AFTER | INSTEAD OF [INSERT, UPDATE, DELETE]
AS
BEGIN
-- SQL statements
END;

 ALTER → Changes the structure of an existing table.

ALTER TABLE Students ADD Email VARCHAR(255);

 DROP → Deletes an entire table or database

DROP TABLE Students;

 TRUNCATE → Deletes all records inside a table but keeps the structure

TRUNCATE TABLE Students;

Add comments to the data COMMENT 'comment_text' ON TABLE


COMMENT
dictionary table_name;

RENAME Rename an object existing RENAME TABLE old_table_name TO


in the database new_table_name;

2. DML (Data Manipulation Language)


These commands manipulate data inside the tables.

 INSERT → Adds new data.

INSERT INTO Students (StudentID, Name, Age) VALUES (1, 'John Doe', 22);

 UPDATE → Changes existing data.

UPDATE Students SET Age = 23 WHERE StudentID = 1;

 DELETE → Removes data

DELETE FROM Students WHERE StudentID = 1;

LOCK Table control concurrency LOCK TABLE table_name IN lock_mode;

Call a PL/SQL or JAVA


CALL CALL procedure_name(arguments);
subprogram

EXPLAIN Describe the access path to EXPLAIN PLAN FOR SELECT * FROM
PLAN data table_name;

3. DCL (Data Control Language)


These commands handle permissions and access to the database.

 GRANT → Gives a user permission.

GRANT SELECT, INSERT ON Students TO user123;

 REVOKE → Takes away permission

REVOKE INSERT ON Students FROM user123;

4. TCL (Transaction Control Language)


These commands handle transactions, like a group of operations you want to treat as one unit.

 COMMIT → Saves all changes permanently.

COMMIT;

 ROLLBACK → Cancels changes if something goes wrong.


ROLLBACK;

 SAVEPOINT → Creates a point you can roll back to.

SAVEPOINT Savepoint1;

BEGIN TRANSACTION Starts a new transaction BEGIN TRANSACTION [transaction_name];

5. DQL (Data Query Language)


Focused only on fetching data.

 SELECT → Gets data from tables.

SELECT * FROM Students;

Quick Summary Diagram:


SQL COMMANDS
├── DDL (CREATE, ALTER, DROP, TRUNCATE)
├── DML (INSERT, UPDATE, DELETE)
├── DCL (GRANT, REVOKE)
├── TCL (COMMIT, ROLLBACK, SAVEPOINT)
└── DQL (SELECT)

SQL Data Types


 SQL Data Types are very important in relational databases.
 It ensures that data is stored efficiently and accurately.
 Data types define the type of value a column can hold,
such as numbers, text, or dates.

1. Numeric Data Types

Data Type Description Range

-9,223,372,036,854,775,808 to
BIGINT Large integer numbers
9,223,372,036,854,775,807

INT Standard integer values -2,147,483,648 to 2,147,483,647

SMALLINT Small integers -32,768 to 32,767

TINYINT Very small integers 0 to 255


Data Type Description Range

Exact fixed-point numbers


DECIMAL(p,
(e.g., for financial values) -10^38 + 1 to 10^38 – 1
s)
pression and scale

Similar to DECIMAL, used


NUMERIC(s,
for precision data pression -10^38 + 1 to 10^38 – 1
p)
and scale

For storing monetary -922,337,203,685,477.5808 to


MONEY
values 922,337,203,685,477.5807

SMALLMON
Smaller monetary values -214,748.3648 to 214,748.3647
EY

What Are Precision and Scale?


 Precision: The total number of digits that can be stored,
both to the left and right of the decimal point.
 Scale: The number of digits that can be stored to the
right of the decimal point.
For example, in DECIMAL(5,2):
 Precision is 5, so the number can have up to 5 digits in
total.
 Scale is 2, so up to 2 digits can be after the decimal
point.

2.Approximate Numeric Types


Data
Type Description Range

-1.79E+308 to
FLOAT Approximate numeric values
1.79E+308

Similar to FLOAT, but with less -3.40E+38 to


REAL
precision 3.40E+38

 DOUBLE PRECISION: Stores double-precision floating-point numbers.


3.Character and String Data Types
Used to store text data:

 CHAR(n): Fixed-length string of n characters.


 VARCHAR(n): Variable-length string with a maximum of n characters.
 TEXT: Stores large text data.

4.Date and Time Data Types


Used to store temporal data:

 DATE: Stores date values (e.g., '2025-05-01').


 TIME: Stores time values (e.g., '11:12:49').
 DATETIME: Stores date and time values.
 TIMESTAMP: Stores a timestamp value.

5.Binary Data Types


Used to store binary data such as images or files:

 BINARY(n): Fixed-length binary data.


 VARBINARY(n): Variable-length binary data.
 BLOB: Binary Large Object, stores large binary data.

6.Boolean Data Type


 BOOLEAN: Stores TRUE or FALSE values.

7.Other Data Types


 ENUM: Stores a predefined set of values.
 SET: Stores zero or more values from a predefined set.

NOTE: Operators in SQL is same as programming languages

SQL Data Bases


1)Create Data Base
The CREATE DATABASE statement is used to create a new SQL database.
>>>>>CREATE DATABASE databasename;
How to Verify if Your Database Was Created

>>> SHOW DATABASES;

Switching to Your New Database (USE Command)

>>> USE database_name

Deleting a Database

DROP DATABASE database_name;

SQL DROP DATABASE IF EXISTS

DROP DATABASE IF EXISTS Database_Name;

To change the name of a database in SQL, use the syntax:

ALTER DATABASE [current_database_name]


MODIFY NAME = [new_database_name];

To rename a database in MySQL use the query:

RENAME DATABASE [current_database_name] TO [new_database_name];

The SQL BACKUP DATABASE Statement


The BACKUP DATABASE statement is used in SQL Server to create a full back up of an
existing SQL database
>>> BACKUP DATABASE databasename
TO DISK = 'filepath';

The SQL BACKUP WITH DIFFERENTIAL


Statement
A differential back up only backs up the parts of the database that have changed since
the last full database backup.

Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;

BACKUP DATABASE Example


The following SQL statement creates a full back up of the existing database "testDB" to
the D disk:

Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Tip: Always back up the database to a different drive than the actual database. Then, if
you get a disk crash, you will not lose your backup file along with the database.

BACKUP WITH DIFFERENTIAL Example


The following SQL statement creates a differential back up of the database "testDB":

Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are backed
up).

Importance of Creating Backup Tables in SQL


Backup tables are essential during complex data changes or migrations
because they let us safely restore the original data if something goes
wrong. Here are the key reasons why creating them is essential:
 Data Integrity: Protecting the original dataset from accidental loss
or corruption.
 Disaster Recovery: Ensuring that the data can be restored in case
of failure or errors during modifications.
 Safe Experimentation: Making changes to data without affecting
the live dataset.
 Data Migration: Moving data from one system or table to another
without losing original records.
How to Create Backup Tables in SQL
We can create a backup of a table by creating a duplicate or copy of
original database. This is particularly useful for preserving the original
table before performing updates, deletions, or other modifications.
Below is a detailed explanation of the syntax and terms used for this
operation.
Syntax
CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name;
Key Terms
 Table_Name: Specifies the name of the new backup table.
 AS: Acts as an alias, enabling the SQL query to copy data from the
source table into the backup table.

Examples of SQL Backup Table Creation


Creating backup tables in SQL can involve duplicating all data, copying
specific columns, or even creating an empty table with the same
structure. Let's look at some examples on how to copy/duplicate table in
SQL to create a backup table in different scenarios:
1. Backup Table with All Columns and Data
In this example, we will create a backup table "stud_1" of
"student_information" table by creating a copy of
"student_information" table that duplicates all columns and their data..
Query:
CREATE TABLE stud_1 AS SELECT * FROM student_information;
SELECT * FROM stud_1;

Output

2. SQL Backup Table with Specific Column Data Example


In this example, we create a backup table, "stud_2", by copying only
selected columns from the "student_information" table using
a SELECT statement.
Query:
CREATE TABLE stud_2 AS
SELECT id,student_name FROM student_information;
SELECT * FROM stud_2;
Output

Till now we have seen how to create a clone of the source table. In the
above backup table, the data is also copied along with the table.
However, we can also create a backup table without copying the data.
3. Backup Table Without Data
So, to create a table without any data being copied we can use
the WHERE clause which needs to return a FALSE value. For example, we
can use WHERE 2<2 or WHERE 1=2.
In this example, we will create a backup table "geeks_student" of
"student_information" table by creating a copy of
"student_information" table and copying its all columns without data.
Query:
CREATE TABLE geeks_student AS SELECT * FROM student_information
WHERE 1!=1;
SELECT * FROM geeks_student;

Output
4. Backup Table with Specific Columns and No Data
In this example, we will create a backup table "geek_student" of
"student_information" table by creating a copy of
"student_information" table and copying specific columns without
data.
Query:
CREATE TABLE specific_empty_backup AS
SELECT ID, Student_Name FROM student_information WHERE 1=2;
SELECT * FROM specific_empty_backup;

Output

Limitations of CREATE TABLE AS SELECT


While convenient, CREATE TABLE AS SELECT has key limitations:
 Constraints Are Not Copied: Constraints such as PRIMARY
KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT are not carried
over to the new table.
 Indexes and Triggers Are Not
Copied: Any indexes or triggers from the base table won't transfer
to the backup
 Manual Effort Required for Full Duplication: To fully replicate
the original table structure including constraints and indexes,
manual setup is necessary.
How to Create Backup Tables with Constraints
To copy the structure of a table along with its constraints, the CREATE
TABLE AS SELECT statement is not sufficient. Instead, we need to define
the table structure manually and then copy the data.
Example: Adding Constraints After Table Creation
1. Create a table without constraints:
CREATE TABLE student_backup AS SELECT * FROM student_information;
2. Add constraints to the backup table
ALTER TABLE student_backup ADD PRIMARY KEY (ID);
Example: Define Table with Constraints and Copy Data
1. Define the new table with constraints
CREATE TABLE student_backup (
ID INT PRIMARY KEY,
Age INT,
Student_Name VARCHAR(50),
Sex VARCHAR(10)
);
2. Copy data into the new table
INSERT INTO student_backup SELECT * FROM student_information;

SQL Tables
 In SQL, a table is a fundamental structure used to store data within a relational database. It organizes
information into rows and columns, facilitating efficient data management and retrieval
 The CREATE TABLE command in SQL is used to define a new table
within a database.
 A table’s structure, including column names, data types, and
constraints like NOT NULL, PRIMARY KEY, and CHECK, are defined
when it is created in SQL.
Syntax:
CREATE table table_name
(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);
Key Terms
 table_name: The name you assign to the new table.
 column1, column2, … : The names of the columns in the table.
 datatype(size): Defines the data type and size of each column.

Create Table Using Another Table


 A copy of an existing table can also be created using CREATE TABLE.
 The new table gets the same column definitions. All columns or specific columns
can be selected.
 If you create a new table using an existing table, the new table will be filled with
the existing values from the old table.
 Syntax
 CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

Constraints in SQL
In SQL, constraints are rules applied to table columns to enforce data integrity and ensure the accuracy and
reliability of the data within the database. They define the limitations on the type of data that can be stored
in a table, preventing invalid data entry and maintaining consistency across related tables.

🔒 Types of SQL Constraints

1. NOT NULL

Ensures that a column cannot have a NULL value. This constraint is used when a column must always
contain a value.

CREATE TABLE Employees (


EmployeeID INT NOT NULL,
Name VARCHAR(100) NOT NULL
);

2. UNIQUE

Ensures that all values in a column are distinct. This constraint prevents duplicate values in a column.

CREATE TABLE Employees (


Email VARCHAR(100) UNIQUE
);

3. PRIMARY KEY

Combines the NOT NULL and UNIQUE constraints. It uniquely identifies each record in a table. A table
can have only one primary key, which may consist of single or multiple columns (composite key).

sql
CopyEdit
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY
);

4. FOREIGN KEY

Establishes a relationship between two tables by linking a column in one table to the primary key of another
table. This constraint ensures referential integrity.

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
EmployeeID INT,
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID)
);
5. CHECK

Ensures that all values in a column satisfy a specific condition. This constraint is used to limit the range of
values that can be placed in a column.

CREATE TABLE Employees (


Age INT CHECK (Age >= 18)
);

6. DEFAULT

Sets a default value for a column when no value is specified. This constraint is used to insert a default value
into a column if no value is specified during the insertion of a record.

CREATE TABLE Employees (


Country VARCHAR(50) DEFAULT 'India'
);

Modifying Constraints

 Adding a Constraint:

ALTER TABLE Employees


ADD CONSTRAINT chk_Age CHECK (Age >= 18);

 Dropping a Constraint:

ALTER TABLE Employees


DROP CONSTRAINT chk_Age;
Important Points About SQL CREATE TABLE
Statement
To ensure the smooth creation and management of your tables, keep these
points in mind:
1. Adding Constraints: The CREATE TABLE statement can also define
constraints like NOT NULL, UNIQUE, and DEFAULT. Example: Age INT NOT
NULL
2. Handling Table Existence: If you attempt to create a table that
already exists, SQL will throw an error. To avoid this, you can use the IF NOT
EXISTS clause.
CREATE TABLE IF NOT EXISTS Customer (...);
3. Data Types and Sizes: Always define appropriate data types for each
column (e.g., VARCHAR(50) for names and INT for IDs) to optimize
performance and storage.
4. Viewing Table Structure: After creating a table, use the following
command to view the structure of your table:
DESC table_name;
5. Modifying Table Structure: If you need to change the table’s
structure after creation (e.g., renaming a column, adding a new column),
use the ALTER TABLE statement.

SQL DROP TABLE


DROP TABLE table_name;

Important Points About SQL DROP TABLE


1. The SQL DROP TABLE statement is used to delete tables in a database,
along with all associated data, indexes, triggers, constraints and
permission specifications.
2. The table will be permanently disable, so use this query with caution.
3. Use DROP TABLE IF EXISTS query to prevent errors when dropping a
table that does not exist. This command ensures that the drop operation
only occurs if the table exists in the database.
DROP TABLE IF EXISTS categories;
4. When dropping a partitioned table, the DROP TABLE
statement removes the table definition, all partitions, all data stored in
those partitions, and all partition definitions. This operation also removes
the partitioning scheme if no other tables use it.
5. The DROP TABLE statement can be used to drop temporary tables by
including the TEMPORARY keyword.
DROP TEMPORARY TABLE temp_table_name;
6. To verify if a table is dropped, you can use the SHOW TABLES (MySQL)
or SELECT * FROM INFORMATION_SCHEMA.TABLES (SQL Server,
PostgreSQL) commands. Alternatively, in some systems,
the DESC or DESCRIBE command can be used to check the table
structure, but it will return an error if the table no longer exists.
SHOW TABLES;
What is Temporary Table in SQL?
A temporary table in SQL is an important tool for maintaining intermediate
results during query execution.

Temporary tables are automatically deleted when the session or


transaction that created them ends, making them perfect for temporary or
intermediate data storage. They are particularly useful in situations where
you need to perform calculations or data transformations without
changing the permanent database structure.

Syntax:
To Create a Temporary Table
CREATE TABLE #EmpDetails (id INT, name VARCHAR(25))
To Insert Values Into Temporary Table
INSERT INTO #EmpDetails VALUES (01, 'Lalit'), (02, 'Atharva')
To Select Values from the Temporary Table
SELECT * FROM #EmpDetails
Types of Temporary Tables in SQL
There are 2 types of Temporary Tables: Local Temporary Table, and Global
Temporary Table.
1)Local Temporary Table
A Local Temp Table is available only for the session that has created it. It is
automatically dropped (deleted) when the connection that has created it, is
closed. To create Local Temporary Table Single "#" is used as the prefix of
a table name. Also, the user can drop this temporary table by using
the "DROP TABLE #EmpDetails" query. There will be Random Numbers
are appended to the Name of Table Name. If the Temporary Table is
created inside the stored procedure, it get dropped automatically upon the
completion of stored procedure execution.
Example:
CREATE PROCEDURE ProcTemp
AS
BEGIN
CREATE TABLE #EmpDetails
INSERT INTO #EmpDetails VALUES ( 01, 'Lalit'), ( 02, 'Atharva')
SELECT * FROM #EmpDetails
END
EXECUTE ProcTemp
2)Global Temporary Table:
To create a Global Temporary Table, add the "##" symbol before the table
name.
Example:
CREATE TABLE ##EmpDetails (id INT, name VARCHAR(25))
Global Temporary Tables are visible to all connections and Dropped when
the last connection referencing the table is closed. Global Table Name must
have an Unique Table Name. There will be no random Numbers suffixed at
the end of the Table Name.
Differences Between Local and Global Temporary
Tables
Local Temporary
Feature Table Global Temporary Table

Prefix # (Single hash) ## (Double hash)

Only the session that


Scope Available to all sessions
created it

Automatically dropped Dropped when the last connection


Lifetime
when the session ends referencing the table ends

Accessibil Only the creating session


All sessions can access it
ity can access it

Session-specific data Shared temporary data storage for


Usage
storage multiple sessions
SQL DELETE Statement
The SQL DELETE statement removes one or more rows from a database
table based on a condition specified in the WHERE clause. It's a DML (Data
Manipulation Language) operation

Syntax:
DELETE FROM table_name
WHERE some_condition;
Parameter Explanation
 Some_condition: A condition used to filter the rows you want to
delete.
 table_name: The name of the table from which you want to delete
the rows
Note: We can delete single as well as multiple records depending on the
condition we provide in the WHERE clause. If we omit the WHERE clause
then all of the records will be deleted and the table will be empty.
ALTER Command in SQL?
The ALTER TABLE command in SQL allows us to modify the structure of an
existing table.
Here are some common tasks you can achieve using the ALTER command:
 Renaming a table.
 Changing a column name.
 Adding or deleting columns.
 Modifying the data type of a column.
Syntax for ALTER Command
1. Renaming a Table
ALTER TABLE table_name
RENAME TO new_table_name;
2. Renaming a Column
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
3. Adding a New Column
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE table_name
DROP COLUMN column_name;
4. Modifying a Column Data Type
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;

DROP and TRUNCATE in SQL


The DROP and TRUNCATE commands in SQL are used to remove data
from a table, but they work differently.
What is the SQL DROP Command?
In SQL, the DROP command is used to permanently remove an object
from a database, such as a table, database, index, or view. When we
DROP a table, both the data and the structure of the object are
permanently removed from the database leaving no trace of the object.
Syntax:
DROP object object_name ;
Key Terms
 object: The type of object you want to drop (e.g., TABLE,
DATABASE).
 object_name: The name of the object to be deleted.
DROP Command Examples
Let's look at some examples of the DROP statement in SQL.
1. DROP Table
To delete an entire table, including its data and structure:
Syntax:
DROP TABLE table_name;
2. DROP database
To delete an entire database and all of its associated tables:
Syntax:
DROP DATABASE database_name;

What is SQL TRUNCATE Command?


The TRUNCATE command is a Data Definition Language (DDL) action
that removes all rows from a table but preserves the structure of the table
for future use. Although TRUNCATE is similar to the DELETE command
(without the WHERE clause), it is much faster because it bypasses certain
integrity constraints and locks. It was officially introduced in the SQL:2008
standard.
Syntax:
TRUNCATE TABLE table_name;
Key Terms
 table_name: Name of the table to be truncated.
 DATABASE name: student_data

SQL SELECT
SQL select command to retrieve data from a database.

With the select command in SQL, users can access data and retrieve
specific records based on various conditions, making it an essential tool for
managing and analyzing data.

Syntax:
SELECT column1,column2.... FROM table_name ;
Example 1: Select Specific Columns
In this example, we will fetch only CustomerName, LastName from the
table Customer:
Query:
SELECT CustomerName, LastName
FROM Customer;
Example 2: Select All Columns
In this example, we will fetch all the fields from the table Customer:
Query:
SELECT * FROM Customer;
Example 3: SELECT Statement with WHERE Clause
Suppose we want to see table values with specific conditions then WHERE
Clause is used with select statement. In this example, filter customers who
are 21 years old.
Query:
SELECT CustomerName
FROM Customer
where Age = '21';
Example 4: SELECT with GROUP BY Clause
In this example, we will use SELECT statement with GROUP BY Clause to
Group rows and perform aggregation. Here, Count orders per customer.
Query:
SELECT Customer_id, COUNT(*) AS order_count
FROM Orders
GROUP BY Customer_id;
Example 5: SELECT Statement with HAVING Clause
Use HAVING to filter results after grouping. Consider the following
database for fetching departments with total salary above 50,000.
Use WHERE for row-level filtering, HAVING for group-level filtering.

Query:
SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Example 6: SELECT Statement with ORDER BY clause in SQL
In this example, we will use SELECT Statement with ORDER BY clause.
Here, Sort results by Age in descending order.
Query:
SELECT * FROM Customer ORDER BY Age DESC;
Tips to Master SELECT
Goal Technique

Fetch unique SELECT DISTINCT column FROM table;


values

Limit result rows SELECT * FROM table LIMIT 10; (MySQL/PostgreSQL)

Aliases for clarity SELECT CustomerName AS Name FROM Customer;

SELECT a.*, b.* FROM TableA a JOIN TableB b ON a.id =


Join tables b.id;

SQL TOP, LIMIT, FETCH FIRST Clause


SQL TOP, LIMIT, FETCH FIRST Clause
When working with large data sets in SQL, limiting the number of rows
returned by a query can improve performance and make the data more
manageable. The SQL SELECT TOP, LIMIT, and FETCH FIRST statements
accomplish this purpose by limiting the result set to a specified number of
row groups.
 SQL TOP Clause is used in SQL Server and Sybase to limit the
number of records returned.
 SQL LIMIT Clause is utilized in MySQL, PostgreSQL, and SQLite.
 SQL FETCH FIRST Clause is part of the SQL standard and is
supported by Oracle, DB2, PostgreSQL, and SQL Server (as part
of OFFSET-FETCH).
Depending on the database management system (DBMS) being used, you
can utilize the respective clause to efficiently manage data retrieval.
SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records. Returning a
large number of records can impact performance.

Note: Not all database systems support the SELECT TOP clause. MySQL supports
the LIMIT clause to select a limited number of records, while Oracle uses FETCH
FIRST n ROWS ONLY and ROWNUM.

Syntax:
SELECT column1, column2, ... TOP count
FROM table_name
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];
Here,
 column1, column2 = names of columns
 count = number of records to be fetched
 WHERE conditions: Optional. Filters the data based on conditions.
 ORDER BY expression: Optional. Sorts the result set in ascending
or descending order.

Example 1: Using SELECT TOP Clause in SQL


Query:
 SELECT TOP 4*
 FROM Employee;
Example 2: SQL SELECT TOP with ORDER BY Clause
Query
 SELECT TOP 4*
 FROM Employee
 ORDER BY Salary DESC;
Example 3: SQL SELECT TOP Clause with WHERE Clause
Example
Query:
 SELECT TOP 2*
 FROM Employee
 WHERE Salary>2000
 ORDER BY Salary;
Example 4: SQL SELECT TOP PERCENT Clause Example
 The PERCENT keyword is utilized to select the primary and percent of
all-out rows. For example,
Query:
 SELECT TOP 50 PERCENT*
 FROM Employee;
 Here, the above query will select the first 50% of employee records
out of the total number of records(i.e., the first 3 rows will be
returned).
Example 5: SQL TOP PERCENT with WHERE Clause Example
 We can also include some situations using the TOP PERCENT with the
WHERE clause in the above query.
 Query:
 SELECT TOP 50 PERCENT*
 FROM Employee
 WHERE Salary<50000;
The above query will select the Top 50% of the records out of the total
number of records from the table according to the given condition such that
it returns only the Top 50% of the records with the employee whose salary
is less than 5000 (i.e, 2 rows will be returned)
SQL LIMIT Clause
SQL LIMIT Clause limits the number of results returned in the results set.
The LIMIT Clause is utilized with the accompanying database systems:
 MySQL
 PostgreSQL
 SQLite
Example 1: SELECT LIMIT Clause in SQL
 SELECT * FROM Employee
 WHERE Salary = 45000
 LIMIT 2;
 From the above query, the LIMIT operator limits the number of records
to be returned. Here, it returns the first 2 rows from the table.
Example 2: SQL LIMIT with WHERE Clause
 The accompanying query selects the initial 2 records from the
Employee table with a given condition.
 Query:
 SELECT * FROM Employee
 WHERE Salary = 45000
 LIMIT 2;
 The above query will select all the employees according to the
imposed condition (i.e. it selects the limited 2 records from the table
where salary is 2000). Finally, the first 2 rows would be returned by
the above query.
Example 3: SQL LIMIT With OFFSET Clause
 The OFFSET keyword is utilized to indicate beginning rows from where
to select rows. For instance,
 Query:
 SELECT * FROM Employee
 LIMIT 2 OFFSET 2;
 Here, the above query selects 2 rows from the beginning of the third
row (i.e., OFFSET 2 means, the initial 2 rows are excluded or avoided).
SQL FETCH FIRST Clause
SQL FETCH FIRST clause fetches the first given number of rows from the
table.
It is supported in database systems like:
 IBM DB2
 Oracle
 PostgreSQL
Syntax:
The syntax to use the FETCH FIRST clause in SQL is:
SELECT columns FROM table WHERE condition FETCH FIRST n ROWS ONLY;
Here,
 n: desired number of rows
Example 1: SQL FETCH FIRST Clause
 Query:
 SELECT * FROM Employee FETCH FIRST 3 ROWS ONLY;
Example 2: SQL FETCH FIRST PERCENT
 In this example, we will fetch first 50% of the data from the table
 Query:
 SELECT *
 FROM Employee
 FETCH FIRST (SELECT CEIL(COUNT(*) / 2) FROM Employee) ROWS ONLY;
Example 3: SQL FETCH FIRST with WHERE Clause
 The "FETCH FIRST" syntax is not supported in MySQL. The correct
syntax for limiting the number of rows in MySQL is by using the LIMIT
clause.
 Query:
 SELECT *
 FROM Employee
 WHERE Salary = 45000
 FETCH FIRST 1 ROW ONLY;

SQL SELECT FIRST


The SELECT FIRST clause is used in some SQL databases (primarily
MS Access) to retrieve the first record from a table based on the order
in which data is stored or queried.
This operation can be useful when you want to retrieve a single, specific
entry, such as the first record of a list, or when you need to implement
certain functionalities in applications like employee management systems,
inventory systems, or billing systems.
Note: The SELECT FIRST clause is not universally supported across all SQL
platforms. Some variations of the FIRST clause in other databases
are LIMIT, TOP, or FETCH FIRST.
Syntax:
The syntax to use the SELECT FIRST clause in SQL is:
SELECT FIRST (columnName) FROM tableName;
Example: Retrieve the First Record from a Table
SELECT FIRST (Name) AS First_name FROM Stationary;
Example: Using SELECT FIRST with ORDER By
SELECT FIRST(Name) AS First_name
FROM Stationary
ORDER BY Price ASC;
Important Points About SQL SELECT FIRST
 The SELECT FIRST command in SQL is used to retrieve only the top
row from a table.
 SELECT FIRST can be beneficial for various purposes like login-
related functions on websites or implementing billing systems.
 The SELECT FIRST clause is not universally supported across all SQL
systems. It is primarily used in MS Access.
 It can used with other clauses like ORDER BY.

SQL - SELECT LAST


SELECT LAST is a concept or function often used to describe retrieving
the last record or last row from a table in SQL. Although MS Access
supports a LAST() function to directly fetch the last value from a column,
this function is not universally supported across all SQL-based databases.
Instead, in MySQL, PostgreSQL, Oracle, and SQL Server, there are
alternative methods to get the last record in a table.
Retrieving the last record is a common requirement in many applications.
Whether you’re dealing with log files, e-commerce transactions, or tracking
user activity, you generally need the ability to query the latest data from a
table. Since SELECT LAST() is not universally supported, we need to use
other approaches to extract the last record efficiently.
Method 1: Using the LAST() Function in MS Access
Syntax :
LAST(expression)
For example, say we want to extract the last student name from the table
"Student Information"
SELECT LAST(Student_name) AS Stud_Name
FROM StudentInformation;
Method 2: By Sorting the Data
MYSQL syntax :
SELECT col_name(s) FROM Table_Name
ORDER BY appr_col_name DESC
LIMIT 1;

col_name(s): The name of the column(s).


appr_col_name: Appropriate column name to perform ORDER BY.
Oracle syntax :
SELECT col_name(s) FROM Table_Name
ORDER BY appr_col_name DESC
WHERE ROWNUM <= 1;

col_name(s): The name of the column(s).


appr_col_name: Appropriate column name to perform ORDER BY.
It is important to note that in order to perform sorting, the column needs
to be chosen properly. For example, if we choose "ORDER
BY Student_name DESC" then it will alphabetically sort the table on the
basis of names. So, the row containing "Vishal" will come at the top, but the
row having "Vishal" as entry is not the last row of the table. Also, we can't
use the column "Age" to perform ORDER BY as shown below:

Hence, it is mandatory to use the column ID or any column which is


unique and sequentially increasing with every record in the table.
Method 3: By using Subquery and AGGREGATE MAX()
Subquery is nothing but a query inside another query that maintains a
parent-child relationship. The inner query will execute first followed by the
outer query. Here, in this method, the basic idea is to get the maximum ID
using aggregate function MAX and then select the student name
associated with that maximum ID. In this way, we can extract the last
student's name from the table.
SELECT col_name(s) FROM Table_Name
WHERE appr_col_name = (
SELECT MAX(appr_col_name)
FROM Table_Name
);

col_name(s): The name of the column(s).


appr_col_name: Appropriate column name. For example ID.

What is RANDOM() in SQL?


The RANDOM() function is used to generate random values and can be applied to
return random rows or records from a table in SQL. It has many real-life applications. Some
common use cases include:
1. There are a lot of employees in an organization. Suppose, if the event manager wants
to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get
the Email Id of the ten random employees.
2. It can also be used to display random questions during an online exam or MCQ from a
pool of questions.
Example 1: Using RAND() in MySQL
3. SELECT col_1,col_2, ... FROM Table_Name
4. ORDER BY RAND()
5.
6. col_1 : Column 1
7. col_2 : Column 2
The above query will return the entire table for the specific columns
mentioned and the rows will be random and changing position every
time we run the query. To get a single row randomly, we can use
the LIMIT Clause and set to only one row. ORDER BY clause in the
query is used to order the row(s) randomly.
8. SELECT col_1,col_2, ... FROM Table_Name
9. ORDER BY RAND()
10. LIMIT 1
11.
12. col_1 : Column 1
13. col_2 : Column 2
Performance Considerations
While RANDOM() is useful, it should be noted that random ordering can be very resource
intensive, especially when working with large data sets. The database must sort the entire
table by random value, which can be slow if the table has millions of rows.
For optimal performance, consider the following strategies:
 Limit the number of rows: Always use LIMIT to restrict the number of random rows
returned, especially for large tables.
 Use indexed columns: If you're selecting a random row based on certain conditions
(e.g., a random customer from a specific city), try to add indexes to relevant columns
to speed up the query.
SQL SELECT IN Statement
The IN operator in SQL is used to compare a column's value against a set
of values. It returns TRUE if the column's value matches any of the values
in the specified list, and FALSE if there is no match.
SQL SELECT IN Statement allows to specify multiple values in the
WHERE clause. It is similar to using multiple OR conditions. It is
particularly useful for filtering records based on a list of values or the
results of a subquery.
Syntax 1: SELECT IN for a list of values
Using the IN operator to provide a list of values:
SELECT column1, column2, ..., columnN
FROM table_name
WHERE column_name IN (val-1, val-2, ..., val-N);
Parameters:
 column1, column2, ..., columnN: The columns you want to
retrieve.
 table_name: The table from which to retrieve the columns.
 column_name: The column you want to filter.
 val-1, val-2, ..., val-N: The list of values you want to match.
Syntax 2: SELECT IN with a Subquery
Using the IN operator on values returned by another subquery:
SELECT column1, column2....columnN
FROM table_name1
WHERE column_name IN
(SELECT column_name
FROM table_name2);
Parameters:
 table_name1: The primary table from which to retrieve the
columns.
 table_name2: The secondary table used in the subquery to
provide the list of values.
Important Points about SQL SELECT IN Statement
 The SQL SELECT IN statement allows you to specify multiple values
in the WHERE clause.
 The IN operator is functionally similar to using multiple OR
conditions.
o For example, WHERE column_name IN (val-1, val-2, ...,
val-N) is equivalent to WHERE column_name = val-1 OR
column_name = val-2 OR ... OR column_name = val-N .
 The IN operator can be used with both static lists of values and
subqueries.

NOT IN
 By using the NOT keyword in front of the IN operator, you return all records that are
NOT any of the values in the list.
 Example
 Return all customers that are NOT from 'Germany', 'France', or 'UK':
 SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

NOT IN (SELECT)
 The result in the example above returned 74 records, that means that there are 17
customers that haven't placed any orders.
 Let us check if that is correct, by using the NOT IN operator.
 Example
 Return all customers that have NOT placed any orders in the Orders table:
 SELECT * FROM Customers
WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders);

SQL - SELECT DATE


SQL Dates
The most difficult part when working with dates is to be sure that the format of the date
you are trying to insert, matches the format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected.
However, if a time portion is involved, it gets more complicated.

SQL Date Data Types


MySQL comes with the following data types for storing a date or a date/time value in the
database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
 YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in
the database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your
database!

SQL SELECT DATE


In SQL, date and time values are stored in DATE, DATETIME, TIME,
TIMESTAMP, and YEAR data types, depending on your use case and the
database system you're using. To retrieve these values, we use
the SELECT statement.
Syntax:
SELECT column_name
FROM table_name
WHERE date_column = 'YYYY-MM-DD';
 column_name: The column from which you want to retrieve the
data.
 table_name: The table where the date column resides.
 date_column: The column that contains date values.
 'YYYY-MM-DD': The date format used to filter the records.
Example: Select Employees Hired on a Specific Date
SELECT FirstName, LastName, HireDate
FROM Employee
WHERE HireDate = '2022-01-15';
Using SQL SELECT Date Functions for Filtering
These SQL functions allow you to extract specific components (like year,
month, or day) from a DATE or DATETIME column.
 YEAR(): Extracts the year from a date.
 MONTH(): Extracts the month from a date.
 DAY(): Extracts the day from a date.
Example 1: Select Employees Hired in a Specific Year
SELECT FirstName, LastName, HireDate
FROM Employee
WHERE YEAR(HireDate) = 2021;
Example 2: Select Employees Hired in a Specific Month
SELECT FirstName, LastName, HireDate
FROM Employee
WHERE MONTH(HireDate) = 6;
Advanced Date Functions
In addition to extracting parts of a date, SQL provides several advanced
date functions for more complex operations. Below are some common
advanced functions:
CURDATE() and NOW()
 CURDATE(): Returns the current date (without the time
component).
 NOW(): Returns the current date and time.
Example 1: Select Employees Hired Before Today
SELECT FirstName, LastName, HireDate
FROM Employee
WHERE HireDate < CURDATE();
Using SQL BETWEEN for Date Ranges
The BETWEEN operator allows you to filter records within a specified date
range. This can be useful when you need to retrieve data between two
specific dates, such as all transactions made within a certain period or all
employees hired during a specific quarter.
Example 1: Select Employees Hired Between Two Dates
SELECT FirstName, LastName, HireDate
FROM Employee
WHERE HireDate BETWEEN '2021-01-01' AND '2022-01-01';

SQL INSERT INTO Statement


The SQL INSERT INTO statement is one of the most commonly used
commands for adding new data into a table in a database.
There are two main ways to use the INSERT INTO statement by specifying
the columns and values explicitly or by inserting values for all columns
without specifying them.
1. Inserting Data into All Columns (Simple Method)
This method is used when you want to insert data into all columns of a
table without specifying column names. We simply provide the values for
each column, in the same order that the columns are defined in the table.
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value);
Parameters:
 table_name: The name of the table where the data will be inserted
 value1, value2: The values you want to insert into the respective
columns of the table
2. Inserting Data into Specific Columns (Flexible
Method)
In some cases, you might want to insert data into only certain columns,
leaving the others empty or with default values. In such cases, we can
specify the column names explicitly.
Syntax
INSERT INTO table_name (column1, column2, column3)
VALUES ( value1, value2, value);
Parameters:
 table_name: name of the table.
 column1, column2..: name of first column, second column.
 value1, value2, value..: the values for each specified column of
the new record.
Important Points About SQL INSERT INTO
Statement
 Multiple Inserts: You can insert multiple rows at once by
separating each set of values with commas. This reduces the
number of queries you need to run.
 NULL Values: If you don't insert data into a column, it will typically
be set to NULL unless the column has a default value.
 Order of Columns: When using the simple INSERT INTO syntax
without specifying column names, the values must be in the exact
same order as the columns are defined in the table.
 Default Values: Columns not mentioned in the INSERT
INTO statement will be filled with their default values (often NULL).
 Efficiency: Inserting multiple rows at once is much more efficient
than doing it one by one.

SQL Query to Insert Multiple Rows


In SQL, the INSERT statement is used to add new records to a database
table. When you need to insert multiple rows in a single query, the
INSERT statement becomes efficient.
Insertion in a table is a DML (Data manipulation language) operation in
SQL.
Basic INSERT for Multiple Rows
INSERT INTO Employees (EmployeeID, EmployeeName, Age, Department)
VALUES
(1, 'John Doe', 30, 'Engineering'),
(2, 'Jane Smith', 28, 'Marketing'),
(3, 'Sam Brown', 35, 'Sales'),
(4, 'Lucy Green', 25, 'Human Resources');
Using INSERT INTO ... SELECT for Inserting
Multiple Rows
The INSERT INTO ... SELECT method is useful when you need to
insert multiple rows into a table based on the results of another
query or a different table.
INSERT INTO Employees (EmployeeID, EmployeeName, Age, Department)
SELECT EmployeeID, EmployeeName, Age, Department
FROM NewEmployees
WHERE Age > 30;
Inserting Data Using Transactions
When inserting large amounts of data, you can use SQL transactions to
ensure that all rows are inserted correctly. A transaction groups
multiple SQL operations into a single unit, so if one operation fails, the
entire transaction is rolled back.
Query:
BEGIN TRANSACTION;

INSERT INTO Customers (CustomerID, CustomerName, ContactName,


Country)
VALUES (5, 'Sarah White', 'John White', 'Canada');

INSERT INTO Customers (CustomerID, CustomerName, ContactName,


Country)
VALUES (6, 'Mohamed Ibrahim', 'Ahmed Ibrahim', 'UAE');

-- If any error occurs, the transaction will be rolled back

COMMIT;

SQL UPDATE Statement


The UPDATE statement in SQL is used to modify the data of an existing
record in a database table. We can update single or multiple columns in a
single query using the UPDATE statement as per our requirement. Whether
you need to correct data, change values based on certain conditions, or
update multiple fields simultaneously, the UPDATE statement provides a
simple yet effective way to perform these operations.
key points about UPDATE statement
1. Modify Specific Data: The UPDATE statement can be used to change
specific data in one or more columns for rows that meet a certain
condition.
2. Target Specific Rows: You can control which rows to update by using
the WHERE clause. If you omit the WHERE clause, all rows in the table
will be updated, so it’s important to use this clause carefully to avoid
unintended changes.
3. Single or Multiple Columns: The UPDATE statement allows you to
modify one or more columns at a time. This makes it versatile when
you need to update multiple pieces of information for the same
record.
4. Efficiency: Using UPDATE is more efficient than deleting and re-
inserting data because it directly modifies the existing record without
affecting other rows in the table.
5. Data Integrity: The UPDATE statement helps maintain data integrity
by allowing you to fix errors or modify data without needing to remove
and re-add records, ensuring that related data remains consistent.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;
Parameters
 UPDATE: The SQL command used to modify the data in a table.
 SET: This clause defines which columns will be updated and what
their new values will be.
 WHERE: The condition that determines which rows will be updated.
Without it, all rows will be affected.
 table_name: name of the table in which you want to make updates
 column1, column2, ...: The columns you want to update.
 value1, value2, ...: The new values to assign to these columns.
 condition: Specifies which rows to update. This condition is crucial,
as omitting it will update all rows in the table.
Note: In the above query the SET statement is used to set new values to
the particular column and the WHERE clause is used to select the rows for
which the columns are needed to be updated. If we have not used the
WHERE clause then the columns in all the rows will be updated. So the
WHERE clause is used to choose the particular rows.
Example 1: Update Single Column Using UPDATE Statement
We have a Customer table, and we want to Update
the CustomerName where the Age is 22.
Query:
UPDATE Customer
SET CustomerName = 'Nitin'
WHERE Age = 22;
Example 2: Updating Multiple Columns using UPDATE
Statement
We need to update both the CustomerName and Country for a
specific CustomerID.
Query:
UPDATE Customer
SET CustomerName = 'Satyam',
Country = 'USA'
WHERE CustomerID = 1;
Note: For updating multiple columns we have used comma(,) to separate
the names and values of two columns.
Example 3: Omitting WHERE Clause in UPDATE Statement
If we accidentally omit the WHERE clause, all the rows in the table will be
updated, which is a common mistake. Let’s update the CustomerName for
every record in the table:
Query:
UPDATE Customer
SET CustomerName = 'Shubham';
Explanation: This will set the CustomerName for every row in
the Customer table to 'Shubham'. Be careful while omitting
the WHERE clause, as this action is irreversible unless you have a backup.
Optimizing Your SQL UPDATE Queries
 Avoid frequent updates: Constantly updating rows can slow
down performance. Batch updates or consider using a database
trigger to handle automatic updates.
 Index relevant columns: Ensure that columns in the WHERE clause
(such as CustomerID) are indexed. This will improve the speed of the
update operation.
Important Points About SQL UPDATE Statement
1. Always use the WHERE clause: The most important point when using
the UPDATE statement is to always include a WHERE clause unless you
genuinely intend to update all rows.
2. Check your data before updating: Run a SELECT query to view the
data you want to update before executing the UPDATE statement. This helps
avoid accidental data modifications.
SELECT * FROM Customer WHERE Age = 22;
3. Use transactions for critical updates: When performing updates in a
production environment, consider using transactions. Transactions allow
you to commit or roll back changes as needed.
BEGIN TRANSACTION;
UPDATE Customer SET CustomerName = 'John' WHERE CustomerID = 3;
COMMIT; -- Use ROLLBACK to undo if necessary
4. Test on a small dataset first: If you’re uncertain about the impact of
your UPDATE, test it on a small subset of data to ensure the changes are as
expected.

SQL DELETE Statement


SQL DELETE Statement
The SQL DELETE statement removes one or more rows from a database
table based on a condition specified in the WHERE clause. It's a DML (Data
Manipulation Language) operation that modifies the data within the
table without altering its structure.
Syntax:
DELETE FROM table_name
WHERE some_condition;
Parameter Explanation
 Some_condition: A condition used to filter the rows you want to
delete.
 table_name: The name of the table from which you want to delete
the rows
Note: We can delete single as well as multiple records depending on the
condition we provide in the WHERE clause. If we omit the WHERE clause
then all of the records will be deleted and the table will be empty.
Example 1: Deleting Single Record
We can use the DELETE statement with a condition to delete a specific
row from a table. The WHERE clause ensures only the intended record is
removed. We can delete the records named Rithvik by using the below
query:
Query:
DELETE FROM GFG_Employees WHERE NAME = 'Rithvik';
Example 2: Deleting Multiple Records
To delete multiple records, you can specify a condition that matches
several rows. Let's delete the rows from the table GFG_Employees where
the department is "Development". This will delete 2 rows (the first row
and the seventh row).
Query
DELETE FROM GFG_Employees
WHERE department = 'Development';
Example 3: Delete All Records from a Table
If we need to delete all records from the table, we can omit
the WHERE clause, or alternatively use the DELETE statement with an
asterisk (*) to denote all rows.
Query:
DELETE FROM GFG_Employees;
Or
DELETE * FROM GFG_Employees;
Rolling Back DELETE Operations
Since the DELETE statement is a DML operation, it can be rolled
back when executed in a statement. If you accidentally delete records or
need to repeat the process, you can use the ROLLBACK command.
Query:
START TRANSACTION;
DELETE FROM GFG_Employees WHERE department = 'Development';
-- If needed, you can rollback the deletion
ROLLBACK;
Explanation: The ROLLBACK command will undo the changes made by the
DELETE statement, effectively restoring the records that were deleted
during the transaction.
Best Practices for Using SQL DELETE
To use the SQL DELETE statement safely and efficiently, here are some
best practices:
1. Use Transactions: Wrap DELETE statements in transactions to
provide an option to roll back changes if necessary. This ensures
data integrity.
2. Always Use a WHERE Clause: Avoid deleting all rows by
accident. Always filter records using a WHERE clause to specify
which rows to delete. Omitting the WHERE clause will delete all
records.
3. Backup Data: Before performing large deletions, ensure that you
have a backup of the data to avoid irreversible loss.
4. Test on Development Server: Always test your DELETE queries
on a development or staging environment to ensure they
produce the desired result before executing them on a live
database.
5. Optimize Deletions: For large datasets, delete records in
batches to reduce performance impact and avoid long-running
queries.
6. Use Caution When Deleting Data: Be extra cautious when
deleting records from sensitive or production databases. Always
verify the condition in the WHERE clause to ensure you're deleting
the right data.

SQL Query to Delete Duplicate Rows


What Are Duplicate Rows?
Duplicate rows are records in a database that have identical values in
one or more columns. These rows often arise due to issues like multiple
imports, user errors, or missing constraints like primary keys or
unique indexes. SQL query to delete duplicate rows typically involves
identifying duplicates using functions like ROW_NUMBER() or COUNT() and
making sure that only one copy of each record is kept in the table. If not
handled properly, duplicates can lead to:
 Inaccurate Data Reporting: Reports may contain false
information.
 Storage Waste: Redundant records consume unnecessary space.
 Decreased Query Performance: Queries on large tables with
duplicates may perform poorly.
Why You Should Remove Duplicate Rows
1. Data Integrity: Duplicates can distort reports and analyses,
leading to incorrect insights.
2. Optimal Performance: Redundant data can slow down queries,
especially when dealing with large datasets.
3. Efficient Storage: Removing duplicates helps optimize storage
usage, keeping your database lean.
How to Identify Duplicate Rows
We Use the GROUP BY clause with the COUNT(*) function to
find rows with duplicate values. This step helps us group the records
by specific columns and count how many times each combination
occurs, making it easier to identify duplicates that appear more than once
in the table.
Query:
SELECT EMPNAME, DEPT, CONTACTNO, CITY,
COUNT(*) FROM DETAILS
GROUP BY EMPNAME, DEPT, CONTACTNO, CITY
HAVING COUNT(*)>1
Method 1: Using GROUP BY and COUNT()
Use the GROUP BY clause along with MIN(SN) to retain one unique row for each
duplicate group. This method identifies the first occurrence of
each duplicate combination based on the SN (serial number) and
deletes the other duplicate rows.
Query:
DELETE FROM DETAILS
WHERE SN NOT IN (
SELECT MIN(SN)
FROM DETAILS
GROUP BY EMPNAME, DEPT, CONTACTNO, CITY
);
Select * FROM DETAILS;

Method 2: Using ROW_NUMBER()


The ROW_NUMBER() function provides a more elegant and flexible solution. This
window function assigns a unique number to each row within a partition
(group of duplicates). We can delete rows where the row number is greater
than 1.
Query:
WITH CTE AS (
SELECT SN, EMPNAME, DEPT, CONTACTNO, CITY,
ROW_NUMBER() OVER (PARTITION BY EMPNAME, DEPT, CONTACTNO,
CITY ORDER BY SN) AS RowNum
FROM DETAILS
)
DELETE FROM CTE WHERE RowNum > 1;

SQL Clauses
SQL | WHERE Clause
Whether you're retrieving data, updating records, or deleting entries
from a database, the WHERE clause plays an important role in defining
which rows will be affected by the query. Without it, SQL queries would
return all rows in a table, making it difficult to target specific data.
The SQL WHERE clause is used to specify a condition while fetching or
modifying data in a database. It filters the rows that are affected by
the SELECT, UPDATE, DELETE, or INSERT operations. The condition can
range from simple comparisons to complex expressions, enabling precise
targeting of the data.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name
operator value;
Parameter Explanation:
1. column1,column2: fields in the table
2. table_name: name of table
3. column_name: name of field used for filtering the data
4. operator: operation to be considered for filtering
5. value: exact value or pattern to get related data in the result
Example 1: Where Clause with Logical Operators
To fetch records of Employee with age equal to 24.
Query:
SELECT * FROM Emp1 WHERE Age=24;
Query:
SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;

Example 2: Where Clause with BETWEEN Operator


It is used to fetch filtered data in a given range inclusive of two values.
Syntax:
SELECT column1,column2 FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Parameter Explanation:
1. BETWEEN: operator name
2. value1 AND value2: exact value from value1 to value2 to get
related data in result set.
SELECT * FROM Emp1 WHERE Age BETWEEN 22 AND 24;
Example 3: Where Clause with LIKE Operator
It is used to fetch filtered data by searching for a particular pattern in the
where clause.
Syntax:
SELECT column1,column2 FROM
table_name WHERE column_name LIKE pattern;
Parameters Explanation:
1. LIKE: operator name
2. pattern: exact value extracted from the pattern to get related data
in the result set.
Note: The character(s) in the pattern is case-insensitive.
To fetch records of Employees where Name starts with the letter S.
Query:
SELECT * FROM Emp1 WHERE Name LIKE 'S%';
Example 4: Where Clause with IN Operator
It is used to fetch the filtered data same as fetched by '=' operator just the
difference is that here we can specify multiple values for which we can get
the result set.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name IN
(value1,value2,..);
Parameters Explanation:
1. IN: operator name
2. value1,value2,..: exact value matching the values given and get
related data in the result set.
To fetch the Names of Employees where Age is 21 or 23.
Query:
SELECT Name FROM Emp1 WHERE Age IN (21,23);
List of Operators that Can be Used with WHERE
Clause
Operato
r Description

> Greater Than

>= Greater than or Equal to

< Less Than

<= Less than or Equal to

= Equal to

<> Not Equal to

BETWEE
In an inclusive Range
N

LIKE Search for a pattern

To specify multiple possible values for a


IN
column

SQL | WITH Clause


What is SQL WITH Clause?
The SQL WITH clause is used to define temporary tables or result
sets within a query. These temporary relations also known as Common
Table Expressions (CTEs), act like virtual tables that exist only during
the execution of the query. We can use these temporary tables multiple
times in the main query, making it easier to manage and reuse complex
logic without repeating the same subquery.
This method also helps in performance optimization, as the query
planner can optimize the reuse of intermediate results instead of re-
executing the same complex subqueries multiple times.
Why Use the WITH Clause?
 Improves Readability: By breaking down complex queries into
smaller, more manageable parts.
 Enhances Maintainability: Makes it easier to debug and modify
your queries.
 Optimizes Performance: Reduces redundancy and ensures that
temporary results are only calculated once.
Syntax:
WITH temporaryTable (averageValue) AS (
SELECT AVG (Attr1)
FROM Table
)
SELECT Attr1
FROM Table, temporaryTable
WHERE Table.Attr1 > temporaryTable.averageValue;
Key Terms
 The WITH clause defines a temporary relation (temporaryTable),
which contains values selected from some_table.
 The subsequent SELECT query uses this temporary table in the
main query to perform a join or filter data based on specific
conditions.
 Note: When a query with a WITH clause is executed, first the
query mentioned within the clause is evaluated and the output of
this evaluation is stored in a temporary relation. Following this,
the main query associated with the WITH clause is finally executed
that would use the temporary relation produced.

Examples of SQL WITH Clause


Let's look at some practical examples of WITH Clause in SQL to better
understand how it can simplify complex queries and improve query
performance:
Example 1: Finding Employees with Above-Average Salary
This example demonstrates how to find all employees whose salary is
higher than the average salary of all employees in the database. The
query calculates the average salary using the WITH clause and compares
each employee's salary against this average to return those with above-
average salaries.
Query:
WITH temporaryTable (averageValue) AS (
SELECT AVG(Salary)
FROM Employee
)
SELECT EmployeeID,Name, Salary
FROM Employee, temporaryTable
WHERE Employee.Salary > temporaryTable.averageValue;
Explanation:
 Temporary Table (CTE): We calculate the average salary using
the WITH clause and store it in a temporary table
called averageSalary.
 Main Query: The main query then compares each employee's
salary against the calculated average and returns the employees
whose salaries are above the average.
 The average salary of all employees is 70591. Therefore, all
employees whose salary is more than the obtained average lies in
the output relation.
Example 2: Finding Airlines with High Pilot Salaries
In this example, we aim to find airlines where the total salary of all pilots
exceeds the average salary of all pilots in the database. The WITH
clause will be used to first calculate the total salary for each airline and
then compare it to the overall average salary.
Query:
WITH totalSalary(Airline, total) AS (
SELECT Airline, SUM(Salary)
FROM Pilot
GROUP BY Airline
),
airlineAverage (avgSalary) AS (
SELECT avg(Salary)
FROM Pilot
)
SELECT Airline
FROM totalSalary, airlineAverage
WHERE totalSalary.total > airlineAverage.avgSalary;
Explanation:
The total salary of all pilots of Airbus 380 = 298,830 and that of Boeing
= 45000. Average salary of all pilots in the table Pilot = 57305. Since
only the total salary of all pilots of Airbus 380 is greater than the average
salary obtained, so Airbus 380 lies in the output relation.
Key Benefits of Using the WITH Clause
1. Improved Readability: The WITH clause breaks down complex
queries into simpler parts, making it easier to follow the logic.
2. Reusable Subqueries: If you need to reference the same subquery
multiple times in your query, the WITH clause saves you from repeating
the same code.
3. Performance Optimization: By storing intermediate results, SQL
databases can optimize the execution of queries, potentially improving
performance.
4. Easy Debugging: Since each CTE is defined separately, it's easier to
test and debug different parts of the query without affecting the main logic.
Important Things to Remember About the SQL
WITH Clause
1. Temporary Lifetime: The temporary tables (CTEs) defined in the WITH
clause only exist during the execution of the query. Once the query is
finished, they are discarded.
2. Nested WITH Clauses: You can define multiple CTEs in a single query,
and they can reference each other.
Example:
WITH CTE1 AS (...), CTE2 AS (...)
SELECT * FROM CTE1, CTE2;
3. Performance Consideration: While the WITH clause is excellent for
readability and maintainability, it can sometimes be less efficient in cases
where the temporary result set is large. Always check the execution plan to
ensure you're optimizing your queries correctly.

SQL HAVING Clause


🔹 How is it Different from WHERE?

Clause Filters Data Used On Can Use Aggregate Functions?


WHERE Before grouping Individual rows ❌ No
✅ Yes
HAVING After grouping Groups of rows

The HAVING clause in SQL is used to filter query results based on


aggregate functions.
Unlike the WHERE clause, which filters individual rows before grouping,
the HAVING clause filters groups of data after aggregation. It is commonly
used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
It was introduced because the WHERE clause cannot be used with aggregate
functions. Similar to WHERE clause, it helps apply conditions but specifically
works with grouped data.
Key Features of the HAVING Clause
 Used to filter grouped data based on aggregate functions.
 Works with Boolean conditions (AND, OR
 Cannot be used without GROUP BY unless an aggregate function is
present.
 Must be placed after the GROUP BY clause and before the ORDER
BY clause (if used).
 Helps generate summary reports from large datasets.
Syntax:

SELECT column_name, AGGREGATE_FUNCTION(column_name)


FROM table_name
GROUP BY column_name
HAVING condition;
Example 1 : Using HAVING to Filter Aggregated Results
This employee table will help us understand the HAVING Clause. It contains
employee IDs, Name, Gender, department, and salary. To Know the sum of
salaries, we will write the query:
Query:
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department;
Now if we need to display the departments where the sum of salaries is
50,000 or more. In this condition, we will use the HAVING Clause.
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Example 2: Using HAVING with Multiple Conditions
If we want to find the departments where the total salary is greater than or
equal to $50,000, and the average salary is greater than $55,000. We can
use the HAVING clause to apply both conditions.
Query
SELECT Department, SUM(Salary) AS Total_Salary, AVG(Salary) AS
Average_Salary
FROM Employee
GROUP BY Department
HAVING SUM(Salary) >= 50000 AND AVG(Salary) > 55000;
Example 3: Using HAVING with COUNT()
If we want to find departments where there are more than two employees.
For this, we can use the COUNT() aggregate function along with the
HAVING clause.
Query:
SELECT Department, COUNT(EmployeeId) AS Employee_Count
FROM Employee
GROUP BY Department
HAVING COUNT(EmployeeId) >= 2;
Example 4: Using HAVING with AVG()
In this example, let's find out the average salary for each department and
use the HAVING clause to display only those departments where the
average salary is greater than $50,000.
Query:
SELECT Department, AVG(Salary) AS Average_Salary
FROM Employee
GROUP BY Department
HAVING AVG(Salary) > 50000;
Having Where

In the HAVING clause it will check In the WHERE condition it will check or
the condition in group of a row. execute at each row individual.

HAVING clause can only be used The WHERE Clause cannot be used with
with aggregate function. aggregate function like Having
Having Where

Priority Wise HAVING Clause is Priority Wise WHERE is executed before


executed after Group By. Group By.

SQL ORDER BY
The ORDER BY clause in SQL is a powerful feature used to sort query
results in either ascending or descending order based on one or more
columns.
The ORDER BY statement in SQL is used to sort the fetched data in
either ascending or descending according to one or more columns. It is
very useful to present data in a structured manner.
SQL ORDER BY default mode is sorting data into ascending order. To sort
data in descending order use the DESC keyword with ORDER BY clause.
Syntax:
The syntax to use ORDER BY clause in SQL is:
SELECT * FROM table_name ORDER BY column_name ASC | DESC
Key Terms:
 table_name: name of the table.
 column_name: name of the column according to which the data is
needed to be arranged.
 ASC: to sort the data in ascending order.
 DESC: to sort the data in descending order.
Example 1 : Sort According To a Single Column using ORDER
BY Clause
SELECT * FROM students ORDER BY ROLL_NO DESC;
Example 2 : Sort According To Multiple Columns using
ORDER BY Clause
SELECT * FROM students ORDER BY age DESC , name ASC;

Note: ASC is the default value for the ORDER BY clause. So, if we don't
specify anything after the column name in the ORDER BY clause, the
output will be sorted in ascending order by default.
Sorting By Column Number (instead of name)
An integer that identifies the number of the column in the SelectItems in
the underlying query of the SELECT statement. Column number must be
greater than 0 and not greater than the number of columns in the result
table.
The rule checks for ORDER BY clauses that reference select list columns using the
column number instead of the column name. Further, changing the order of
columns in the SELECT list has no impact on the ORDER BY when the columns are
referred to by names instead of numbers.
Syntax:
The Syntax to use ORDER BY Clause with Column Number
ORDER BY Column_Number asc/desc
Query:
CREATE TABLE studentinfo
( Roll_no INT,
NAME VARCHAR(25),
Address VARCHAR(20),
CONTACTNO BIGINT NOT NULL,
Age INT );

INSERT INTO studentinfo


VALUES (7,'ROHIT','GHAZIABAD',9193458625,18),
(4,'DEEP','RAMNAGAR',9193458546,18),
(1,'HARSH','DELHI',9193342625,18),
(8,'NIRAJ','ALIPUR',9193678625,19),
(5,'SAPTARHI','KOLKATA',9193789625,19),
(2,'PRATIK','BIHAR',9193457825,19),
(6,'DHANRAJ','BARABAJAR',9193358625,20),
(3,'RIYANKA','SILIGURI',9193218625,20);

SELECT Roll_no, Name, Address


FROM studentinfo
ORDER BY 1
Explanation:
ORDER BY 1 means sorting values according to first column in the SELECT
statement.
Important Points About ORDER BY Clause in SQL
 The ORDER BY clause in SQL is used to sort the result set of a
SELECT statement based on specified columns.
 It is essential for organizing query results and presenting data in a
structured manner.
 It can sort data in either ascending (ASC) or descending (DESC)
order.
 Multiple columns can be specified for sorting, allowing for more
complex sorting criteria.
 We can use ORDER BY with WHERE clause, GROUP BY clause,
and HAVING clause.

SQL | GROUP BY
The SQL GROUP BY clause is a powerful tool used to organize data into groups
based on shared values in one or more columns. It's most often used with
aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform summary
operations on each group helping us extract meaningful insights from large
datasets.
The GROUP BY statement in SQL is used to arrange identical data into groups
based on specified columns. If a particular column has the same values in multiple
rows, the GROUP BY clause will group these rows together. It’s commonly used
with aggregate functions to calculate totals or averages per group. Key Points
About GROUP BY:
 GROUP BY clause is used with the SELECT statement.
 In the query, the GROUP BY clause is placed after the WHERE clause.
 In the query, the GROUP BY clause is placed before the ORDER BY clause if
used.
 In the query, the GROUP BY clause is placed before the Having clause.
 Place condition in the having clause.

Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() , AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Example 1 : Group By Single Column
SELECT name, SUM(sal) FROM emp
GROUP BY name;
Example 2 : Group By Multiple Columns
Group by multiple columns is say, for example, GROUP BY column1, column2.
This means placing all the rows with the same values of columns column
1 and column 2 in one group. This SQL query groups student records by
both SUBJECT and YEAR and then counts the number of records (i.e.,
students) in each of those groups.
Query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
HAVING Clause in GROUP BY Clause
We know that the WHERE clause is used to place conditions on columns but what if
we want to place conditions on groups? This is where the HAVING clause comes
into use. We can use the HAVING clause to place conditions to decide which group
will be part of the final result set. Also, we can not use aggregate functions like
SUM(), COUNT(), etc. with the WHERE clause. So we have to use the HAVING
clause if we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Key Terms
 function_name: Name of the function used for example, SUM() , AVG().
 table_name: Name of the table.
 condition: Condition used.
Example:
SELECT NAME, SUM(sal) FROM Emp
GROUP BY name
HAVING SUM(sal)>50000;
SQL LIMIT Clause
The LIMIT clause in SQL is used to control the number of rows returned in
a query result.
What is the SQL LIMIT Clause?
The SQL LIMIT clause is used to control maximum number of
records returned by a query. It is commonly used for limiting query
results when only a subset of the data is required, such as
for pagination, filtering top values, or analyzing a smaller portion of a
large table. This can be particularly useful for tasks like:
 Paginating results (e.g., showing 10 results per page)
 Retrieving top records (e.g., the top 5 highest-rated products)
 Sampling data (e.g., getting a random sample of rows for
analysis)
Syntax:

SELECT column1, column2, ...


FROM table_name
WHERE condition
ORDER BY column
LIMIT [offset,] row_count;
Key Terms
 offset: number of rows to skip before returning the result set.
 row_count: number of rows to return in the result set.

Example 1: Basic LIMIT Usage


Query:
SELECT * FROM student
LIMIT 3;
Example 2: LIMIT with ORDER BY Clause
In this example, we will use the LIMIT clause with ORDER BY clause to
retrieve the top 3 students sorted by their grade (assuming
a Grade column exists.
Query:
SELECT * FROM Student
ORDER BY Grade DESC
LIMIT 3;
SQL LIMIT with OFFSET
The OFFSET clause allows us to skip a specified number of rows before
starting to return the results. OFFSET can only be used with the ORDER
BY clause. It cannot be used on its own. It’s particularly helpful
for pagination, where we might want to show different "pages" of
results from a larger dataset. OFFSET value must be greater
than or equal to zero. It cannot be negative, else returns an error.
Syntax:
SELECT * FROM table_name ORDER BY column_name LIMIT X OFFSET Y;
OR
SELECT * FROM table_name ORDER BY column_name LIMIT Y,X;
 X → Number of rows to return.
 Y → Number of rows to skip.
Example: Skipping First 2 Rows & Fetching 2 Rows
Imagine we have a list of students, but we want to skip the first 2 rows
and fetch the next 2 students based on their age.
Query:
SELECT *
FROM Student
ORDER BY age
LIMIT 2 OFFSET 2;
Using LIMIT to Get the nth Highest or Lowest
Value
Now we will look for LIMIT use in finding highest or lowest value we
need to retrieve the rows with the nth highest or lowest value. In that
situation, we can use the subsequent LIMIT clause to obtain the desired
outcome.
Syntax:
SELECT column_list
FROM table_name
ORDER BY expression
LIMIT n-1, 1;
Example: Fetching the 3rd Highest Age
Let’s say we want to find the third-highest age from your Student table.
We can do this using LIMIT along with ORDER BY.
Query:
SELECT age FROM Student
ORDER BY age LIMIT 2, 1;
Explanation:
 Orders records in descending order (highest age first).
 Skips 2 records (LIMIT 2) and retrieves the next one (LIMIT 2,1).
Using LIMIT with WHERE Clause
The WHERE clause can also be used with LIMIT. It produces the rows
that matched the condition after checking the specified condition in the
table.
Query:
SELECT age
FROM Student
WHERE id<4
ORDER BY age
LIMIT 2, 1;
Explanation: This query filters students whose ID is less than 4, orders
them by age, and retrieves the second youngest student (skipping the
first one and fetching the next one). It's a powerful way to focus on
specific data before limiting the output.
Restrictions on the LIMIT clause
There are several limitations of SQL LIMIT. The following situations do
not allow the LIMIT clause to be used:
 With regard to defining a view
 The use of nested SELECT statements
 Except for subqueries with table expressions specified in the
FROM clause.
 Embedded SELECT statements are used as expressions in a
singleton SELECT (where max = 1) within an SPL routine where
embedded SELECT statements are used as expressions.
Important Points About SQL LIMIT
 The LIMIT clause is used to set an upper limit on the number of
tuples returned by SQL.
 It is important to note that this clause is not supported by all SQL
versions.
 The LIMIT clause can also be specified using the SQL 2008
OFFSET/FETCH FIRST clauses.
 The limit/offset expressions must be a non-negative integer.
SQL Operators
SQL AND Operator
The AND operator allows you to filter data based on multiple
conditions, all of which must be true for the record to be included in the
result set.
Syntax:
The syntax to use the AND operator in SQL is:
SELECT * FROM table_name WHERE condition1 AND condition2
AND ...conditionN;
Here,
 table_name: name of the table
 condition1,2,..N: first condition, second condition, and so on.
SELECT * FROM Student
WHERE Age = 18 AND ADDRESS = 'Delhi';

SQL OR Operator
The OR Operator in SQL displays the records where any one condition is
true, i.e. either condition1 or condition2 is True.
Syntax:
The syntax to use the OR operator in SQL is:
SELECT * FROM table_name WHERE condition1 OR condition2 OR...
conditionN;
 table_name: name of the table
 condition1,2,..N: first condition, second condition, and so on
SELECT * FROM Student
WHERE NAME = 'Ram' OR NAME = 'SUJIT';
Combining AND and OR Operators in SQL
SELECT * FROM table_name
WHERE condition1 AND (condition2 OR condition3);
SQL LIKE Operator
The SQL LIKE operator is used for performing pattern-based searches in a
database. It is used in combination with the WHERE clause to filter
records based on specified patterns, making it essential for any database-
driven application that requires flexible search functionality.
SQL LIKE operator is used with the WHERE clause to search for a
specified pattern in a column. LIKE operator finds and returns the rows that
fit in the given pattern.
LIKE operator is case-insensitive by default in most database systems.
This means that if you search for "apple" using the LIKE operator, it will
return results that include "Apple", "APPLE", "aPpLe", and so on.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
 column_name: The column to be searched.
 pattern: The pattern to search for, which can include wildcard
characters.
For making the LIKE operator case-sensitive, you can use the "BINARY"
keyword in MySQL or the "COLLATE" keyword in other database
systems.
For example:
SELECT * FROM products WHERE name LIKE BINARY 'apple%'
Wildcard Characters with the SQL LIKE Operator
Wildcards are used with the LIKE operator to search for specific patterns
in strings. Wildcard characters substitute one or more characters in the
string. There are four wildcard characters in SQL:
1. % (Percent): Represents zero or more characters.
2. _ (Underscore): Represents a single character.
3. [] (Square Brackets): Represents any single character within
brackets.
4. - (Hyphen): Specify a range of characters inside brackets.
Examples of Wildcards
The below table shows some examples on how wild card can be written and
what do they mean:
Pattern Meaning

'a%' Match strings that start with 'a'

'%a' Match strings with end with 'a'


Pattern Meaning

'a%t' Match strings that contain the start with 'a' and end with 't'.

'%wow Match strings that contain the substring 'wow' in them at any
%' position.

Match strings that contain the substring 'wow' in them at the


'_wow%'
second position.

'_a%' Match strings that contain 'a' at the second position.

Match strings that start with 'a and contain at least 2 more
'a_ _%'
characters.

Example 1 : Match Names Starting with 'Ca'


Retrieve SupplierID, Name, and Address from suppliers table, where
supplier name starts form k.
SELECT SupplierID, Name, Address
FROM Supplier
WHERE Name LIKE 'Ca%';
Example 2: Match Addresses Containing 'Okhla'
Retrieve entire table, where address contains OKHLA.
SELECT *
FROM Supplier
WHERE Address LIKE '%Okhla%';
Example 3: Match Names Where 'ango' Appears in the
Second Position
Retrieve SupplierID, Name and Address of supplier whose name contains
"ango" in second substring.
SELECT SupplierID, Name, Address
FROM Supplier
WHERE Name LIKE '_ango%';
Example 4: Using LIKE with AND for Complex Conditions
Retrieve suppliers from Delhi with names starting with "C":
SELECT SupplierID, Name, Address
FROM Supplier
WHERE Address LIKE '%Delhi%' AND Name LIKE 'C%';
Example 5: Using NOT LIKE for Exclusion
To retrieve all suppliers whose name does not contain "Mango"
SELECT SupplierID, Name, Address
FROM Supplier
WHERE Name NOT LIKE '%Mango%';
SQL IN Operator
The SQL IN operator filters data based on a list of specific values. In
general, we can only use one condition in the Where clause, but the IN
operator allows us to specify multiple values.
The IN Operator in SQL is used to specify multiple values/sub-queries in
the WHERE clause. It provides an easy way to handle
multiple OR conditions.
We only pass a single condition in the WHERE clause, however there might
be situations where we need to select data based on multiple conditions.
For such cases, the IN operator is used.
Note: If any of the conditions are passed using the IN operator, they
will be considered true
Syntax:
SELECT column_name FROM table_name
WHERE condition IN (condition_value1, condition_value2 .....);
Example 1: Basic Use of the IN Operator
SQL Query to get Fname and Lname of employees who have address in
Delhi and Himachal
Query:
SELECT Fname, Lname FROM employee
WHERE Address IN ('Delhi','Himachal');
Example 2: SQL IN and NOT IN Operators
We can use the SQL IN with the NOT operator to exclude specified data
from our result.
Query:
SELECT Fname FROM employee
WHERE Address NOT IN ('Delhi', 'Lucknow');
Example 3
We have used IN operator with explicit values for conditions. However, we
can use the IN operator to select values for the condition from another
query. For demonstrating this, we will use another table from the database,
manager. The contents of the table are given below.
Ss Departme
n nt

5 Sales

1 Technical

Now, we will write a query to fetch details of all employees who are
managers. This can be done by using nested SELCT queries with the IN
operator.
Query:
SELECT * FROM employee
WHERE Ssn IN (SELECT Ssn FROM manager);
Here, we have selected the Ssn of all managers from the manager table
and then, we have passed the result of this query to the main query in the
IN operator, which will fetch the details of all employees who have same
Ssn as fetched from the nested query.
Key takeaways about the SQL IN operator:
 The SQL IN operator allows you to specify multiple values in a
WHERE clause.
 It checks if a specified value matches any value in a list.
 It simplifies querying for records that match multiple criteria
without needing to use multiple OR conditions.
 The syntax is straightforward: WHERE column_name IN (value1,
value2, ...).
 It is commonly used with SELECT, INSERT, UPDATE, and DELETE
statements for filtering or updating data based on multiple values.
 Using the IN operator can make SQL queries more concise and
readable.

SQL NOT Operator


The SQL NOT operator is used to reverse the boolean result of a condition
in SQL. It helps in retrieving records that do not match a specific condition.
It is mostly used to specify what should not be included in the results table.
Syntax:
SELECT column1, colomn2, …
FROM table_name WHERE NOT condition;
Example 1: Using SQL NOT to Exclude a Specific Value
Query:
SELECT *
FROM Customers
WHERE NOT Country = 'UK';
Example 2: Using SQL NOT with IN Operator
Query:
SELECT *
FROM Customers
WHERE NOT Country IN ('USA', 'UK');
Example 3: Using SQL NOT with LIKE Operator
Query:
SELECT *
FROM Customers
WHERE NOT CustomerName LIKE 'R%';
Example 4: Using SQL NOT with NULL Values
Query:
SELECT *
FROM Customers
WHERE NOT PostalCode IS NULL;
This query excludes customers who have a NULL value for PostalCode.
Example 5: Using NOT with AND Operator
We can combine NOT with the AND operator to create more complex
conditions. This query retrieves customers who are not from the USA and
are also not from the UK.
Query:
SELECT *
FROM Customers
WHERE NOT Country = 'USA' AND NOT Country = 'UK';
Key TakeAways About NOT Operator
 NOT operator returns opposite results or negative results. It
negates boolean condition in the WHERE clause.
 It is used to exclude specific data from the result set.
 It can also be combined with other operators like- LIKE, BETWEEN,
and IN.

SQL NOT EQUAL Operator


The SQL NOT EQUAL operator is a comparison operator used to check if
two expressions are not equal to each other.
NOT EQUAL Operator in SQL is used to compare two values and return if
they are not equal. This operator returns boolean values. If given
expressions are equal, the operator returns false otherwise true. If any
one expression is NULL, it will return NULL.
It performs type conversion when expressions are of different data types,
for example, 5!= "Five".
We use the NOT EQUAL operator to display our table without some
exceptional values. For example, Let's, consider a table 'Students'. For
this table, we have, "id", "name", and "marks" as its columns. Now we
want to display all those rows that have marks not equal to "100". In this
kind of situation, the NOT EQUAL operator can be used.
Note: <> and != perform the same operation i.e. check inequality. The
only difference between <> and != is that <> follows
the ISO standard but != does not. So it is recommended to use <> for
NOT EQUAL Operator.
Syntax:
The SQL NOT EQUAL Operator syntax is:
SELECT * FROM table_name
WHERE column_name != value;

Example 1: SQL NOT EQUAL Operator For String


Query:
SELECT *
FROM students
WHERE name != 'Harsh';
Example 2: SQL NOT EQUAL Operator with Multiple Condition
Query:
SELECT * FROM geeksforgeeks
WHERE contest_score != 98 AND rank != 3
AND coding_streak >= 100;
Example 3: SQL NOT EQUAL Operator with GROUP BY Clause
Query:
SELECT rank, COUNT(*) as count_score
FROM geeksforgeeks
WHERE contest_score <> 100
GROUP BY rank;
Important Points About SQL NOT EQUAL Operator
 SQL NOT EQUAL Operator is a comparison operator denoted as != or <>. It returns
boolean values i.e. True or False.
 It returns False when the compared expressions are equal otherwise it returns True.
 We use this operator with the WHERE clause.
 We can use this operator for integers and strings-based logical reasoning. It is case-
sensitive for string comparisons.
 We can put multiple conditions using the AND or OR operator.

SQL IS NULL
The IS NULL operator is used to check if a column contains a NULL value. If
a column value is NULL, the operator returns TRUE; otherwise, it returns
FALSE. It's commonly used in WHERE clauses to filter rows that
contain NULL values in specific columns.
Syntax:
SQL IS NULL syntax is:
SELECT * FROM table_name
WHERE column_name IS NULL;
Note: A NULL value is different from a Zero Value and Blank Spaces. A
field that has NULL value means the field was left blank.
Example 1: IS NULL with WHERE clause
Query:
SELECT *
FROM students
WHERE email IS NULL;
Example 2: IS NULL Operator on Multiple Columns
Query:
SELECT *
FROM students
WHERE email IS NULL OR coding_score IS NULL;
Example 3: IS NULL with COUNT() Function
SELECT COUNT(*) AS count_empty_coding_score
FROM students
WHERE coding_score IS NULL;
Example 4: IS NULL with UPDATE Statement
Query:
UPDATE students
SET email = '[email protected]'
WHERE email IS NULL;
Example 5: IS NULL with DELETE Statement
Query:
DELETE FROM students
WHERE coding_score IS NULL;
Important Points About SQL IS NULL
 SQl IS NULL is used to detect any rows that contain a NULL value in
its column.
 IS NULL operator is mostly used with WHERE clause in SQL.
 We can use IS NULL operator on multiple columns using OR
operator.
 Using COUNT function we can count total number of NULL values in
SQL.
 We can UPDATE or DELETE the NULL values, after filtering them
with IS NULL operator.

SQL UNION Operator


The SQL UNION operator is used to combine the result sets of two or
more SELECT queries into a single result set.
The SQL UNION operator combines the results of two or more SELECT
statements into one result set. By default, UNION removes duplicate
rows, ensuring that the result set contains only distinct records.
There are some rules for using the SQL UNION operator.
Rules for SQL UNION
 Each table used within UNION must have the same number of
columns.
 The columns must have the same data types.
 The columns in each table must be in the same order.
Syntax:
The Syntax of the SQL UNION operator is:
SELECT columnnames FROM table1
UNION
SELECT columnnames FROM table2;
UNION operator provides unique values by default. To find duplicate values,
use UNION ALL.
Note: SQL UNION and UNION ALL difference is that UNION operator removes
duplicate rows from results set and
UNION ALL operator retains all rows, including duplicate.
Example 1: SQL UNION Operator
In this example, we will find the cities (only unique values) from both the
"Table1" and the "Table2" tables:
Query:
SELECT Country FROM Emp1
UNION
SELECT Country FROM Emp2
ORDER BY Country;
Example 2: SQL UNION ALL
In the below example, we will find the cities (duplicate values also) from
both tables
Query:
SELECT Country FROM Emp1
UNION ALL
SELECT Country FROM Emp2
ORDER BY Country;
SQL UNION ALL With WHERE
You can use the WHERE clause with UNION ALL in SQL. The WHERE clause
is used to filter records and is added after each SELECT statement
Example : SQL UNION ALL with WHERE
The following SQL statement returns the cities (duplicate values also) from
both the tables:
Query:
SELECT Country, Name FROM Emp1
WHERE Name='Aditya'
UNION ALL
SELECT Country, Name FROM Emp2
WHERE Country='Ireland'
ORDER BY Country;
Output:

Important Points About SQL UNION Operator


 The SQL UNION operator combines the result sets of two or more
SELECT queries.
 UNION returns unique rows, eliminating duplicate entries from the
result set.
 UNION ALL includes all rows, including duplicate rows.
 Columns in the result set must be in the same order and have the
same data types.
 UNION is useful for aggregating data from multiple tables or
applying different filters to data from the same table.

Feature UNION ALL UNION

Duplicate
Includes all duplicates Removes duplicate records
Records

Performan Faster, as it doesn't check for Slower, as it needs to


ce duplicates eliminate duplicates

When duplicates are acceptable When duplicates need to be


Use Case
or needed removed

SELECT columns FROM table1 SELECT columns FROM table1


Syntax UNION ALL SELECT columns FROM UNION SELECT columns FROM
table2; table2;

Memory Generally lower, since no extra Higher, due to additional


Usage processing for duplicates steps for duplicate removal
Feature UNION ALL UNION

Combined rows from Combined rows from


Result Set all SELECT statements, including all SELECT statements,
duplicates without duplicates

Useful for large datasets where Useful when data integrity


Applicabilit
performance is critical and requires unique records in
y
duplicates are acceptable the result set

SQL | Except Clause


The SQL EXCEPT operator is used to return the rows from the first SELECT
statement that are not present in the second SELECT statement. This
operator is conceptually similar to the subtract operator in relational
algebra. It is particularly useful for excluding specific data from your
result set.
Syntax:
SELECT column_name(s)
FROM table1
EXCEPT
SELECT column_name(s)
FROM table2;
Note: The two SELECT queries must return the same number of columns and
the data types must be compatible.
Example 1: Filter Student
We want to find all the students who are not teaching assistants.
Query:
SELECT Name
FROM Students
EXCEPT
SELECT Name
FROM TA;
Example 2: Retaining Duplicates with EXCEPTALL
By default, EXCEPT removes duplicates from the result set. To retain
duplicates, you can use EXCEPT ALL instead.
Query:
SELECT Name
FROM Students
EXCEPT SELECT Name
FROM TA;
SQL EXCEPT vs. SQL NOT IN
While both EXCEPT and NOT IN are used to exclude certain records, there
are important differences between them.
Feature EXCEPT NOT IN

Duplicate Removes duplicates from the Retains duplicates in the


Handling result result
Feature EXCEPT NOT IN

Generally more efficient for May be slower for large


Performanc
large datasets as it processes datasets, especially when
e
only the required rows checking multiple conditions

When you need to find rows When you need to check a


Use Case that exist in one result set but specific column’s values
not the other against a list

SQL Supported by most SQL


Not supported by MySQL
Support databases

Key Points to Remember


 EXCEPT returns rows from the first result set that are not in the
second result set.
 EXCEPT automatically removes duplicates, while EXCEPT
ALL retains duplicates.
 EXCEPT requires both queries to have the same number of columns
and compatible data types.
 EXCEPT is not supported in MySQL, while NOT IN can be used as an
alternative.
 Use EXCEPT when you need to exclude certain rows efficiently from
the first result set, especially in larger datasets.
SQL BETWEEN Operator
 The SQL BETWEEN operator is used to filter the result set within a
specified range.
 It can be applied to numeric, date, and text columns.
 The BETWEEN operator is inclusive, meaning it includes the start and
end values in the result set.
Syntax:
The basic syntax of the ' BETWEEN' operator is as follows:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Parameters:
 column_name(s): The name of the column(s) you want to retrieve
data from.
 table_name: The name of the table containing the data.
 column_name: The name of the column you want to apply
the BETWEEN filter to.
 value1: The starting value of the range.
 value2: The ending value of the range.
Example 1: NOT BETWEEN Text Values
Find employees whose last names are not alphabetically between 'B' and
'S'.
Query:
SELECT FirstName, LastName
FROM Employees
WHERE LastName NOT BETWEEN 'B' AND 'S';
Example 2: BETWEEN Dates
Query:
SELECT FirstName, LastName, HireDate
FROM Employees
WHERE HireDate BETWEEN '2020-01-01' AND '2021-12-31';
Example 3: NOT BETWEEN
Find employees whose age is not between 30 and 40.
Query:
SELECT FirstName, LastName, Age
FROM Employees
WHERE Age NOT BETWEEN 30 AND 40;
Example 4: BETWEEN with IN
Query:
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary BETWEEN 50000 AND 70000
AND FirstName IN ('John', 'Sue', 'Tom');
SQL ALL Operator
The ALL operator is used to compare a value with all the values returned
by a subquery. The condition will be evaluated to TRUE if the value meets
the specified condition for every value in the result set of the subquery.
 The ALL must be preceded by comparison operators and
evaluates true if all of the subqueries values meet the condition.
 ALL is used with SELECT, WHERE, and HAVING statements.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ALL
(SELECT column_name
FROM table_name
WHERE condition(s));
 comparison_operator: This is the comparison operator that can
be one of =, >, <, >=, <=, <>, etc.
 subquery: A query that returns the set of values to be compared
with the column in the outer query.
Example 1 : Retrieve all product names from the Products
table.
Query:
SELECT ALL ProductName
FROM Products
WHERE TRUE;
This query retrieves all product names from the Products table because
TRUE always evaluates as true for every row.
Example 2: Retrieve product names if all records in the
OrderDetails table have a quantity of 6 or 2.
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 6 OR Quantity = 2);
Example 3 : Find the OrderIDs where the maximum quantity
in the order exceeds the average quantity of all orders.
SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
HAVING MAX(Quantity) > ALL (SELECT AVG(Quantity)
FROM OrderDetails
GROUP BY OrderID);
SQL ANY Operator
ANY compares a value to each value in a list or results from a query and
evaluates to true if the result of an inner query contains at least one row.
 ANY return true if any of the subqueries values meet the condition.
 ANY must be preceded by comparison operators.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ANY
(SELECT column_name
FROM table_name
WHERE condition(s));
How to Use SQL ANY with SELECT, WHERE, and
HAVING
Example 1 : Find distinct category IDs of products that
appear in the OrderDetails table.
Query:
SELECT DISTINCT CategoryID
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails);
This query finds the distinct CategoryIDs of products that exist in the
OrderDetails table.
Example 2 : Find product names with a quantity of 9 in the
OrderDetails table.
Query:
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 9);
This query retrieves product names where at least one record in the
OrderDetails table has a quantity of 9.
Differences Between SQL ALL and ANY
 ALL requires that the condition be true for every value in the
subquery result, while ANY only needs the condition to be true for
at least one value in the subquery.
 ALL is used when you want to compare a value against all values in
the subquery, while ANY is useful when you want to compare a
value against any one of the values.
SQL INTERSECT
The INTERSECT statement will return only those rows that will be common
to both of the SELECT statements.
The INTERSECT returns only the records that exist in both queries, ensuring
uniqueness
Key Characteristics of SQL INTERSECT:
 Returns only the common rows between two result sets.
 Ensures uniqueness by automatically removing duplicate rows.
 Requires that both SELECT statements have the same number of
columns.
 The data types of corresponding columns in both queries must be
compatible.
Syntax:
SELECT column1 , column2 ....
FROM table1
WHERE condition
INTERSECT
SELECT column1 , column2 ....
FROM table2
WHERE condition
Example 1: Basic INTERSECT Query
Query:
SELECT CustomerID
FROM Customers
INTERSECT
SELECT CustomerID
FROM Orders;
Example 2: Using INTERSECT with BETWEEN Operator
Query:
SELECT CustomerID
FROM Customers
WHERE CustomerID BETWEEN 3 AND 8
INTERSECT
SELECT CustomerID
FROM Orders;
Example 3: Using INTERSECT with LIKE Operator
Query:
SELECT CustomerID
FROM Customers
WHERE FirstName LIKE 'J%'
INTERSECT
SELECT CustomerID
FROM Orders;
Important Notes About SQL INTERSECT
 Column Count & Data Types: Both SELECT statements must have
the same number of columns with compatible data types.
 Performance Considerations: INTERSECT can be slower on large
datasets as it performs row-by-row comparison. Indexing can help
optimize performance.
 NULL Handling: Unlike comparison
operators, INTERSECT treats NULL values as equal, meaning if both
queries return a row with NULL, it will be included in the result.
 Alternative Approach: In cases where INTERSECT is not supported
(e.g., MySQL), you can achieve the same result using INNER JOIN.
SQL | EXISTS
The EXISTS condition is primarily used to check the existence of rows
returned by a subquery. It’s commonly used in scenarios where you need
to check if a record exists in a related table, and you want to perform an
action based on that result.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS (
SELECT column_name(s)
FROM subquery_table
WHERE condition
);
 EXISTS: The boolean operator that checks if a subquery returns
rows.
 Subquery: A nested SELECT query that returns data for evaluation.
 Condition: The condition applied to the subquery.
Example 1 : Using EXISTS with SELECT
To fetch the first and last name of the customers who placed atleast one
order.
Query:
SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Example 2 : Using NOT with EXISTS
Fetch last and first name of the customers who has not placed any order.
SELECT lname, fname
FROM Customers
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Example 3 : Using EXISTS condition with DELETE statement
Delete the record of all the customer from Order Table whose last name is
'Mehra'.
DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.c_id
AND Customers.lname = 'Mehra');
SELECT * FROM Orders;

Example 4 : Using EXISTS condition with UPDATE statement


Update the lname as 'Kumari' of customer in Customer Table whose
customer_id is 401.
UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);
SELECT * FROM Customers;
When to Use SQL EXISTS
The EXISTS condition is particularly useful in the following scenarios:
 Checking Data Existence: You can use EXISTS to check if
related data exists in another table before performing an action
(e.g., selecting, updating, deleting).
 Performance: EXISTS is often more efficient than using IN when
dealing with large datasets, as it stops searching once a match is
found.
 Correlated Subqueries: EXISTS is ideal for
correlated subqueries, where the subquery refers to the outer
query’s values.
Differences Between EXISTS and IN
 EXISTS is used for checking the existence of rows, while IN checks
if a value matches any value from a list or subquery result.
 EXISTS is more efficient when the subquery results in a large
number of rows.
 IN works well for small datasets or static lists of values.
SQL CASE Statement
The CASE statement in SQL is a versatile conditional expression that
enables us to incorporate conditional logic directly within our queries. It
allows you to return specific results based on certain conditions, enabling
dynamic query outputs. Whether you need to create new columns,
modify existing ones, or customize the output of your queries, the CASE
statement can handle it all.
 The CASE statement in SQL is a conditional expression that allows
you to perform conditional logic within a query.
 It is commonly used to create new columns based on conditional
logic, provide custom values, or control query outputs based on
certain conditions.
 If no condition is true then the ELSE part will be executed. If there
is no ELSE part then it returns NULL.
Syntax:
CASE case_value
WHEN condition THEN result1
WHEN condition THEN result2
...
Else result
END CASE;
Example 1: Simple CASE Expression
In this example, we use CASE statement
Query:
SELECT CustomerName, Age,
CASE
WHEN Country = "India" THEN 'Indian'
ELSE 'Foreign'
END AS Nationality
FROM Customer;
Example 2: SQL CASE When Multiple Conditions
We can add multiple conditions in the CASE statement by using
multiple WHEN clauses.
Query:
SELECT CustomerName, Age,
CASE
WHEN Age> 22 THEN 'The Age is greater than 22'
WHEN Age = 21 THEN 'The Age is 21'
ELSE 'The Age is over 30'
END AS QuantityText
FROM Customer;
Example 3: CASE Statement With ORDER BY Clause
Let's take the Customer Table which contains CustomerID, CustomerName,
LastName, Country, Age, and Phone. We can check the data of the
Customer table by using the ORDER BY clause with the CASE statement.
Query:
SELECT CustomerName, Country
FROM Customer
ORDER BY
(CASE
WHEN Country IS 'India' THEN Country
ELSE Age
END);
Important Points About CASE Statement
 The SQL CASE statement is a conditional expression that allows for
the execution of different queries based on specified conditions.
 There should always be a SELECT in the CASE statement.
 END ELSE is an optional component but WHEN THEN these cases
must be included in the CASE statement.
 We can make any conditional statement using any conditional
operator (like WHERE ) between WHEN and THEN. This includes
stringing together multiple conditional statements using AND and
OR.
 We can include multiple WHEN statements and an ELSE statement
to counter with unaddressed conditions.
SQL Aggregate functions
SQL Aggregate Functions are used to perform calculations on multiple
rows of data and return a single summarized result. These functions are
typically used with the GROUP BY clause to organize data into groups, where
we can then perform calculations like summing, averaging, or counting.
Aggregate functions allow you to make sense of large datasets by
collapsing them into meaningful summaries.
Key Features of SQL Aggregate Functions:
 Operate on groups of rows: They work on a set of rows and
return a single value.
 Ignore NULLs: Most aggregate functions ignore NULL values,
except for COUNT(*).
 Used with GROUP BY: To perform calculations on grouped data, you
often use aggregate functions with GROUP BY.
 Can be combined with other SQL clauses: Aggregate functions
can be used alongside HAVING, ORDER BY, and other SQL clauses to
filter or sort results.
Commonly Used SQL Aggregate Functions
Below are the most frequently used aggregate functions in SQL.
1. Count()
The COUNT() function returns the number of rows that match a given
condition or are present in a column.
 COUNT(*): Counts all rows.
 COUNT(column_name) : Counts non-NULL values in the specified column.
 COUNT(DISTINCT column_name) : Counts unique non-NULL values in the
column.
Examples:
-- Total number of records in the table
SELECT COUNT(*) AS TotalRecords FROM Employee;

-- Count of non-NULL salaries


SELECT COUNT(Salary) AS NonNullSalaries FROM Employee;

-- Count of unique non-NULL salaries


SELECT COUNT(DISTINCT Salary) AS UniqueSalaries FROM Employee;
2. SUM()
The SUM() function calculates the total sum of a numeric column.
 SUM(column_name): Returns the total sum of all non-NULL values in a
column.
Examples:
-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;

-- Calculate the sum of unique salaries


SELECT SUM(DISTINCT Salary) AS DistinctSalarySum FROM Employee;
3. AVG()
The AVG()function calculates the average of a numeric column. It divides
the sum of the column by the number of non-NULL rows.
 AVG(column_name): Returns the average of the non-NULL values in the
column.
Examples:
-- Calculate the average salary
SELECT AVG(Salary) AS AverageSalary FROM Employee;

-- Average of distinct salaries


SELECT AVG(DISTINCT Salary) AS DistinctAvgSalary FROM Employee;
4. MIN() and MAX()
The MIN() and MAX() functions return the smallest and largest values,
respectively, from a column.
 MIN(column_name): Returns the minimum value.
 MAX(column_name): Returns the maximum value.
Examples:
-- Find the highest salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;

-- Find the lowest salary


SELECT MIN(Salary) AS LowestSalary FROM Employee;

SQL Data Constraints

SQL NOT NULL Constraint


 NOT NULL is used to enforce mandatory fields.
 It prevents NULL values from being inserted or updated.
 It is applicable at the column level.
 It can be used during table creation or modification (with the ALTER
command).
Syntax:
CREATE TABLE table_Name
(
column1 data_type(size) NOT NULL,
column2 data_type(size) NOT NULL,
....
);
SQL NOT NULL on CREATE a Table
In SQL, we can add NOT NULL constraints while creating a table.
For example, the "EMPID" will not accept NULL values when
the EMPLOYEES table is created because NOT NULL constraints are used
with these columns.
Query:
CREATE TABLE Emp(
EmpID INT NOT NULL PRIMARY KEY,
Name VARCHAR (50),
Country VARCHAR(50),
Age int(2),
Salary int(10));
SQL NOT NULL on ALTER Table
We can also add a NOT NULL constraint in the existing table using
the ALTER statement. For example, if the EMPLOYEES table has already
been created then add NOT NULL constraints to the "Name" column
using ALTER statements in SQL as follows:
Query:
ALTER TABLE Emp modify Name Varchar(50) NOT NULL;
This command ensures that the Name column will no longer accept NULL
values, enforcing a requirement for all employee records to have a valid
name.
SQL | UNIQUE Constraint
The SQL UNIQUE constraint ensures that all values in a column or a set
of columns are different from one another. It can be applied to one or more
columns in a table. When applied, the database will reject any insert or
update operation that would create a duplicate value in the specified
column(s).
The UNIQUE constraint allows NULL values, and multiple NULL values are
allowed in a column with a UNIQUE constraint because NULL is considered
a distinct value in SQL
Syntax:
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
...
);
Example 1: Creating a Table with UNIQUE Constraints
Let's create a Customers table where the Email column must be unique.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100) UNIQUE,
Country VARCHAR(50)
);
Example 2: Using UNIQUE with Multiple Columns
We can also apply the UNIQUE constraint to multiple columns to
ensure that the combination of those columns is unique.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
ProductID INT,
OrderDate DATE,
UNIQUE (CustomerID, ProductID)
);
Example 3: Checking for Unique Values Using Subqueries
SQL allows you to check for uniqueness in subqueries. You can use the
UNIQUE keyword in a subquery to ensure that the results do not contain
duplicate values.
SELECT CustomerID
FROM Orders
WHERE UNIQUE (
SELECT OrderID
FROM OrderDetails
WHERE Orders.CustomerID = OrderDetails.CustomerID
);
SQL PRIMARY KEY Constraint
1. No duplicate values are allowed, i.e. The column assigned as the
primary key should have UNIQUE values only.
2. NO NULL values are present in the Primary key column. Hence
there is a Mandatory value in the column having the Primary key.
3. Only one primary key per table exists although the Primary key
may have multiple columns.
4. No new row can be inserted with the already existing primary key.
5. Primary keys can be classified into two categories Simple primary
key that consists of one column and composite primary key that
consists of Multiple column.
6. Defined in CREATE TABLE or ALTER TABLE statement.
Syntax
There are two syntaxes to create/add primary key to a table:
 Using CREATE TABLE Statement
 Using ALTER TABLE Statement
SQL PRIMARY KEY with CREATE TABLE
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...,
CONSTRAINT pk_constraint_name PRIMARY KEY (column1, column2, ...)
);
Query
CREATE TABLE Persons (
PersonID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

SQL PRIMARY KEY with ALTER TABLE


ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (PersonID);
SQL FOREIGN KEY
A FOREIGN KEY is a column or set of columns in one table that references
the primary key columns of another table. This creates
a relationship between the two tables, ensuring that the child table
(which contains the foreign key) can only have values that exist in the
parent table's primary key column(s).
The table containing the foreign key is called the foreign table (or child
table), and the table that the foreign key references is called the primary
table (or parent table).
The primary purpose of a foreign key is to maintain referential integrity,
ensuring that the relationship between tables is consistent and that invalid
data does not enter the system.
Syntax:
A foreign key can be created during table creation using CREATE
TABLE statement or it can be added to a table later using ALTER
TABLE statement
SQL FOREIGN KEY on CREATE TABLE
The syntax to create a foreign key in CREATE TABLE statement is:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...,
CONSTRAINT fk_constraint_name FOREIGN KEY (column1, column2, ...)
REFERENCES parent_table(column1, column2, ...)
);
SQL FOREIGN KEY on ALTER TABLE
The syntax to add a foreign key with ALTER TABLE statement is:
ALTER TABLE table_name
ADD CONSTRAINT fk_constraint_name FOREIGN KEY (column1,
column2, ...)
REFERENCES parent_table(column1, column2, ...);
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50) NOT NULL
);

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
OrderNumber INT NOT NULL,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

Composite Key in SQL


 A composite key is formed from multiple columns.
 It ensures uniqueness when the combined values of the columns
are considered together.
 None of the columns involved in a composite key can be NULL.
 The composite key helps in tables where single columns cannot
guarantee uniqueness, but a combination of columns can.
When to Use a Composite Key?
A composite key is useful in situations where:
 A single column cannot uniquely identify a row, but a combination of
columns can.
 You need to enforce a relationship between two or more attributes.
 You want to maintain data integrity by ensuring that the combination
of columns remains unique.
CREATE TABLE student
(rollNumber INT,
name VARCHAR(30),
class VARCHAR(30),
section VARCHAR(1),
mobile VARCHAR(10),
PRIMARY KEY (rollNumber, mobile));
SQL - ALTERNATE KEY
Alternate Key is any candidate key not selected as the primary key. So,
while a table may have multiple candidate keys (sets of columns that could
uniquely identify rows), only one of them is designated as the Primary Key.
The rest of these candidate keys become Alternate Keys.
1. A Primary Key can't be an Alternate Key. For a table with a single
Candidate Key which has to be the Primary Key will not contain any
Alternate Key.
2. A Foreign Key can't be an Alternate Key as it is only used to
reference another table.
3. The alternate Key should be unique.
4. An Alternate Key can be a set of a single attribute or multiple
attributes.
5. It can be NULL as well.
In the Customer Information Table, Customer ID, Pan Number, Email
Address are unique as it can uniquely identify a row in the given table.
PAN Number is unique for every person and Customer ID is also a unique
number provided by E-Commerce sites to distinguish among tons of
customers registered in their shopping site.
A user can register on the shopping site using only a single E-Mail Address.
If he/she wants to create another account using the same E-Mail will show a
message, "An account with this E-Mail Address already exists, Please
Login". So, every consumer will have a unique E-Mail Address. Hence, all
these attributes can uniquely identify a row in a table.
The candidate key set for the above table is : { Customer ID, Pan Number,
Email Address }
CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint,
col_3 TYPE UNIQUE,
col_4 TYPE REFERENCES Table_Name(col_name),
.....
)

col: The name of the columns.


TYPE: Data type whether an integer, variable character, etc
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE,
REFERENCES, etc.
col_3: Defining an ALTERNATE KEY using constraint UNIQUE
col_4: Defining an FOREIGN KEY using constraint REFERENCES
Feature Primary Key Alternate Key

Uniqueness Must be unique Must be unique


Feature Primary Key Alternate Key

Cannot contain NULL


Null Values Can contain NULL values
values

Used to identify each An alternate option for


Use
row uniquely uniqueness

Relationship with The selected Other candidate keys not


Candidate Key candidate key selected as primary

One primary key per Multiple alternate keys


Number of Keys
table possible

SQL CHECK Constraint


The CHECK constraint in SQL is used to limit the range or set of values that
can be inserted into a column. It ensures that the data entered into a
column meets a certain condition or rule. The CHECK constraint can be
applied to a column when the table is created or altered. If any data being
inserted or updated violates the CHECK condition, the database will return
an error and the operation will be prevented.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype CHECK (condition),
...
);
Key Points About the CHECK Constraint
 Domain Integrity: It ensures that the values in a column meet
specified conditions, thus helping maintain valid data in the
database.
 Used with CREATE or ALTER: The CHECK constraint can be
defined when creating a table or added to an existing table.
 Can Be Combined with Other Constraints: You can use CHECK
along with other constraints like PRIMARY KEY, FOREIGN KEY, and
NOT NULL to define more comprehensive rules for the table data.
 Row-level Constraints: Unlike column-level constraints that
affect individual columns, a CHECK constraint can apply to multiple
columns at once if needed.
Example 1: Applying CHECK on a Single Column
Query:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT CHECK (Age >= 18 AND Age <= 120)
);

-- Valid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (1, 'John Doe', 25);

-- Invalid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (2, 'Jane Smith', 15); -- This will fail due to the CHECK
constraint
Example 2: CHECK Constraint with Multiple Columns
Query:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Salary DECIMAL(10, 2),
CHECK (Age >= 18 AND Salary > 0)
);

-- Valid insert
INSERT INTO Employee (EmployeeID, Name, Age, Salary)
VALUES (1, 'Alice Johnson', 30, 50000);

-- Invalid insert (age < 18)


INSERT INTO Employee (EmployeeID, Name, Age, Salary)
VALUES (2, 'Bob Lee', 16, 45000); -- This will fail due to the CHECK
constraint
Example 3: Adding a CHECK Constraint with ALTER TABLE
Query:
ALTER TABLE Employee
ADD CONSTRAINT chk_salary CHECK (Salary >= 30000);
SQL DEFAULT Constraint
The DEFAULT constraint in SQL is used to provide a default value for a
column when no value is specified during an INSERT operation. If a
column has a DEFAULT constraint and no value is explicitly provided
during the insertion of a record, the database will automatically insert the
default value defined for that column.
Syntax :
CREATE TABLE table_name (
column1 datatype DEFAULT default_value,
column2 datatype DEFAULT default_value,
...
);
Key Points About the DEFAULT Constraint
 Automatic Value Insertion: The DEFAULT constraint ensures
that if a value is not supplied during insertion, a pre-defined default
value is used.
 Simplifies Data Entry: It simplifies data entry when certain fields
often have common or default values.
 Optional in SQL: The DEFAULT constraint is optional. Not all
columns require a default value.
 Can Be Applied to Any Data Type: It can be applied to any data
type, including numbers, dates, and strings.
 Not Applicable to NULL: You cannot use the DEFAULT constraint
to assign NULL as a default value. For null values, you can either
omit the value or explicitly specify NULL.
Using the DEFAULT Constraint during Table
Creation
Let’s create a table and use the DEFAULT constraint for the Location
column, ensuring that a default value of 'Noida' is inserted when no value is
provided.
Query:
CREATE TABLE Geeks (
ID INT NOT NULL,
Name VARCHAR(255),
Age INT,
Location VARCHAR(255) DEFAULT 'Noida'
);

-- Explicit value
INSERT INTO Geeks (ID, Name, Age, Location) VALUES (4, 'Mira', 23,
'Delhi');

-- Using the DEFAULT constraint


INSERT INTO Geeks (ID, Name, Age, Location) VALUES (5, 'Hema', 27);

-- Explicit value again


INSERT INTO Geeks (ID, Name, Age, Location) VALUES (6, 'Neha', 25,
'Delhi');

-- Using DEFAULT constraint again


INSERT INTO Geeks (ID, Name, Age, Location) VALUES (7, 'Khushi', 26,
DEFAULT);
Dropping the DEFAULT Constraint
Syntax:
ALTER TABLE tablename
ALTER COLUMN columnname
DROP DEFAULT;
Query:
ALTER TABLE Geeks
ALTER COLUMN Location
DROP DEFAULT;

SQL Joins
An SQL JOIN clause is used to query and access data from multiple tables
by establishing logical relationships between them. It can access data
from multiple tables simultaneously using common key values shared
across different tables.
1. SQL INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as
the condition is satisfied. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e
value of the common field will be the same.

Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.

Query:
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

2. SQL LEFT JOIN


A LEFT JOIN returns all rows from the left table, along with matching rows
from the right table. If there is no match, NULL values are returned for
columns from the right table. LEFT JOIN is also known as LEFT OUTER
JOIN.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the
same.

LEFT JOIN Example


In this example, the LEFT JOIN retrieves all rows from the Student table
and the matching rows from the StudentCourse table based on
the ROLL_NO column.
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
3. SQL RIGHT JOIN
RIGHT JOIN returns all the rows of the table on the right side of the
join and matching rows for the table on the left side of the join. It is very
similar to LEFT JOIN for the rows for which there is no matching row on the
left side, the result-set will contain null. RIGHT JOIN is also known
as RIGHT OUTER JOIN.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Key Terms
 table1: First table.
 table2: Second table
 matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both
are the same.

RIGHT JOIN Example


In this example, the RIGHT JOIN retrieves all rows from
the StudentCourse table and the matching rows from the Student table
based on the ROLL_NO column.
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
4. SQL FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both
tables. For the rows for which there is no matching, the result-set will
contain NULL values.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Key Terms
 table1: First table.
 table2: Second table
 matching_column: Column common to both the tables.
FULL JOIN Example
This example demonstrates the use of a FULL JOIN, which combines the
results of both LEFT JOIN and RIGHT JOIN. The query retrieves all rows
from the Student and StudentCourse tables. If a record in one table does
not have a matching record in the other table, the result set will include
that record with NULL values for the missing fields
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
5. SQL Natural Join (?)
Natural join can join tables based on the common columns in the tables
being joined. A natural join returns all rows by matching values in common
columns having same name and data type of columns and that column
should be present in both tables.
 Both table must have at least one common column with same
column name and same data type.
 The two table are joined using Cross join.
 DBMS will look for a common column with same name and data
type. Tuples having exactly same values in common columns are
kept in result.

You might also like