0% found this document useful (0 votes)
10 views787 pages

SQL Tutorial

SQL (Structured Query Language) is the standard language for managing and interacting with relational databases, allowing users to perform operations such as creating, updating, and querying data. The tutorial covers essential SQL concepts, including writing queries, database management, data types, and advanced topics like joins, functions, and security. It also highlights the importance of SQL in various fields such as data science, web development, and machine learning, along with potential career opportunities and average salaries.

Uploaded by

Ajay gadiparthi
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)
10 views787 pages

SQL Tutorial

SQL (Structured Query Language) is the standard language for managing and interacting with relational databases, allowing users to perform operations such as creating, updating, and querying data. The tutorial covers essential SQL concepts, including writing queries, database management, data types, and advanced topics like joins, functions, and security. It also highlights the importance of SQL in various fields such as data science, web development, and machine learning, along with potential career opportunities and average salaries.

Uploaded by

Ajay gadiparthi
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/ 787

SQL Tutorial

Structured Query Language (SQL) is the standard language used to interact


with relational databases.

 Mainly used to manage data. Whether you want to create, delete,


update or read data, SQL provides commands to perform these
operations.

 Widely supported across various database systems like MySQL, Oracle,


PostgreSQL, SQL Server and many others.

 Mainly works with Relational Databases (data is stored in the form of


tables)

Writing First SQL Query

Before running SQL queries you need to set up a database server like MySQL,
PostgreSQL or SQLite. Here, we are going to use MySQL server. Follow below
steps to set up a basic SQL Environment:

1. Install MySQL in your system

2. Start MySQL Server

3. Access MySQL Command Line

After your MySQL environment is set up, you can write your SQL program.
Below is the example to display " Hello World" using SQL.

1. Create a database named test_db

CREATE DATABASE test_db;

2. Use the test_db database

USE test_db;
3. Create a table named greetings

CREATE TABLE greetings (


id INT AUTO_INCREMENT PRIMARY KEY,
message VARCHAR(255)
);

3. Insert the message 'Hello, World!' into the greetings table

INSERT INTO greetings (message)


VALUES ('Hello, World!');

4. Retrieve the message from the greetings table

SELECT message FROM greetings;

Note: Try replacing "Hello World!" with your name in the SQL query. It's a
fun way to see how databases store and display your own data! Give it a try
and watch your name pop up!

Why Learn SQL?

SQL's integration with various technologies makes it essential for managing


and querying data in databases. Whether it is in traditional relational
databases (RDBMS) or modern technologies such as machine learning, AI
and blockchain, SQL plays a key role. It works effortlessly with DBMS to help
users interact with data, whether stored in structured RDBMS or other types
of databases.

 Data Science & Analytics: Used for querying large datasets, data
cleaning and analysis. Analysts use SQL to generate reports and
insights that inform business decisions.

 Machine Learning & AI: Helps in preparing and managing the data
required for training machine learning models and AI algorithms. It is
used for data cleaning, transformation, and extraction.

 Web Development: Used to manage user data, e-commerce


transactions, and content management in websites and applications
built with frameworks like Django, Node.js, and Ruby on Rails.

 Cloud and Big Data: SQL is integrated into cloud-based databases


(e.g., Amazon RDS, Microsoft Azure SQL) and Big Data platforms (e.g.,
Apache Hive) to enable seamless data querying and management.
 Blockchain and Decentralized Systems: In blockchain systems,
SQL can be used to manage off-chain data, providing efficient data
storage and retrieval alongside decentralized ledger technology

SQL Basics

Learn the foundational concepts of SQL, essential for anyone working with
relational databases. This section covers the syntax, commands, and key
elements to start querying and managing data effectively.

 Introduction

 Data Types

 Operators

 Commands

SQL Database

This section guides you through the process of creating and managing
databases. Learn how to create, select, rename, and drop databases with
practical examples.

 CREATE Database

 DROP Database

 RENAME Database

 SELECT Database

SQL Tables

Tables are the core data structures in databases, organizing data into rows
and columns. This section covers how to create, modify, and manage tables
effectively.

 CREATE TABLE

 DROP TABLE

 RENAME TABLE

 TRUNCATE TABLE

 COPY TABLE

 TEMP TABLE
 ALTER TABLE

SQL Queries

Master writing SQL queries to interact with and manipulate data stored in
your tables. This section covers common query types and operations.

 SELECT Statement

 INSERT INTO

 INSERT Multiple Rows

 UPDATE Statement

 DELETE Statement

 DELETE Duplicate Rows

SQL Clauses

Unlock powerful ways to filter, organize, and group your query results.
Clauses help you refine your data extraction.

 WHERE Clause

 WITH Clause

 HAVING Clause

 ORDER By Clause

 Group By Clause

 LIMIT Clause

 Distinct Clause

 FETCH

 Aliases

SQL Operators

SQL Operators" refers to the fundamental symbols and keywords within the
SQL that enable users to perform various operations. Operators let you build
complex query conditions.

 AND Operator

 OR Operator
 Logical Operators

 LIKE Operator

 IN Operator

 NOT Operator

 NOT EQUAL Operator

 IS NULL Operator

 UNION Operator

 UNION ALL Operator

 EXCEPT Operator

 BETWEEN Operator

 ALL and ANY

 INTERSECT Operator

 EXISTS Operator

 CASE Operator

SQL Aggregate Functions

Whether you are calculating the total sales revenue for a particular product,
finding the average age of customers, or determining the highest value in a
dataset, SQL Aggregate Functions make these tasks straightforward and
manageable.

 Aggregate Function

 Count() Function

 SUM() Function

 MIN() Function

 MAX() Function

 AVG() Function

Data Constraints

Constraints act as rules or conditions imposed on the data, dictating what


values are permissible and what actions can be taken. They play a crucial
role in maintaining the quality and coherence of the database by preventing
errors.

 NOT NULL Constraints

 Primary Key Constraints

 Foreign Key Constraints

 Composite Key

 Unique Constraints

 Alternate Key

 CHECK Constraints

 DEFAULT Constraints

SQL Joins

SQL joins serve as the weaver's tool, allowing you to seamlessly merge data
from multiple tables based on common threads. So explore this section to
learn how to use JOIN command.

 JOIN

 Outer Join

 Left Join

 Right Join

 Full Join

 Cross Join

 Self Join

 UPDATE with JOIN

 DELETE JOIN

 Recursive Join

SQL Functions

SQL functions offer an efficient and versatile approach to data analysis.


Enhance your queries with built-in functions that manipulate data types and
perform calculations.
 Date Functions

 String Functions

 Numeric Functions

 Statistical Functions

 JSON Functions

 Conversion Functions

 Datatype Functions

 LTRIM Function

 UPPER Function

 RTRIM Function

SQL Views

Views simplify complex queries and improve security by controlling data


access. Views also act like a helpful security guard, keeping the most
sensitive information in the back room, while still allowing access to what's
needed.

 CREATE VIEW

 UPDATE VIEW

 RENAME VIEW

 DROP VIEW

SQL Indexes

Improve query performance by creating indexes that speed up data retrieval.

 Indexes

 Create Index

 Drop Index

 Show Indexes

 Unique Index

 Clustered Index vs Non-Clustered Index

SQL Subquery
Perform queries within queries to solve complex data retrieval problems.
They help in filtering data or performing operations on data that would
otherwise require multiple queries.

 Subquery

 Correlated Subqueries

 Nested Queries

Miscellaneous Topics

Explore advanced and useful SQL concepts to deepen your knowledge

 Wildcards Operators

 Comments

 Pivot and Unpivot

 Trigger

 Hosting

 Performance Tuning

 Stored Procedures

 Transactions

 Sub Queries

 Using Sequences

 Auto Increment

 Window functions

 Cursors

 Common Table Expressions

 Database Tuning

 Dynamic

 Regular Expressions

Exercises, Interview Questions & Cheat Sheet


This section provides practical exercises and commonly asked interview
questions to help strengthen your SQL knowledge. It also includes a cheat
sheet for quick reference, making SQL concepts easier to grasp.

 Exercises

 Quiz

 Interview Questions

 Query Interview Questions

 Cheat Sheet

 30 Days of SQL – From Basic to Advanced

Advanced SQL & Databases

Advanced SQL topics explore techniques like optimization, complex joins,


and working with large-scale databases. This section also covers the use of
advanced functions and stored procedures to handle advanced database
operations.

Database Design and Modeling

Database design focuses on creating an efficient database structure that is


scalable and meets user requirements. Modeling involves defining
relationships, entities, and constraints to ensure data integrity and efficient
querying.

 Introduction of ER Model

 How to Draw Entity Relationship Diagrams (ERDs)

 Mapping from ER Model to Relational Model

 Introduction of Database Normalization

 Functional Dependency and Attribute Closure

 Types of Functional dependencies

 Rules of Inference

 Normal Forms in DBMS

 Denormalization in Databases

 Database Design
Database Security

Database security protects data from unauthorized access, corruption, and


breaches. It includes encryption, authentication, and user privilege
management to safeguard sensitive information stored in databases.

 Injection

 Types of SQL Injection

 Data Encryption

 Database Recovery Techniques in DBMS

 Backup

 How to Restore SQL Server Database From Backup?

Database Connectivity

Database connectivity enables applications to interact with databases


through established protocols and drivers. This section covers how to
establish secure connections and manage database interactions in
programming languages like PHP, Python, and Java.

 ORM (Object-Relational Mapping)

 ODM (Object-Document Mapping)

 ODBC (Open Database Connectivity)

Career & Job Opportunities in SQL

While SQL is a key skills for various roles in the tech industry, but it is
important to understand that most of the positions listed below require more
than just SQL knowledge. To increase your chances of landing high paying
roles at top companies, you should have strong foundation in other
databases, Data Management tools and related technologies.

Here we have listed the best career opportunities anyone can pursue after
learning SQL.

Average Salary Average Salary


Career Role (INR) per Annum (USD) per Annum

SQL Developer ₹4,50,000 – $84,276 – $153,107


Average Salary Average Salary
Career Role (INR) per Annum (USD) per Annum

₹11,30,000

Database ₹4,00,000 –
$90,000 – $131,060
Administrator (DBA) ₹10,00,000

₹4,00,000 –
Data Analyst $85,500
₹9,00,000

₹8,00,000 –
Data Scientist $70,000 – $130,000
₹25,00,000

₹6,00,000 –
ETL Developer $85,500
₹14,00,000

Business Intelligence ₹7,00,000 –


$107,870
(BI) Developer ₹20,00,000

₹5,50,000 –
SQL Server Developer $104,864
₹13,00,000

₹10,00,000 –
Big Data Engineer $125,003 – $300,000
₹30,00,000

₹7,00,000 –
Software Consultant $100,000 – $150,000
₹20,00,000
Average Salary Average Salary
Career Role (INR) per Annum (USD) per Annum

.NET Developer (with ₹4,50,000 –


$100,000 – $120,000
SQL) ₹12,00,000

Applications of SQL

SQL plays an important role in data-driven industries where efficient


database management is crucial. Its versatility makes it applicable in various
architectural models and operational domains, including:

 Client/Server Architecture: Connects front-end and back-end


systems for smooth data exchange.

 Three-Tier Architecture: Supports interaction between client,


application server, and database.

 Data Definition Language (DDL): Create, modify, and delete


database structures.

 Data Manipulation Language (DML): Insert, update, delete, and


retrieve data.

 Data Control Language (DCL): Manage database access and


security permissions.

Latest Trend [2025]: SQL Server 2025 introduces AI-driven features


directly within the SQL engine. It supports native vector data types and AI
model management, allowing developers to run AI tasks directly in SQL
without external tools.

Quick Links:

 SQL | Multiple Choice Questions

 SQL | Interview Questions

 SQL Interview Questions | Set 1

 SQL Interview Questions | Set 2

 SQL | Commonly asked DBMS interview questions | Set 1

 SQL | Commonly asked DBMS interview questions | Set 2


What is SQL?

Structured Query Language (SQL) is the standard language used to interact


with relational databases.

 It allows users to store, retrieve, update and manage data efficiently


through simple commands.

 It is known for its user-friendly syntax and powerful capabilities, SQL is


widely used across industries.
How Does SQL Work?

We interact with databases using SQL queries. DBMS tools like MySQL and
SQL Server have their own SQL engine and an interface where users can
write and execute SQL queries.

Below are the detailed steps involved in the SQL query execution.

1. Input: The user submits a query (e.g., SELECT, INSERT, UPDATE,


DELETE) via an application or interface.

2. Parsing: The query processor breaks the query into parts (tokens) and
checks for syntax and schema correctness.

3. Optimization: The optimizer finds the most efficient way to run the
query using indexes, statistics and available resources.

4. Execution: The execution engine runs the query using the chosen
plan, accessing or modifying the database as needed.

5. Output: Results are returned to the user, either data (for SELECT) or a
success message (for other operations).

Key Components of a SQL System

 Databases : A database is a structured collection of data. It organizes


data into tables, which are like spreadsheets with rows (records) and
columns (fields) .

 Tables: Each table enforces rules and relationships among its columns
for data integrity.
 Indexes: Indexes speed up queries by allowing the database to quickly
locate data without scanning the entire table.

 Views: A view is a virtual table basically a saved SELECT statement


you can query like a table.

 Stored Procedures: These are pre-written SQL scripts stored inside


the database. They can receive inputs, run complex logic and return
results boosting performance, reusability and security.

 Transactions: A transaction groups multiple SQL operations into a


single unit. It ensures all changes are applied successfully or none are,
preserving data integrity (ACID properties)

 Security and Permissions: SQL includes tools to restrict access,


letting DBAs assign who can do what whether it's accessing tables,
executing procedures, or changing structures.

 Joins: Joins combine data from multiple tables based on relationships


essential for querying across related datasets.

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.

 End with Semicolon (;): Each SQL statement must end with a
semicolon to execute properly.

 Case Insensitivity: SQL keywords (e.g., SELECT, INSERT) are not


case-sensitive. However, table or column names may be case-sensitive
depending on the DBMS.

 Whitespace Allowed: Queries can span multiple lines, but use spaces
between keywords and names.

 Reserved Words: Avoid using SQL keywords as names. If needed,


wrap them in quotes (" ") or backticks (`).

Comments

 Single-line: -- comment

 Multi-line: /* comment */
Data Constraints: Use NOT NULL, UNIQUE, PRIMARY KEY, etc., to ensure
data accuracy.

String Values: Enclose strings in single quotes ('text').

Naming Rules:

 We Start with a letter

 We can only use Max 30 characters

 We only use letters, numbers and underscores (_)

What are Different SQL Commands or Queries?

Structured Query Language (SQL) commands are standardized instructions


used by developers to interact with data stored in relational databases.
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. Data Definition Language

These commands are used to define the structure of database objects


by creating, altering and dropping the database objects. Based on the
needs of the business, database engineers create and modify database
objects using DDL. The CREATE command, for instance, is used by the
database engineer to create database objects like tables, views and indexes.

Comman
d Description

Creates a new table, a view on a table, or some other object in


CREATE the database.

ALTER Modifies an existing database object, such as a table

Deletes an entire table, a view of a table, or other objects in the


DROP database

TRUNCA Removes all records from a table but keeps the table structure
TE intact.
2. Data Manipulation Language

A relational database can be updated with new data using data manipulation
language (DML) statements. The INSERT command, for instance, is used by
an application to add a new record to the database.

Comma
nd Description

Creates a
INSERT record.

Modifies
UPDATE records.

Deletes
DELETE records.

3. Data Query Language

Data retrieval instructions are written in the data query language (DQL),
which is used to access relational databases. The SELECT command is used
by software programs to filter and return particular results from a SQL table.

4. Data Control language

DCL commands manage user access to the database by granting or revoking


permissions. Database administrators use DCL to enforce security and
control access to database objects.

Comma
nd Description

GRANT Gives a privilege to the user.

Takes back privileges granted by


REVOKE the user.
5. Transaction Control Language

TCL commands manage transactions in relational databases, ensuring data


integrity and consistency. These commands are used to commit changes or
roll back operations in case of errors.

Command Description

Saves all changes made during the current


transaction on a permanent basis. Some
databases provide an auto-commit feature,
COMMIT which can be configured using settings.

Reverts changes made during the current


transaction, ensuring no unwanted changes
ROLLBACK are saved.

Sets a point within a transaction to which


changes can be rolled back, allowing partial
SAVEPOINT rollbacks

Benefits of SQL

 Efficiency: SQL is designed to handle complex queries and large


datasets with optimal performance, making data retrieval and
manipulation seamless.

 Standardization: As an ANSI and ISO standard language, SQL


provides a universal method to interact with relational databases
across platforms.

 Scalability: SQL supports databases ranging from small-scale


applications to enterprise-level systems, ensuring smooth operations
regardless of size.

 Flexibility: SQL can be extended with procedural programming (e.g.,


PL/SQL, T-SQL) to build complex business logic and custom functions.

Limitations of SQL
 Complexity in Advanced Operations: Advanced functionalities such
as indexing, query optimization and performance tuning require in-
depth technical knowledge.

 Scalability Concerns: SQL performs best with structured data but


handling unstructured data or massive distributed systems can pose
challenges.

 Platform-Specific Variations: While SQL is standardized, many


databases implement unique extensions, leading to portability and
compatibility issues.

 Lack of Real Time Analytics: Traditional SQL databases are not


optimized for real-time data ingestion and analysis.

SQL Data Types


In SQL, each column must be assigned a data type that defines the kind of
data it can store, such as integers, dates, text, or binary values. Choosing the
correct data type is crucial for data integrity, query performance and efficient
indexing.

Benefits of using the right data type:

 Memory-efficient storage

 Accurate operations (e.g., calculations, sorting)

 Consistency in stored values

 Validation of input data

SQL data types are broadly categorized into several groups:


1. Numeric Data Types

Numeric data types are fundamental to database design and are used to
store numbers, whether they are integers, decimals or floating-point
numbers. These data types allow for mathematical operations like addition,
subtraction, multiplication and division, which makes them essential for
managing financial, scientific and analytical data.

Exact Numeric Datatype

Exact numeric types are used when precise numeric values are needed, such
as for financial data, quantities, and counts. Some common exact numeric
types include:

Data Type Description Range

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

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

SMALLINT Small integers -32,768 to 32,767


Data Type Description Range

TINYINT Very small integers 0 to 255

Exact fixed-point
DECIMAL numbers (e.g., for -10^38 + 1 to 10^38 - 1
financial values)

Similar to DECIMAL,
NUMERIC -10^38 + 1 to 10^38 - 1
used for precision data

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


MONEY
values 922,337,203,685,477.5807

SMALLMON Smaller monetary


-214,748.3648 to 214,748.3647
EY values

Approximate Numeric Datatype

These types are used to store approximate values, such as scientific


measurements or large ranges of data that don't need exact precision.

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

2. Character and String Data Types


Character data types are used to store text or character-based data. The
choice between fixed-length and variable-length data types depends on the
nature of your data.

Data Type Description

The maximum length of 8000 characters. (Fixed-Length


Char
non-Unicode Characters)

The maximum length of 8000 characters. (Variable-Length


Varchar
non-Unicode Characters)

Varchar(m The maximum length of 2^31 - 1 characters(SQL Server


ax) 2005 only). (Variable Length non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable


Text
Length non-Unicode data)

Unicode Character String Data Types

Unicode data types are used to store characters from any language,
supporting a wider variety of characters. These are given in below table.

Data Type Description

The maximum length of 4000 characters(Fixed-Length


Nchar
Unicode Characters)

The maximum length of 4000 characters.(Variable-Length


Nvarchar
Unicode Characters)

Nvarchar(m The maximum length of 2^31 - 1 characters(SQL Server


ax) 2005 only). (Variable Length Unicode data)

3. Date and Time Data Type


SQL provides several data types for storing date and time information. They
are essential for managing timestamps, events and time-based queries.
These are given in the below table.

Data Storage
Type Description Size

DATE stores the data of date (year, month, day) 3 Bytes

TIME stores the data of time (hour, minute,second) 3 Bytes

DATETI store both the data and time (year, month, day,
8 Bytes
ME hour, minute, second)

4. Binary Data Types in SQL

Binary data types are used to store binary data such as images, videos or
other file types. These include:

Data
Type Description Max Length

Binary Fixed-length binary data. 8000 bytes

VarBina Variable-length binary


8000 bytes
ry data.

Stores binary data as 2,147,483,647


Image
images. bytes

5. Boolean Data Type in SQL

The BOOLEAN data types are used to store logical values, typically TRUE or
FALSE. It is commonly used for flag fields or binary conditions.

6. Special Data Types


SQL also supports some specialized data types for advanced use cases:

 XML Data Type: Used to store XML data and manipulate XML
structures in the database

 Spatial Data Type (Geometry): stores planar spatial data, such as


points, lines, and polygons, in a database table.

SQL Operators
SQL operators are symbols or keywords used to perform operations on data
in SQL queries.

 Perform operations like calculations, comparisons, and logical checks.

 Enable filtering, calculating, and updating data in databases.

 Essential for query optimization and accurate data management.

Types of SQL Operators

SQL operators can be categorized based on the type of operation they


perform. Here are the primary types of SQL operators:

 Arithmetic Operator

 Comparison Operator

 Logical Operator

 Bitwise Operators

 Compound Operators

 Special Operators

Each of these operators is essential for performing different types of


operations on data in SQL databases.

SQL Arithmetic Operators

Arithmetic operators in SQL are used to perform mathematical operations on


numeric data types in SQL queries. Some common arithmetic operators:
Operat
or Description

The addition is used to perform an addition operation on the data


+
values.

- This operator is used for the subtraction of the data values.

This operator works with the 'ALL' keyword and it calculates


/
division operations.

* This operator is used for multiplying data values.

Modulus is used to get the remainder when data is divided by


%
another.

Example: Arithmetic Operations

In this example, we calculates a 5% increment on employee salaries and


returns both the original and updated salary values.

Query:

SELECT emp_salary, emp_salary * 1.05 AS "Revised Salary" FROM employee;

Output:

Arithmetic Operation Example

SQL Comparison Operators


Comparison Operators in SQL are used to compare one expression's value
to other expressions. SQL supports different types of comparison operator,
which are described below:

Operat
or Description

= Equal to.

> Greater than.

< Less than.

Greater than
>=
equal to.

Less than equal


<=
to.

<> Not equal to.

Example: Comparison Operation

In this example, we will retrieve all records from the "MATHS" table where the
value in the "MARKS" column is equal to 50.

Query:

SELECT * FROM MATHS WHERE MARKS=50;

Output:
Comparison Operation

SQL Logical Operators

Logical Operators in SQL are used to combine or manipulate conditions in


SQL queries to retrieve or manipulate data based on specified criteria..

Operat
or Description

Logical AND compares two Booleans as expressions and returns


AND
true when both expressions are true.

Logical OR compares two Booleans as expressions and returns


OR
true when one of the expressions is true.

Not takes a single Boolean as an argument and change its value


NOT
from false to true or from true to false.

Example: Logical Operation

In this example, retrieve all records from the "employee" table where the
"emp_city" column is equal to 'Allahabad' and the "emp_country" column
is equal to 'India'.

Query:
SELECT * FROM employee
WHERE emp_city = 'Allahabad' AND emp_country = 'India';

Output:

Logical Operation

SQL Bitwise Operators

Bitwise operators in SQL are used to perform bitwise operations on binary


values in SQL queries, manipulating individual bits to perform logical
operations at the bit level. Some SQL Bitwise Operators are:

Operat
or Description

& Bitwise AND operator

| Bitwise OR operator

Bitwise XOR (exclusive OR)


^
operator

Bitwise NOT (complement)


~
operator

<< Left shift operator

>> Right shift operator

SQL Compound Operators


Compound operators combine an operation with assignment. These
operators modify the value of a column and store the result in the same
column in a single step. Some Compound operators are:

Operat
or Description

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulo and assign

Bitwise AND and


&=
assign

Bitwise XOR and


^=
assign

Bitwise OR and
|=
assign

SQL Special Operators

SQL also provides several special operators that serve specific functions such
as filtering data based on a range, checking for existence, and comparing
sets of values.
Operat
ors Description

ALL is used to select all records of a SELECT STATEMENT. It


compares a value to every value in a list of results from a query.
The ALL must be preceded by the comparison operators and
ALL evaluated to TRUE if the query returns no rows.

ANY compares a value to each value in a list of results from a


query and evaluates to true if the result of an inner query
ANY contains at least one row.

The SQL BETWEEN operator tests an expression against a range.


BETWEE The range consists of a beginning, followed by an AND keyword
N and an end expression.

The IN operator checks a value within a set of values separated


IN by commas and retrieves the rows from the table that match.

The EXISTS checks the existence of a result of a subquery. The


EXISTS subquery tests whether a subquery fetches at least one
EXISTS row. When no data is returned then this operator returns 'FALSE'.

SOME operator evaluates the condition between the outer and


inner tables and evaluates to true if the final result returns any
SOME one row. If not, then it evaluates to false.

The UNIQUE operator searches every unique row of a specified


UNIQUE table.

Example: Special Operator (BETWEEN)


In this example, we will retrieve all records from the "employee" table where
the "emp_id" column has a value that falls within the range of 101 to 104
(inclusive).

Query:

SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;

Output:

Special Operator

SQL AND and OR Operators

Last Updated : 23 Jul, 2025

The SQL AND and OR operators are used to filter data based on multiple
conditions. These logical operators allow users to retrieve precise results
from a database by combining various conditions in SELECT, INSERT,
UPDATE, and DELETE statements.

In this article, we'll learn the AND and OR operators, demonstrate their usage
with examples, and provide insights on combining them for complex
queries.

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.

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

SQL AND and OR Operator Examples

Let's look at some examples of AND and OR operators in SQL and


understand their working.

Now, we consider a table database to demonstrate AND & OR operators with


multiple cases.
Student Table

Example 1: SQL AND Operator

If suppose we want to fetch all the records from the Student table where Age
is 18 and ADDRESS is Delhi.

Query:

SELECT * FROM Student

WHERE Age = 18 AND ADDRESS = 'Delhi';

Output:

ROLL_N ADDRE Ag
O NAME SS PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

SURES XXXXXXXX
4 Delhi 18
H XX

Example 2: SQL OR Operator

To fetch all the records from the Student table where NAME is Ram or NAME
is SUJIT.
Query:

SELECT * FROM Student

WHERE NAME = 'Ram' OR NAME = 'SUJIT';

Output:

ROLL_N NAM ADDRE Ag


O E SS PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

XXXXXXXX
3 SUJIT ROHTAK 20
XX

XXXXXXXX
3 SUJIT ROHTAK 20
XX

Combining AND and OR Operators in SQL

Combining AND and OR Operators in SQL allows the creation of complex


conditions in queries. This helps in filtering data on multiple conditions.

Syntax:

Syntax to use AND and OR operator in one statement in SQL is:

SELECT * FROM table_name


WHERE condition1 AND (condition2 OR condition3);

Example

Let's look at example of combining AND and OR operators in a single


statement. In this example we will fetch all the records from the Student
table where Age is 18, NAME is Ram or RAMESH.

Query:

SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ram' OR NAME


= 'RAMESH');

Output:
ROLL_N ADDRES Ag
O NAME S PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

RAMES GURGAO XXXXXXXX


2 18
H N XX

Important Points About SQL AND and OR Operators

 The SQL AND operator is used to combine multiple conditions, where


all the conditions must be true for the row to be included in the result
set.

 The OR operator is used to combine multiple conditions, where at least


one of the conditions must be true for the row to be included in the
result set.

 Any kind of condition, including equality, inequality, comparison, and


logical operators, can be utilized with the AND and OR operators.

 The AND operator is more important than the OR operator. In other


words, when both are used in the same SQL statement, the AND
operator will be executed first. To change the order of evaluation,
parentheses can be used.

 You can employ the AND and OR operators inside of other conditions
because they can both be nested.

Conclusion

The AND and OR operators are essential tools for filtering data in SQL. By
combining multiple conditions, you can create powerful and efficient queries
to retrieve exactly the data you need. Remember to use parentheses for
clarity and control the order of evaluation, especially when combining both
operators. By mastering these logical operators, you’ll be able to handle
complex queries and data filtering tasks more effectively.

SQL NOT Operator


Last Updated : 06 Dec, 2024

The SQL NOT Operator is a logical operator used to negate or reverse the
result of a condition in SQL queries. It is commonly used with the WHERE
clause to filter records that do not meet a specified condition, helping you
exclude certain values from your results.

In this article, we will learn everything you need to know about the SQL NOT
operator, from basic usage to advanced examples.

What is the 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;

Examples of SQL NOT Operator

CREATE TABLE Customers (

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

City VARCHAR(50),

PostalCode VARCHAR(10),

Country VARCHAR(50)

);

INSERT INTO Customers (CustomerID, CustomerName, City, PostalCode,


Country)

VALUES
(1, 'John Wick', 'New York', '1248', 'USA'),

(2, 'Around the Horn', 'London', 'WA1 1DP', 'UK'),

(3, 'Rohan', 'New Delhi', '100084', 'India');

Customer Customer PostalCo Count


ID Name City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn

New
3 Rohan 100084 India
Delhi

Example 1: Using SQL NOT to Exclude a Specific Value

The following SQL statement selects all fields from Customers table where
the country is not UK.

Query:

SELECT *

FROM Customers

WHERE NOT Country = 'UK';

Output:

Customer Customer PostalCo Count


ID Name City de ry

New
1 John Wick 1248 USA
York
Customer Customer PostalCo Count
ID Name City de ry

New
3 Rohan 100084 India
Delhi

In this example, the NOT operator filters out customers from the UK and
returns all other customers.

Example 2: Using SQL NOT with IN Operator

The NOT operator can also be used with the IN condition to exclude multiple
values from the result set.

Query:

SELECT *

FROM Customers

WHERE NOT Country IN ('USA', 'UK');

Output:

Customer Customer PostalCo Count


ID Name City de ry

New
3 Rohan 100084 India
Delhi

Here, the NOT IN condition filters out customers from both the USA and UK
and returns only customers from other countries.

Example 3: Using SQL NOT with LIKE Operator

We can also combine NOT with the LIKE operator to exclude records that
match a certain pattern.

Query:

SELECT *

FROM Customers
WHERE NOT CustomerName LIKE 'R%';

Output:

Customer CustomerNa PostalCo Count


ID me City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn

In this query, the NOT LIKE condition filters out customers whose name starts
with the letter 'R', returning all others.

Example 4: Using SQL NOT with NULL Values

To exclude records where a column has a NULL value, combine NOT with the
IS NULL condition.

Query:

SELECT *

FROM Customers

WHERE NOT PostalCode IS NULL;

Output:

Customer CustomerNa PostalCo Count


ID me City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn
Customer CustomerNa PostalCo Count
ID me City de ry

New
3 Rohan 100084 India
Delhi

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

Output:

Customer CustomerNa PostalCo Count


ID me City de ry

New
3 Rohan 100084 India
Delhi

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.

Conclusion

The SQL NOT operator is an essential tool for SQL developers. Whether
you're excluding specific records, filtering null values, or creating more
complex logical conditions, the NOT operator helps you fine-tune your
queries. Understanding how to combine it with other SQL operators will
improve your ability to write more efficient and precise SQL queries.

SQL | ALL and ANY

In SQL, the ALL and ANY operators are logical operators used to compare
a value with a set of values returned by a subquery. These operators provide
powerful ways to filter results based on a range of conditions.

In this article, we will explore ALL and ANY in SQL, their differences, and
how to use them effectively to boost your query performance and
efficiency.

What is the 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.

How to Use SQL ALL with SELECT, WHERE, and HAVING

The ALL operator can be used in conjunction with SELECT, WHERE,


and HAVING statements to refine your data filtering.

lets Consider the following Products Table and OrderDetails Table for
explaining the examples.

Products Table
OrderDetails Table

Queries

Example 1 : Retrieve all product names from the Products table.

Query:

SELECT ALL ProductName

FROM Products

WHERE TRUE;
Output:

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

Output:

This query ensures that the product names returned have ALL quantities of 6
or 2 in the OrderDetails table.
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);

Output:

ANY

This query filters out OrderIDs where the maximum quantity is greater than
the average quantity of the orders.

What is the 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);

Output:

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

Output:

product names

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.

Conclusion

The ALL and ANY operators in SQL are essential for advanced filtering based
on dynamic conditions. The key differences lie in how they evaluate the
conditions across the results of the subquery. ALL requires the condition to
be true for all values in the subquery, while ANY only needs the condition to
be true for one value. By mastering these operators, you can write more
efficient and flexible SQL queries.

SQL | BETWEEN & IN Operator

In SQL, the BETWEEN and IN operators are widely used for filtering
data based on specific criteria. The BETWEEN operator helps filter results
within a specified range of values, such as numbers, dates, or text, while
the IN operator filters results based on a specific list of values. Both
operators simplify data retrieval, enhancing the efficiency of SQL queries.

In this article, we will explain the BETWEEN and IN operators,


their syntax, significance, and practical use cases with examples.
Understanding their differences and when to use each operator is essential
for building optimized and maintainable SQL queries.

SQL Between Operator

The SQL BETWEEN operator is used to test whether a value falls within a
given range of values (inclusive). The values can be text, date,
or numbers. It can be used in a SELECT, INSERT, UPDATE or DELETE
statement. The SQL BETWEEN Condition will return the records where the
expression is within the range of value1 and value2.

Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Key Features:

 Inclusive of both boundary values (value1 and value2).

 Simplifies queries when working with continuous ranges.

Creating a Sample Table

Let’s create a sample table named Emp to demonstrate the use of


the BETWEEN and IN operators. The Emp table contains employee data,
including details such as name, country, age, and salary. These columns
will be used to demonstrate filtering using the BETWEEN and IN operators.

Query:

CREATE TABLE Emp(


EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Salary int(10)
);

INSERT INTO Emp (EmpID, Name,Country, Age, Salary)


VALUES (1, 'Shubham', 'India','23','30000'),
(2, 'Aman ', 'Australia','21','45000'),
(3, 'Naveen', 'Sri lanka','24','40000'),
(4, 'Aditya', 'Austria','21','35000'),
(5, 'Nishant', 'Spain','22','25000');

Select * from Emp;

Output
Emp Table

Examples of SQL Between Operator

The BETWEEN operator simplifies queries by filtering data within


a specified range, making it easier to retrieve relevant records. Below are
examples demonstrating its application with numeric and date values, as
well as with the NOT operator.

Example 1: Using BETWEEN with Numeric Values

List all the Employee's Names who is having salary between 30000 and
45000. This query filters employees whose salary falls within the range of
30000 to 45000, inclusive. The BETWEEN operator simplifies filtering
compared to writing multiple conditions with AND

Query:

SELECT Name
FROM Emp
WHERE Salary
BETWEEN 30000 AND 45000;

Output

Using BETWEEN with Numeric Values


Example 2: Using BETWEEN with Date Values

Find all the Employees an Age Between 22 to 24. This query retrieves
employees whose age is between 22 and 24, including the boundary values.
The BETWEEN operator efficiently filters the range without
requiring complex conditions.

Query:

SELECT Name
FROM Emp
where Age
BETWEEN '22' AND '24';

Output

Using BETWEEN with Date Values

Example 3: Using the NOT Operator with BETWEEN

Find all the Employee names whose salary is not in the range of 30000
and 45000. The NOT BETWEEN clause excludes employees whose salary
falls within the specified range, returning only those outside the range.

Query:

SELECT Name
FROM Emp
WHERE Salary
NOT BETWEEN 30000 AND 45000;

Output

NOT Operator with BETWEEN

SQL IN Operator
IN operator allows us to easily test if the expression matches any
value in the list of values. It is used to remove the need for multiple OR
conditions in SELECT, INSERT, UPDATE, or DELETE. We can also use NOT
IN to exclude the rows in our list. We should note that any kind of duplicate
entry will be retained.

Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (list_of_values);

Key Features:

 Ideal for filtering non-sequential values.

 Handles duplicates in the list of values.

Examples of SQL IN Operator

The IN operator allows us to filter data by matching values against a


specific list, simplifying queries that involve multiple conditions. Below are
examples showcasing its usage with both IN and NOT IN clauses for
effective data retrieval.

Example 1: Using IN Operator

Find the Fname, and Lname of the Employees who have a Salary equal
to 30000, 40000, or 25000. The query retrieves employees whose salary
matches any of the specified values in the list. This approach is more
concise and efficient compared to using multiple OR conditions

Query:

SELECT Name
FROM Emp
WHERE Salary IN (30000, 40000, 25000);

Output
IN Operator

Example 2: Using the NOT Operator with IN

Find the Fname and Lname of all the Employees who has a Salary not
equal to 25000 or 30000. This query excludes employees with salaries of
25000 and 30000. The NOT IN clause ensures that all other employees are
included in the result set.

Query:

SELECT Name
FROM Emp
WHERE Salary NOT IN (25000, 30000);

Output

NOT operator with IN

Difference Between BETWEEN and IN

Feature BETWEEN IN

Tests if a value falls


Tests if a value matches any
within a specified range
value in a specified list.
Purpose (inclusive).

Syntax column BETWEEN value1 column IN (value1, value2, ...)


Feature BETWEEN IN

AND value2

Data Types Numbers, dates, or text Numbers, dates, text, or a list


Supported values. of values.

Used for checking values


Used for checking if a value is
Range vs. within a range (e.g., 1 to
in a list (e.g., 1, 5, 10).
List 10).

Example Salary BETWEEN 30000 Salary IN (30000, 40000,


Usage AND 45000 25000)

Exclusion Salary NOT BETWEEN


Salary NOT IN (25000, 30000)
Example 30000 AND 45000

Efficient for non-sequential


Efficient for continuous
values or when checking
ranges.
Efficiency multiple conditions.

Conclusion

Both BETWEEN and IN are powerful SQL operators for filtering data
effectively. The BETWEEN operator is ideal for queries involving continuous
ranges, such as dates or salary bands, while the IN operator is better
suited for discrete values or fixed conditions. By understanding their
strengths, we can choose the right operator for your use case,
ensuring optimal query performance and clear results

Can the BETWEEN operator be used with text values?

Yes, the BETWEEN operator can be used with text values to filter results
alphabetically within a range of strings, such as finding names that fall
alphabetically between "A" and "D".

What is the difference between NOT BETWEEN and NOT IN?


NOT BETWEEN is used to exclude results within a certain range, while NOT IN
excludes specific values from a list.

Can the IN operator handle duplicate values?

Yes, the IN operator can handle duplicate values in the list, but it will treat
them as the same and will not return duplicates in the result set.

SQL | EXISTS

The SQL EXISTS condition is used to test whether a correlated


subquery returns any results. If the subquery returns at least one row, the
EXISTS condition evaluates to TRUE; otherwise, it evaluates to FALSE. The
EXISTS operator can be used in various SQL statements like SELECT,
UPDATE, INSERT, and DELETE to filter data based on whether certain
conditions are met.

What is 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.

Examples of SQL EXISTS

Consider the following two relation "Customers" and "Orders".

Customers Table

Orders Table:

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

Output:

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

Output:

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;

Output:

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;

Output:

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.

Conclusion

The SQL EXISTS condition is an essential tool for database professionals,


helping to test the existence of records in a subquery. By using EXISTS, you
can perform various operations such as SELECT, UPDATE, INSERT, and
DELETE based on the presence of related data. Whether you're checking if
customers have placed orders or performing data integrity checks, EXISTS
provides a powerful, efficient way to filter and manipulate data.
SQL | SOME

SQL | ALL and ANY SOME operator evaluates the condition between the outer
and inner tables and evaluates to true if the final result returns any one row.
If not, then it evaluates to false.

 The SOME and ANY comparison conditions are similar to each other
and are completely interchangeable.

 SOME must match at least one row in the subquery and must be
preceded by comparison operators.

Syntax:

SELECT column_name(s)

FROM table_name

WHERE expression comparison_operator SOME (subquery)

Instructor Table:

Name Department Salary

Chandra Computational Biology 1

Visweswaran Electronics 1.5

Abraham Computer Science 1.3


John Electronics 1.2

Samantha Computer Science 2

Jyoti Electronics 1.2

Debarka Computer Science 2

Ganesh Computational Biology 0.9

Sample Queries and Outputs:

select name

from instructor

where Salary > some(select Salary

from instructor

where dept='Computer Science');

Output:

Visweswar
an

Samantha

Debarka

Explanation The instructors with salary > (salary of some instructor in the
'Computer Science' department) get returned. The salaries in the 'Computer
Science' department are 1.3, 2 and 2. This implies any instructor with a
salary greater than 1.3 can be included in the final result. Exercise: Try to
write same query using ANY clause.
SQL | ALL and ANY

In SQL, the ALL and ANY operators are logical operators used to compare
a value with a set of values returned by a subquery. These operators provide
powerful ways to filter results based on a range of conditions.

In this article, we will explore ALL and ANY in SQL, their differences, and
how to use them effectively to boost your query performance and
efficiency.

What is the 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.
How to Use SQL ALL with SELECT, WHERE, and HAVING

The ALL operator can be used in conjunction with SELECT, WHERE,


and HAVING statements to refine your data filtering.

lets Consider the following Products Table and OrderDetails Table for
explaining the examples.

Products Table

OrderDetails Table
Queries

Example 1 : Retrieve all product names from the Products table.

Query:

SELECT ALL ProductName

FROM Products

WHERE TRUE;

Output:

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


Output:

This query ensures that the product names returned have ALL quantities of 6
or 2 in the OrderDetails table.

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

Output:

ANY

This query filters out OrderIDs where the maximum quantity is greater than
the average quantity of the orders.

What is the 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);

Output:

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

Output:

product names

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.

Conclusion

The ALL and ANY operators in SQL are essential for advanced filtering based
on dynamic conditions. The key differences lie in how they evaluate the
conditions across the results of the subquery. ALL requires the condition to
be true for all values in the subquery, while ANY only needs the condition to
be true for one value. By mastering these operators, you can write more
efficient and flexible SQL queries.
SQL | UNIQUE Constraint

The UNIQUE constraint in SQL ensures that values in a column or set of


columns are distinct, preventing duplicates. Unlike a PRIMARY KEY, it allows
multiple NULL values since each NULL is treated as unique, while a primary
key requires all values to be unique and non-NULL.

Features of UNIQUE Constraint

 Prevents Duplicates: Ensures column(s) have unique values.

 Allows NULLs: Multiple NULLs are permitted.

 Single or Multiple Columns: Can apply to one or more columns.

 Index Not Required: Does not automatically create an index (though


many databases do for performance).

 Modifiable: Can be added or removed using ALTER TABLE.

Syntax:

CREATE TABLE table_name (

column1 datatype UNIQUE,

column2 datatype,

...

);

In the above syntax:

 CREATE TABLE table_name: creates a new table.

 column1 datatype UNIQUE: defines a column with a data type and


enforces unique values.

 column2 datatype: defines another column without the unique


constraint.

 Repeat for additional columns as needed.


Example of Using the SQL UNIQUE Constraint

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)

);

In this case, each customer must have a unique email address. If you try to
insert a duplicate email, SQL will raise an error.

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (1, 'John Doe', '[email protected]', 'USA');

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (2, 'Jane Smith', '[email protected]', 'Canada');

-- This will fail because '[email protected]' already exists

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (3, 'Alice Johnson', '[email protected]', 'UK');

The third insert will fail because the Email [email protected] already
exists in the Customers table.

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)

);

In this example, the combination of CustomerID and ProductID must be


unique, meaning a customer cannot order the same product more than once.

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

);

In this example, we check if there are any duplicate OrderID values for each
customer in the Orders table. If the subquery returns unique values, the
CustomerID will be selected.

Important Points

 Evaluates to true on an empty subquery.

 Returns true only if there are unique tuples present as the output of
the sub-query (two tuples are unique if the value of any attribute of the
two tuples differs).

 Returns true if the sub-query has two duplicate rows with at least one
attribute as NULL.
SQL Commands | DDL, DQL, DML, DCL and TCL
Commands

SQL commands are fundamental building blocks for communicating with


a database management system (DBMS) used to interact with database with
some operations. It is also used to perform specific tasks, functions and
queries of data. SQL can perform various tasks like creating a table, adding
data to tables, dropping the table, modifying the table, set permission for
users.

SQL Commands are mainly categorized into five categories:

SQL Commands

1. DDL - Data Definition Language

DDL (Data Definition Language) actually consists of SQL commands that can
be used for defining, altering and deleting database structures such as
tables, indexes and schemas. It simply deals with descriptions of the
database schema and is used to create and modify the structure of database
objects in the database
Common DDL Commands

Command Description Syntax

Create database or its CREATE TABLE


objects (table, index, table_name (column1
CREATE
function, views, store data_type, column2
procedure and triggers) data_type, ...);

Delete objects from the


DROP DROP TABLE table_name;
database

ALTER TABLE table_name


Alter the structure of the
ALTER ADD COLUMN
database
column_name data_type;

Remove all records from a


table, including all spaces TRUNCATE TABLE
TRUNCATE
allocated for the records table_name;
are removed

COMMENT ON TABLE
Add comments to the data
COMMENT table_name IS
dictionary
'comment_text';

RENAME TABLE
Rename an object existing
RENAME old_table_name TO
in the database
new_table_name;
SQL CREATE TABLE

Creating a table is one of the first and most important steps in building a
database. The CREATE TABLE command in SQL defines how your data will be
stored, including the table name, column names, data types, and rules
(constraints) such as NOT NULL, PRIMARY KEY, and CHECK.

 Defines a new table in the database.

 Specifies columns, their data types, and sizes.

 Applies constraints such as NOT NULL, PRIMARY KEY, and CHECK.

 Ensures accuracy, consistency, and organized data storage.

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.

Example: Create a Customer Table

Let’s walk through a practical example where we create a Customer table


that stores customer data. We will define various columns such as
CustomerID, CustomerName, Country, Age, and Phone with appropriate data
types and constraints.
Query:

CREATE TABLE Customer(

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

LastName VARCHAR(50),

Country VARCHAR(50),

Age INT CHECK (Age >= 0 AND Age <= 99),

Phone int(10)

);

Output:

Explanation:

 CustomerID is an integer and serves as the PRIMARY KEY, ensuring


each record is unique.

 CustomerName, LastName, and Country are VARCHAR fields to store


variable-length text.

 Age has a CHECK constraint, ensuring it’s within the range of 0 to 99.

 Phone is an integer field, although in real scenarios, a VARCHAR would


often be used for storing phone numbers to allow for leading zeros and
formatting.

Inserting Data into the Table

After creating the table, you can use INSERT INTO command to add data into
it. Here is how to add some sample records into the Customer table:

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,


Age, Phone)

VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),


(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),

(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),

(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),

(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

Note: If you are working with a large amount of data, consider using bulk
inserts or importing data from external files to optimize performance.

Create Table from Existing Table

We can also create a new table based on the structure (and optionally the
data) of an existing table. The CREATE TABLE AS SELECT command allows us
to duplicate an entire table or select specific columns to form a new one. The
following query creates a new table called SubTable that contains
CustomerID and CustomerName from the existing Customer table.

Syntax:

CREATE TABLE new_table_name AS

SELECT column1, column2, ...

FROM existing_table_name

WHERE ...;

In this example, we create a new table SubTable that contains just the
CustomerID and CustomerName columns from the Customer table. This
method is useful for creating backups or performing quick data migrations.

Query:
CREATE TABLE SubTable AS

SELECT CustomerID, CustomerName

FROM customer;

Output:

Note: We can use * instead of column name to copy whole table to another
table.

Key Tips for Using CREATE TABLE in SQL

To ensure the smooth creation and management of your tables, keep these
points in mind:

1. The CREATE TABLE statement can also define constraints like NOT NULL,
UNIQUE, and DEFAULT.

2. 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. Always define appropriate data types for each column


(e.g., VARCHAR(50) for names and INT for IDs) to optimize performance and
storage.

4. After creating a table, use the following command to view the structure of
your table:

DESC table_name;

6. 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.
2. DQL - Data Query Language

DQL is used to fetch data from the database. The main command is SELECT,
which retrieves records based on the query. The output is returned as a
result set (a temporary table) that can be viewed or used in applications.

DQL Command

Comman
d Description Syntax

SELECT column1,
It is used to retrieve data
SELECT column2, ...FROM table_name
from the database
WHERE condition;

Indicates the table(s) from SELECT column1


FROM
which to retrieve data. FROM table_name;

SELECT column1
Filters rows before any
WHERE FROM table_name
grouping or aggregation
WHERE condition;

SELECT column1,
Groups rows that have the
GROUP AVG_FUNCTION(column2)
same values in specified
BY FROM table_name
columns.
GROUP BY column1;

HAVING Filters the results of GROUP SELECT column1,


BY AVG_FUNCTION(column2)
FROM table_name
GROUP BY column1
Comman
d Description Syntax

HAVING condition;

SELECT DISTINCT column1,


DISTINC Removes duplicate
column2, ...
T rows from the result set
FROM table_name;

SELECT column1
ORDER Sorts the result set by one FROM table_name
BY or more columns ORDER BY column1 [ASC |
DESC];

By default, it sorts
SELECT * FROM table_name
LIMIT in ascending order unless
LIMIT number;
specified as DESC

Note: DQL has only one command, SELECT. Other terms like FROM,
WHERE, GROUP BY, HAVING, ORDER BY, DISTINCT and LIMIT are clauses of
SELECT, not separate commands.

Example:

SELECT first_name, last_name, hire_date


FROM employees
WHERE department = 'Sales'
ORDER BY hire_date DESC;

This query retrieves employees first and last names, along with their hire
dates, from the employees table, specifically for those in the 'Sales'
department, sorted by hire date.
SQL SELECT Query

SQL SELECT is used to retrieve data from one or more tables, either all
records or specific results based on conditions. It returns output in a tabular
format of rows and columns.

 Extracts data from tables.

 Targets specific or all columns (*).

 Supports filtering, sorting, grouping, and joins.

 Results are stored in a result set.

Syntax

SELECT column1,column2.... FROM table_name;

Parameters:

 column1, column2: columns you want to retrieve.

 table_name: name of the table you're querying.

Examples of SELECT Statement

Let us start by creating a sample table that we will use for our examples. We
will also insert some sample data to make the demonstration more practical.

CREATE TABLE Customer (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT(2),
Phone VARCHAR(10) );

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,


Age, Phone)
VALUES (1, 'Liam', 'Smith', 'USA', 23, 'xxxxxxxxxx'),
(2, 'Sophia', 'Miller', 'USA', 21, 'xxxxxxxxxx'),
(3, 'Akira', 'Tanaka', 'Japan', 24, 'xxxxxxxxxx'),
(4, 'Carlos', 'Hernandez', 'USA', 21, 'xxxxxxxxxx'),
(5, 'Isabella', 'Rossi', 'Italy', 22, 'xxxxxxxxxx');

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

xxxxxxx
1 Liam Smith USA 23
xxx

xxxxxxx
2 Sophia Miller USA 21
xxx

xxxxxxx
3 Akira Tanaka Japan 24
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

Example 1: Select Specific Columns

In this example, we will demonstrate how to retrieve specific columns from


the Customer table. Here we will fetch only CustomerName and LastName
for each record.
Query:

SELECT CustomerName, LastName


FROM Customer;

Output

CustomerNa LastNa
me me

Liam Smith

Sophia Miller

Akira Tanaka

Hernand
Carlos
ez

Isabella Rossi

Example 2: Select All Columns

In this example, we will fetch all the fields from table Customer:

Query:

SELECT * FROM Customer;

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

1 Liam Smith USA 23 xxxxxxx


Customer CustomerNa LastNa Count Ag
ID me me ry e Phone

xxx

xxxxxxx
2 Sophia Miller USA 21
xxx

xxxxxxx
3 Akira Tanaka Japan 24
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

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

Output
CustomerNa
me

Sophia

Carlos

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, we will count the number of
customers from each country.

Query:

SELECT Country, COUNT(*) AS customer_count


FROM Customer
GROUP BY Country;

Output

Count customer_co
ry unt

USA 3

Japan 1

Italy 1

Example 5: SELECT with DISTINCT Clause

In this example, we will use DISTINCT keyword to return only unique values
from a column. Here, we will fetch unique countries from the Customer table.
Query:

SELECT DISTINCT Country


FROM Customer;

Output

Count
ry

USA

Japan

Italy

Example 6: SELECT Statement with HAVING Clause

The HAVING clause is used to filter results after applying GROUP BY. In this
example, we will find countries that have 2 or more customers in the
Customer table.

Query:

SELECT Country, COUNT(*) AS customer_count


FROM Customer
GROUP BY Country
HAVING COUNT(*) >= 2;

Output

Count customer_co
ry unt

USA 3
Example 7: SELECT Statement with ORDER BY clause

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;

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

xxxxxxx
3 Akira Tanaka Japan 24
xxx

xxxxxxx
1 Liam Smith USA 23
xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

xxxxxxx
2 Sophia Miller USA 21
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx

SQL - WHERE Clause

In SQL, the WHERE clause is used to filter rows based on specific conditions.
Whether you are retrieving, updating, or deleting data, WHERE ensures that
only relevant records are affected. Without it, your query applies to every
row in the table! The WHERE clause helps you:

 Filter rows that meet certain conditions

 Target specific data using logical, comparison and pattern-based


operators

 Control SELECT, UPDATE, DELETE or even INSERT statements

Syntax:

SELECT column1, column2


FROM table_name
WHERE column_name operator value;

Parameters:

 column1, column2: Columns you want to retrieve

 table_name: Table you are querying from

 operator: Comparison logic (e.g., =, <, >, LIKE)

 value: The value or pattern to filter against

Importance of WHERE Clause

The WHERE clause is critical for several reasons:

 Data Accuracy: Filters data to return only relevant rows

 Performance: Reduces the amount of scanned data

 Flexibility: Works with many operators and conditions

Examples of WHERE Clause in SQL

We will create a basic employee table structure in SQL for performing all the
where clause operation.

Query:

CREATE TABLE Emp1 (


EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age INT,
Mob VARCHAR(15)
);

INSERT INTO Emp1 VALUES


(1, 'Shubham', 'India', 23, '738479734'),
(2, 'Aman', 'Australia', 21, '436789555'),
(3, 'Naveen', 'Sri Lanka', 24, '34873847'),
(4, 'Aditya', 'Austria', 21, '328440934'),
(5, 'Nishant', 'Spain', 22, '73248679');

SELECT * FROM Emp1;

Output:

EmpI Count Ag
D Name ry e mob

Shubha 7384797
1 India 23
m 34

Australi 4367895
2 Aman 21
a 55

Sri 3487384
3 Naveen 24
lanka 7

3284409
4 Aditya Austria 21
34

7324867
5 Nishant Spain 22
9

Example 1: Where Clause with Logical Operators

To fetch records of Employee with age equal to 24.

Query:

SELECT * FROM Emp1 WHERE Age=24;


Output:

EmpI Countr Ag
D Name y e Mob

Navee Sri 348738


3 24
n Lanka 47

Example 2: WHERE with Comparison Operators

To fetch the EmpID, Name and Country of Employees with Age greater than
21.

Query:

SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;

Output:

EmpI Countr
D Name y

Shubha
1 India
m

Sri
3 Naveen
Lanka

5 Nishant Spain

Example 3: Where Clause with BETWEEN Operator

The BETWEEN operator is used to filter records within a specified range, and
it includes both the start and end values. In this example, we want to find
employees whose age is between 22 and 24, including both 22 and 24.

Query:

SELECT * FROM Emp1


WHERE Age BETWEEN 22 AND 24;
Output:

EmpI Countr Ag
D Name y e Mob

Shubha 7384797
1 India 23
m 34

Sri 3487384
3 Naveen 24
Lanka 7

7324867
5 Nishant Spain 22
9

Example 4: Where Clause with LIKE Operator

It is used to fetch filtered data by searching for a particular pattern in the


where clause. In this example we want to find records of Employees where
Name starts with the letter. The '%'(wildcard) signifies the later characters
here which can be of any length and value.

Query:

SELECT * FROM Emp1 WHERE Name LIKE 'S%';

Output:

EmpI Count Ag
D Name ry e Mob

Shubha 7384797
1 India 23
m 34

To fetch records of Employees where Name contains the pattern 'M'.

Query:

SELECT * FROM Emp1 WHERE Name LIKE '%M%';


Output:

EmpI Count Ag
D Name ry e Mob

Shubha 7384797
1 India 23
m 34

Australi 4367895
2 Aman 21
a 55

Example 5: 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. Here we want to find the Names of Employees where Age is 21
or 23.

Query:

SELECT Name FROM Emp1 WHERE Age IN (21,23);

Output:

Name

Aman

Aditya

Shubha
m

List of Operators that Can be Used with WHERE Clause


Operator 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 GROUP BY

GROUP BY statement groups rows that have the same values in one or more
columns. It is commonly used to create summaries, such as total sales by
region or number of users by age group.

Its main features include:

 Used with the SELECT statement.

 Groups rows after filtering with WHERE.

 Can be combined with aggregate functions like SUM(), COUNT(), AVG(),


etc.

 Filter grouped results using the HAVING clause.

 Comes after WHERE but before HAVING and ORDER BY.

Query execution order: FROM -> WHERE -> GROUP BY -> HAVING ->
SELECT -> ORDER BY.

Syntax:

SELECT column1, aggregate_function(column2)


FROM table_name
WHERE condition
GROUP BY column1, column2;

Parameters:

 aggregate_function: function used for aggregation, e.g., SUM(),


AVG(), COUNT().

 table_name: name of the table from which data is selected.

 condition: Optional condition to filter rows before grouping (used with


WHERE).

 column1, column2: Columns on which the grouping is applied.


Examples of GROUP BY

Let's assume that we have a Student table. We will insert some sample data
into this table and then perform operations using GROUP BY to understand
how it groups rows based on a column and aggregates data.

CREATE TABLE student (


name VARCHAR(50),
year INT,
subject VARCHAR(50) );

INSERT INTO student (name, year, subject) VALUES


('Avery', 1, 'Mathematics'),
('Elijah', 2, 'English'),
('Harper', 3, 'Science'),
('James', 1, 'Mathematics'),
('Charlotte', 2, 'English'),
('Benjamin', 3, 'Science');

Output

ye
name ar subject

Mathemati
Avery 1
cs

Elijah 2 English

Harper 3 Science

Mathemati
James 1
cs

Charlott 2 English
ye
name ar subject

Benjami
3 Science
n

Example 1: Group By Single Column

When we group by a single column, rows with the same value in that column
are combined. For example, grouping by subject shows how many students
are enrolled in each subject.

Query:

SELECT subject, COUNT(*) AS Student_Count


FROM Student
GROUP BY subject;

Output

Student_Co
subject unt

English 2

Mathemati
2
cs

Science 2
Student_Co
subject unt

Explanation: Each subject appears twice in the table, so the count for
English, Mathematics and Science is 2.

Example 2: Group By Multiple Columns

Using GROUP BY with multiple columns groups rows that share the same
values in those columns. For example, grouping by subject and year will
combine rows with the same subject–year pair and we can count how many
students fall into each group.

Query:

SELECT subject, year, COUNT(*)


FROM Student
GROUP BY subject, year;

Output

ye count(
subject ar *)

English 2 2

Mathemati
1 2
cs

Science 3 2
Explantion: Students with the same subject and year are grouped together.
Since each subject–year pair occurs twice, the count is 2 for every group.

HAVING Clause in GROUP BY Clause

HAVING clause is used to filter results after grouping, especially when


working with aggregate functions like SUM(), COUNT() or AVG(). Unlike
WHERE, it applies conditions on grouped data.

In this section, we will use Employee table(emp) first insert some sample
data, then perform GROUP BY queries combined with HAVING.

CREATE TABLE emp (


emp_no INT PRIMARY KEY,
name VARCHAR(50),
sal DECIMAL(10,2),
age INT );

INSERT INTO emp (emp_no, name, sal, age) VALUES


(1, 'Liam', 50000.00, 25),
(2, 'Emma', 60000.50, 30),
(3, 'Noah', 75000.75, 35),
(4, 'Olivia', 45000.25, 28),
(5, 'Ethan', 80000.00, 32),
(6, 'Sophia', 65000.00, 27),
(7, 'Mason', 55000.50, 29),
(8, 'Isabella', 72000.75, 31),
(9, 'Logan', 48000.25, 26),
(10, 'Mia', 83000.00, 33);

SELECT * FROM emp;

Output

emp_ ag
no name sal e

50000.
Liam 25
1 00
emp_ ag
no name sal e

60000.
Emma 30
2 50

75000.
Noah 35
3 75

45000.
Olivia 28
4 25

80000.
Ethan 32
5 00

65000.
Sophia 27
6 00

55000.
Mason 29
7 50

Isabell 72000.
31
8 a 75

48000.
Logan 26
9 25

83000.
Mia 33
10 00
Example 1: Filter by Total Salary

In this query, we group employees by name and display only those whose
total salary is greater than 50,000.

SELECT NAME, SUM(sal) FROM Emp


GROUP BY name
HAVING SUM(sal)>50000;

Output

SUM(s
name al)

60000.
Emma
50

75000.
Noah
75

80000.
Ethan
00

Sophi 65000.
a 00

55000.
Mason
50

Isabell 72000.
a 75

83000.
Mia
00
Explanation: Only employees whose total salary exceeds 50,000 appear in
the result.

Example 2: Filter by Average Salary

In this query, we group employees by age and display only those age groups
where average salary is above 60,000.

SELECT age, AVG(sal) AS Average_Salary


FROM emp
GROUP BY age
HAVING AVG(sal) > 60000;

Output

ag Average_Sal
e ary

2
65000.00
7

3
60000.50
0

3
72000.75
1

3
80000.00
2

3
83000.00
3

3 75000.75
ag Average_Sal
e ary

Explanation: This query groups employees by age and calculates average


salary for each age. Only those age groups where average salary is greater
than 60,000 are displayed.

SQL HAVING Clause

HAVING clause filters results after applying aggregate functions. Unlike


WHERE, which filters individual rows, HAVING works with aggregated results.

Its main features include:

 Filters results based on aggregate functions.

 Supports Boolean conditions (AND, OR).

 Applied after aggregate functions in the query.

 Useful for summary-level or aggregated filtering.

Syntax:

SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
HAVING condition;

Examples of HAVING Clause

First, we create the Employee table and insert sample data to demonstrate
the HAVING clause.

Query:
CREATE TABLE Employee (
EmployeeId int,
Name varchar(50),
Gender varchar(10),
Salary int,
Department varchar(20),
Experience int );

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department,


Experience)
VALUES (1, 'Emily Johnson', 'Female', 45000, 'IT', 2),
(2, 'Michael Smith', 'Male', 65000, 'Sales', 5),
(3, 'Olivia Brown', 'Female', 55000, 'Marketing', 4),
(4, 'James Davis', 'Male', 75000, 'Finance', 7),
(5, 'Sophia Wilson', 'Female', 50000, 'IT', 3);

SELECT * FROM Employee;

Output

Employe Gend Sala Departm Experien


eId Name er ry ent ce

Emily Femal 4500


1 IT 2
Johnson e 0

Michael 6500
2 Male Sales 5
Smith 0

Olivia Femal 5500


3 Marketing 4
Brown e 0

7500
4 James Davis Male Finance 7
0

5 Sophia Femal 5000 IT 3


Employe Gend Sala Departm Experien
eId Name er ry ent ce

Wilson e 0

Example 1: Filter Total Salary

In this Example we calculate the total salary of all employees and display it
only if it meets the specified condition.

Query:

SELECT SUM(Salary) AS Total_Salary


FROM Employee
HAVING SUM(Salary) >= 250000;

Output

Total_Sal
ary

290000

Example 2: Filter Average Salary

In this example, we calculate the average salary of all employees and display
it only if the average exceeds 55,000.

Query:
SELECT AVG(Salary) AS Average_Salary
FROM Employee
HAVING AVG(Salary) > 55000;

Output

Average_Sal
ary

58000

Example 3: Filter Maximum Salary

In this example, we find the highest salary among employees and display it
only if it exceeds 70,000.

Query:

SELECT MAX(Salary) AS Max_Salary


FROM Employee
HAVING MAX(Salary) > 70000;

Output

Max_Sal
ary

75000

Example 4: Filter Minimum Experience

In this example, we find the least experienced employee and display it only if
their experience is less than 3 years.
Query:

SELECT MIN(Experience) AS Min_Experience


FROM Employee
HAVING MIN(Experience) < 3;

Output

Min_Experie
nce

Example 5: Multiple Conditions

In this example, we calculate both the total and average salary of employees
and display the results only if the total salary is at least 250,000 and the
average salary exceeds 55,000.

Query:

SELECT SUM(Salary) AS Total_Salary, AVG(Salary) AS Average_Salary


FROM Employee
HAVING SUM(Salary) >= 250000 AND AVG(Salary) > 55000;

Output

Total_Sal Average_Sal
ary ary

290000 58000
SQL Distinct Clause

The DISTINCT keyword in SQL is used to retrieve only unique values,


eliminating duplicates from query results. It ensures data accuracy and is
often used with the SELECT statement for clean, precise reporting.

 Removes duplicate rows

 Ensures accurate, clean results

 Works on single or multiple columns

Syntax:

SELECT DISTINCT column1, column2


FROM table_name

Parameters:

 column1, column2: Names of the fields of the table.

 Table_name: Table from where we want to fetch the records.

Note: If used on multiple columns, DISTINCT returns unique combinations of


values across those columns.

Examples of DISTINCT in SQL

Let’s create a sample table and populate it with some duplicate entries. We
will see some examples of using the DISTINCT keyword with a sample
students table.

Query:

CREATE TABLE students (

ROLL_NO INT,

NAME VARCHAR(50),

ADDRESS VARCHAR(100),

PHONE VARCHAR(20),

AGE INT
);

INSERT INTO students (ROLL_NO, NAME, ADDRESS, PHONE, AGE)

VALUES

(1, 'Shubham Kumar', '123 Main Street, Bangalore', '9876543210', 23),

(2, 'Shreya Gupta', '456 Park Road, Mumbai', '9876543211', 23),

(3, 'Naveen Singh', '789 Market Lane, Delhi', '9876543212', 26),

(4, 'Aman Chopra', '246 Forest Avenue, Kolkata', '9876543213', 22),

(5, 'Aditya Patel', '7898 Ocean Drive, Chennai', '9876543214', 27),

(6, 'Avdeep Desai', '34 River View, Hyderabad', '9876543215', 24),

(7, 'Shubham Kumar', '123 Main Street, Bangalore', '9876543210', 23), --


Duplicate

(8, 'Shreya Gupta', '456 Park Road, Mumbai', '9876543211', 23), --


Duplicate

(9, 'Naveen Singh', '789 Market Lane, Delhi', '9876543212', 26), --


Duplicate

(10, 'Aditya Patel', '7898 Ocean Drive, Chennai', '9876543214', 27), --


Duplicate

(11, 'Aman Chopra', '246 Forest Avenue, Kolkata', '9876543213', 22), --


Duplicate

(12, 'Avdeep Desai', '34 River View, Hyderabad', '9876543215', 24); --


Duplicate

Output:
ROLL_N AG
O NAME ADDRESS PHONE E

Shubham 123 Main Street, 98765432


1 23
Kumar Bangalore 10

456 Park Road, 98765432


2 Shreya Gupta 23
Mumbai 11

98765432
3 Naveen Singh 789 Market Lane, Delhi 26
12

246 Forest Avenue, 98765432


4 Aman Chopra 22
Kolkata 13

7898 Ocean Drive, 98765432


5 Aditya Patel 27
Chennai 14

34 River View, 98765432


6 Avdeep Desai 24
Hyderabad 15

Shubham 123 Main Street, 98765432


7 23
Kumar Bangalore 10

456 Park Road, 98765432


8 Shreya Gupta 23
Mumbai 11

98765432
9 Naveen Singh 789 Market Lane, Delhi 26
12

10 Aditya Patel 7898 Ocean Drive, 98765432 27


ROLL_N AG
O NAME ADDRESS PHONE E

Chennai 14

246 Forest Avenue, 98765432


11 Aman Chopra 22
Kolkata 13

34 River View, 98765432


12 Avdeep Desai 24
Hyderabad 15

Example 1: Fetch Unique Names from the NAME Field.

The query returns only unique names, eliminating the duplicate entries from
the table.

Query:

SELECT DISTINCT NAME FROM students;

Output:

output

Example 2: Fetching Unique Combinations of Multiple Columns

This query retrieves distinct combinations of NAME and AGE — if two rows
have the same name and age, only one of them will appear in the result set.

Query:
SELECT DISTINCT NAME, AGE FROM students;

Output:

AG
NAME E

Shubham
23
Kumar

Shreya Gupta 23

Naveen Singh 26

Aman Chopra 22

Aditya Patel 27

Avdeep Desai 24

Example 3: Using DISTINCT with the ORDER BY Clause

We can combine the DISTINCT keyword with the ORDER BY clause to filter
unique values while sorting the result set. This query retrieves the unique
ages from the students table and sorts them in ascending order

Query:

SELECT DISTINCT AGE FROM students ORDER BY AGE;

Output:

AG
E

2
AG
E

2
3

2
4

2
6

2
7

Example 4: Using DISTINCT with Aggregate Functions (e.g.,


COUNT())

Here, we will check the COUNT() function with a DISTINCT clause, which will
give the total number of students by using the COUNT() function.

Query:

SELECT COUNT(DISTINCT ROLL_NO) FROM Students ;

Output:

COUNT(DISTINCT
AGE)

Example 5: DISTINCT with NULL Values


In SQL, the DISTINCT keyword treats NULL as a unique value. NULL is treated
as a distinct value, so it will appear only once if there are multiple NULLs.

Query:

INSERT INTO students (ROLL_NO, NAME, ADDRESS, PHONE, AGE)

VALUES (13, 'John Doe', '123 Unknown Street', '9876543216', NULL);

SELECT DISTINCT AGE FROM students;

Output:

AGE

23

26

22

27

24

NUL
L

SQL ORDER BY

The ORDER BY clause in SQL is used to sort query results based on one or
more columns in either ascending (ASC) or descending (DESC) order.
Whether you are presenting data to users or analyzing large datasets,
sorting the results in a structured way is essential.
 By default, it sorts in ascending order (lowest to highest).

 To sort in descending order, use the DESC keyword.

Syntax:

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.

SQL ORDER BY Clause Examples

We have created a Student table that stores student data including their
roll_no, name, age, addess, and phone. Let's look at some examples of the
SQL ORDER BY clause to understand it's working in SQL. We will use the
following table in examples.

roll_n ag
o e name address phone

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

98765432
2 18 Mohit Thakur 321 Main St, Mumbai
01

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11
roll_n ag
o e name address phone

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

Now consider the above database table and find the results of different
queries.

Example 1 : Sort by a Single Column

In this example, we will fetch all data from the table Student and sort the
result in descending order according to the column ROLL_NO.

Query:

SELECT * FROM students ORDER BY ROLL_NO DESC;

Output:
roll_n ag
o e name address phone

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
2 18 Mohit Thakur 321 Main St, Mumbai
01

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

In the above example, if we want to sort in ascending order we have to use


ASC in place of DESC.

Example 2 : Sort by Multiple Columns

In this example, we will fetch all data from the table Student and then sort
the result in descending order first according to the column age and then in
ascending order according to the column name.

To sort according to multiple columns, separate the names of columns by the


(,) operator.
Query:

SELECT * FROM students ORDER BY age DESC , name ASC;

Output:

roll_n ag
o e name address phone

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

2 18 Mohit Thakur 321 Main St, Mumbai 98765432


roll_n ag
o e name address phone

01

The result is first sorted by Age in descending order. For rows with the same
Age, it’s further sorted by Name in ascending order.

Sorting By Column Number

Instead of using column names, you can sort results using the position of a
column in the SELECT list. The number must be greater than 0 and not
exceed the number of selected columns.

 Using column numbers in ORDER BY reduces query readability.

 Referring to columns by name is clearer and easier to understand.

 Changing column order in SELECT doesn’t affect ORDER BY when using


names.

 Prefer column names over numbers for maintainable SQL code.

Syntax:

ORDER BY Column_Number asc/desc;

Example of Sorting By Column Number

Here we take an example to sort a database table according to column 1 i.e


Roll Number. For this a query will be:

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
Output:

Roll_n
o Name Address

1 HARSH DELHI

2 PRATIK BIHAR

3 RIYANKA SILIGURI

RAMNAGA
4 DEEP
R

SAPTAR
5 KOLKATA
HI

DHANRA BARABAJA
6
J R

GHAZIABA
7 ROHIT
D

8 NIRAJ ALIPUR

Explanation: ORDER BY 1 means sorting values according to first column in


the SELECT statement.

3. DML - Data Manipulation Language


DML commands are used to manipulate the data stored in database tables.
With DML, you can insert new records, update existing ones, delete
unwanted data or retrieve information.

Common DML Commands

Comma
nd Description Syntax

INSERT INTO table_name (column1,


Insert data into a
INSERT column2, ...) VALUES (value1,
table
value2, ...);

UPDATE table_name SET column1 =


Update existing data
UPDATE value1, column2 = value2 WHERE
within a table
condition;

Delete records from DELETE FROM table_name WHERE


DELETE
a database table condition;

Example:

INSERT INTO employees (first_name, last_name, department)


VALUES ('Jane', 'Smith', 'HR');

This query inserts a new record into employees table with first name 'Jane',
last name 'Smith' and department 'HR'.

SQL INSERT INTO Statement

INSERT INTO statement is used to add new rows to an existing table. It can
insert values into all columns, specific columns, or even copy data from
another table. This command is essential for populating databases with
meaningful records such as customers, employees or students.

Let’s explore different ways to use the INSERT INTO statement:

1. Inserting Data into All Columns


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, value3, ...);

Parameters:

 table_name: name of the table where data will be inserted

 value1, value2... : values that correspond to each column in order.

Example: Let’s see how the INSERT INTO statement works with practical
examples.

CREATE DATABASE StudentDB;


USE StudentDB;

CREATE TABLE Student (


ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15),
AGE INT );

INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)


VALUES (1, 'Liam', 'New York', 'xxxxxxxxxx', 18),
(2, 'Sophia', 'Berlin', 'xxxxxxxxxx', 18),
(3, 'Akira', 'Tokyo', 'xxxxxxxxxx', 20),
(4, 'Carlos', 'Tokyo', 'xxxxxxxxxx', 18);

Output

ROLL_N NAM ADDRE AG


O E SS PHONE E

New xxxxxxx
1 Liam 18
York xxx
ROLL_N NAM ADDRE AG
O E SS PHONE E

Sophi xxxxxxx
2 Berlin 18
a xxx

xxxxxxx
3 Akira Tokyo 20
xxx

Carlo xxxxxxx
4 Tokyo 18
s xxx

If we don’t want to specify the column names (and you’re inserting data into
all columns), we can directly insert values in the order they appear in the
table structure. Here's an example:

Query:

INSERT INTO Student


VALUES (5, 'Isabella', 'Rome', 'xxxxxxxxxx', 19);

Output

ROLL_N ADDRE AG
O NAME SS PHONE E

New xxxxxxx
1 Liam 18
York xxx

xxxxxxx
2 Sophia Berlin 18
xxx

xxxxxxx
3 Akira Tokyo 20
xxx
ROLL_N ADDRE AG
O NAME SS PHONE E

xxxxxxx
4 Carlos Tokyo 18
xxx

Isabell xxxxxxx
5 Rome 19
a xxx

2. Inserting Data into Specific Columns

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, value3, ...);

Parameters:

 table_name: name of the table.

 column1, column2..: name of first column, second column.

 value1, value2, value3..: the values for each specified column of


the new record.

Example: Let’s say we only want to insert the student's ID, name, and age
into the Student table, and leave the address and phone number as NULL
(the default value).

INSERT INTO Student (ROLL_NO, NAME, AGE)


VALUES (6, 'Hiroshi', 19);

Output
ROLL_N ADDRE AG
O NAME SS PHONE E

New xxxxxxx
1 Liam 18
York xxx

xxxxxxx
2 Sophia Berlin 18
xxx

xxxxxxx
3 Akira Tokyo 20
xxx

xxxxxxx
4 Carlos Tokyo 18
xxx

Isabell xxxxxxx
5 Rome 19
a xxx

Hirosh
6 NULL NULL 19
i

Note: Columns not included in INSERT statement are filled with default
values (typically NULL).

3. Inserting Multiple Rows at Once

Instead of running multiple INSERT INTO commands, you can insert multiple
rows into a table in a single query. This is more efficient and reduces the
number of database operations.

Syntax

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...), (value1, value2, ...), (value1, value2, ...);

Example: If we want to add multiple students to Student table in one go,


query would look like this:
INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)
VALUES
(7, 'Mateo Garcia', 'Madrid', 'xxxxxxxxxx', 15),
(8, 'Hana Suzuki', 'Osaka', 'xxxxxxxxxx', 18),
(9, 'Oliver Jensen', 'Copenhagen', 'xxxxxxxxxx', 17),
(10, 'Amelia Brown', 'London', 'xxxxxxxxxx', 17);

Output

ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxx
1 Liam New York 18
xxx

xxxxxxx
2 Sophia Berlin 18
xxx

xxxxxxx
3 Akira Tokyo 20
xxx

xxxxxxx
4 Carlos Tokyo 18
xxx

xxxxxxx
5 Isabella Rome 19
xxx

6 Hiroshi NULL NULL 19

7 Mateo Madrid xxxxxxx 15


ROLL_N AG
O NAME ADDRESS PHONE E

Garcia xxx

Hana xxxxxxx
8 Osaka 18
Suzuki xxx

Oliver Copenhag xxxxxxx


9 17
Jensen en xxx

Amelia xxxxxxx
10 London 17
Brown xxx

Explanation:

 Faster than multiple single inserts

 For very large data (>1000 rows), use bulk insert

4. Inserting Data from One Table into Another Table

We can also copy data from one table into another table using the INSERT
INTO SELECT statement. This is very useful when we want to move or
replicate data from one table to another without manually typing all the data.

Here, we are using below table OldStudent as another table and we will
insert its rows into Student table using different methods.

ROLL_N ADDRE AG
O NAME SS PHONE E

Arjun 99999999
101 Mumbai 21
Mehta 99
ROLL_N ADDRE AG
O NAME SS PHONE E

Emily 88888888
102 Sydney 22
Clark 88

77777777
103 Kenji Sato Tokyo 19
77

Method 1: Insert All Columns from Another Table

Inserts every column from source table into destination table

INSERT INTO target_table


SELECT * FROM source_table;

Example: If you want to copy all data from the OldStudent table into the
Student table, use this query:

INSERT INTO Student


SELECT * FROM OldStudent;

Output

ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
1 Liam New York 18
x

xxxxxxxxx
2 Sophia Berlin 18
x

xxxxxxxxx
3 Akira Tokyo 20
x

4 Carlos Tokyo xxxxxxxxx 18


ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
5 Isabella Rome 19
x

6 Hiroshi NULL NULL 19

Mateo xxxxxxxxx
7 Madrid 15
Garcia x

Hana xxxxxxxxx
8 Osaka 18
Suzuki x

Oliver Copenhag xxxxxxxxx


9 17
Jensen en x

Amelia xxxxxxxxx
10 London 17
Brown x

Arjun 99999999
101 Mumbai 21
Mehta 99

88888888
102 Emily Clark Sydney 22
88

77777777
103 Kenji Sato Tokyo 19
77
Method 2: Insert Specific Columns from Another Table

Allows inserting only selected columns from the source table.

INSERT INTO target_table (col1, col2, ...)


SELECT col1, col2, ...
FROM source_table;

Example: Let’s say we want to copy only the Name and Age columns from
OldStudent into Student:

INSERT INTO Student (Name, Age)


SELECT Name, Age
FROM OldStudent;

Output

ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxx
Liam New York 18
1 xxx

xxxxxxx
Sophia Berlin 18
2 xxx

xxxxxxx
Akira Tokyo 20
3 xxx

xxxxxxx
Carlos Tokyo 18
4 xxx
ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxx
Isabella Rome 19
5 xxx

6 Hiroshi NULL NULL 19

Mateo xxxxxxx
Madrid 15
7 Garcia xxx

Hana xxxxxxx
Osaka 18
8 Suzuki xxx

Oliver Copenhag xxxxxxx


17
9 Jensen en xxx

Amelia xxxxxxx
London 17
10 Brown xxx

Arjun
NULL NULL 21
NULL Mehta

NULL Emily Clark NULL NULL 22

NULL Kenji Sato NULL NULL 19

Note: Columns not included in INSERT statement (ROLL_NO, ADDRESS,


PHONE) are automatically filled with NULL in target table.

Method 3: Insert Specific Rows Based on Condition


You can also insert specific rows based on a condition by using the WHERE
clause with the SELECT statement.

INSERT INTO target_table


SELECT * FROM source_table
WHERE condition;

Example: If we want to copy only students older than 20 years from


OldStudent to Student, we would write:

INSERT INTO Student


SELECT * FROM OldStudent
WHERE Age > 20;

Output

ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
1 Liam New York 18
x

xxxxxxxxx
2 Sophia Berlin 18
x

xxxxxxxxx
3 Akira Tokyo 20
x

xxxxxxxxx
4 Carlos Tokyo 18
x
ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
5 Isabella Rome 19
x

6 Hiroshi NULL NULL 19

Mateo xxxxxxxxx
7 Madrid 15
Garcia x

Hana xxxxxxxxx
8 Osaka 18
Suzuki x

Oliver Copenhag xxxxxxxxx


9 17
Jensen en x

Amelia xxxxxxxxx
10 London 17
Brown x

Arjun 99999999
101 Mumbai 21
Mehta 99

88888888
102 Emily Clark Sydney 22
88

SQL UPDATE Statement


The UPDATE statement in SQL is used to modify existing records in a table
without deleting them. It allows updating one or multiple columns, with or
without conditions, to keep data accurate and consistent.

 Change specific column values in selected rows

 Apply targeted updates using WHERE

 Update single or multiple columns at once

 More efficient than deleting and re-inserting rows

 Maintains data integrity by modifying in place

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;

Parameters

 table_name: Name of the table you want to update.

 SET: The column(s) you want to update and their new values.

 WHERE: Filters the specific rows you want to update.

Note: The SET keyword assigns new values to columns, while the WHERE
clause selects which rows to update. Without WHERE, all rows will be
updated.

Examples of SQL UPDATE Statement

Let’s begin by creating a Customer table with some sample data. This table
contains each customer's unique ID, name, last name, phone number and
country. We will use it to demonstrate how the UPDATE statement works in
SQL.

Query:

CREATE TABLE Customer (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT,
Phone VARCHAR(15)
);

-- Insert sample data


INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,
Age, Phone)
VALUES
(1, 'Shubham', 'Thakur', 'India', 23, '9415536635'),
(2, 'Aman', 'Chopra', 'Australia', 21, '9812345678'),
(3, 'Naveen', 'Tulasi', 'Sri Lanka', 24, '9123456789'),
(4, 'Aditya', 'Arpan', 'Austria', 21, '9876543210'),
(5, 'Nishant', 'Jain', 'Spain', 22, '7012345678');

Output

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

94155366
1 Shubham Thakur India 23
35

Australi 98123456
2 Aman Chopra 21
a 78

Sri 91234567
3 Naveen Tulasi 24
Lanka 89

98765432
4 Aditya Arpan Austria 21
10

5 Nishant Jain Spain 22 70123456


Customer CustomerNa LastNa Countr Ag
ID me me y e Phone

78

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;

Output:

Explanation: Only the rows where Age is 22 will be updated, and the
CustomerName will be set to 'Nitin'.

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;

Output:

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

94155366
1 Satyam Thakur USA 23
35
Customer CustomerNa LastNa Countr Ag
ID me me y e Phone

Australi 98123456
2 Aman Chopra 21
a 78

Sri 91234567
3 Naveen Tulasi 24
Lanka 89

98765432
4 Aditya Arpan Austria 21
10

70123456
5 Nishant Jain Spain 22
78

Explanation: For the row where CustomerID is 1, both CustomerName and


Country will be updated simultaneously.

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

Output

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

1 Shubham Thakur USA 23 94155366


Customer CustomerNa LastNa Countr Ag
ID me me y e Phone

35

Australi 98123456
2 Shubham Chopra 21
a 78

Sri 91234567
3 Shubham Tulasi 24
Lanka 89

98765432
4 Shubham Arpan Austria 21
10

70123456
5 Shubham Jain Spain 22
78

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 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.

SQL DELETE Statement


The SQL DELETE statement is used to remove specific rows from a table
while keeping the table structure intact. It is different from DROP, which
deletes the entire table.

 Removes rows based on conditions.

 Retains table schema, constraints, and indexes.

 Can delete a single row or all rows.

 Useful for cleaning or managing datasets.

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.

Examples of SQL DELETE Statement

Assume we have created a table named GFG_Employee in SQL, which


contains the personal details of the Employee including their id, name, email
and department etc. as shown below.

CREATE TABLE GFG_Employees (


id INT PRIMARY KEY,
name VARCHAR (20) ,
email VARCHAR (25),
department VARCHAR(20)
);

INSERT INTO GFG_Employees (id, name, email, department) VALUES


(1, 'Jessie', '[email protected]', 'Development'),
(2, 'Praveen', '[email protected]', 'HR'),
(3, 'Bisa', '[email protected]', 'Sales'),
(4, 'Rithvik', '[email protected]', 'IT'),
(5, 'Suraj', '[email protected]', 'Quality Assurance'),
(6, 'Om', '[email protected]', 'IT'),
(7, 'Naruto', '[email protected]', 'Development');

Select * From GFG_Employees

Output

id name email department

1 Jessie [email protected] Development

Pravee praveen_dagger@yahoo
2 HR
n .com

3 Bisa [email protected] Sales

4 Rithvik [email protected] IT

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

7 Naruto [email protected] Development

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

Output:

id name email department

1 Jessie [email protected] Development

Pravee praveen_dagger@yahoo
2 HR
n .com

3 Bisa [email protected] Sales

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

7 Naruto [email protected] Development

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

Output
id name email department

Pravee praveen_dagger@yahoo
2 HR
n .com

3 Bisa [email protected] Sales

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

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;

Output:

i nam ema departm


d e il ent

All of the records in the table will be deleted, there are no records left to
display. The table GFG_Employees will become empty.

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.

4. DCL - Data Control Language

DCL (Data Control Language) includes commands such as GRANT and


REVOKE which mainly deal with the rights, permissions and other controls of
the database system. These commands are used to control access to data in
the database by granting or revoking permissions.

Common DCL Commands


Command Description Syntax

Assigns new privileges to GRANT privilege_type


a user account, allowing [(column_list)] ON
GRANT access to specific [object_type] object_name
database objects, actions TO user [WITH GRANT
or functions. OPTION];

Removes previously
REVOKE [GRANT OPTION
granted privileges from a
FOR] privilege_type
user account, taking away
REVOKE [(column_list)] ON
their access to certain
[object_type] object_name
database objects or
FROM user [CASCADE];
actions.

Example:

GRANT SELECT, UPDATE ON employees TO user_name;

This command grants the user user_name the permissions to select and
update records in the employees table.

5. TCL - Transaction Control Language

Transactions group a set of tasks into a single execution unit. Each


transaction begins with a specific task and ends when all the tasks in the
group are successfully completed. If any of the tasks fail, transaction fails.
Therefore, a transaction has only two results: success or failure.

Common TCL Commands

Command Description Syntax

BEGIN BEGIN TRANSACTION


Starts a new transaction
TRANSACTION [transaction_name];

Saves all changes made


COMMIT COMMIT;
during the transaction
Command Description Syntax

Undoes all changes made


ROLLBACK ROLLBACK;
during the transaction

Creates a savepoint within SAVEPOINT


SAVEPOINT
the current transaction savepoint_name;

Example:

BEGIN TRANSACTION;
UPDATE employees SET department = 'Marketing' WHERE department =
'Sales';
SAVEPOINT before_update;
UPDATE employees SET department = 'IT' WHERE department = 'HR';
ROLLBACK TO SAVEPOINT before_update;
COMMIT;

In this example, a transaction is started, changes are made and a savepoint


is set. If needed, the transaction can be rolled back to the savepoint before
being committed.

Chapter II

SQL Database
This section guides you through the process of creating and managing
databases. Learn how to create, select, rename, and drop databases with
practical examples.

 CREATE Database

 DROP Database

 RENAME Database

 SELECT Database

SQL CREATE DATABASE and CREATE TABLE

CREATE command in SQL is used to define new databases and tables. A


database acts as a container that holds related objects such as tables, views
and procedures, while a table stores data in rows and columns. We will learn
how to create databases and tables in SQL with the help of examples.

Creating Database

To create a new database in SQL, we use CREATE DATABASE command


followed by the database name. Database names cannot contain spaces; if
needed, an underscore (_) can be used instead.

Syntax:

CREATE DATABASE database_name;

Let’s create a simple database called GeeksForGeeks

Query:

CREATE DATABASE GeeksForGeeks;

Output
Creating a new database

Explanation: This query creates an empty database named GeeksForGeeks.


A success message will confirm that the database was created.

Note: If you try to create a database with a name that already exists, you’ll
see an error. To avoid this, either choose a new name or use IF NOT EXISTS
clause to only create database if it doesn't already exist.

Query:

CREATE DATABASE IF NOT EXISTS GeeksForGeeks;

1. Verifying Database Creation

To confirm that a new database has been created, use:

Query:

SHOW DATABASES;

Output
Database successfully created

Explanation: This command lists all databases in the system. From this list,
you can check if GeeksForGeeks has been added.

2. Switching to a Database (USE Command)

Once your database is created, we can switch to that database to begin


adding tables, inserting data and performing queries. To switch to your new
database, use the USE command.

Syntax:

USE database_name

Query:

USE GeeksForGeeks;

Explanation: After running this, any SQL operations like creating tables or
inserting data will be done within GeeksForGeeks database. This allows you
to work within the scope of the newly created database.

3. Deleting a Database
If you ever want to delete a database, use:

Query:

DROP DATABASE GeeksForGeeks;

This permanently deletes the database.

Note: Once dropped, all data inside the database will be lost permanently.

Creating Tables

A table is the core structure of a database where data is stored in rows and
columns. While creating a table, you must define:

 Column names

 Data types (e.g., INT, VARCHAR, DATE)

 Constraints (e.g., PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, FOREIGN


KEY)

Syntax:

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
...
);

Example: Creating a Student Table

Here, we are creating a table named Student to store student details like ID,
name, subject, year and marks.

CREATE TABLE Student (


StudentID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Subject VARCHAR(50),
Year INT,
Marks INT
);

Explanation: In this table, StudentID is the unique identifier (Primary Key),


Name must not be empty, Subject stores the subject name, Year represents
the study year and Marks stores the marks scored by the student.

1. Verifying Table Creation


After running the CREATE TABLE query, the system shows a success message
like Table created successfully. To confirm that the table exists, we can list all
tables in the current database using:

SHOW TABLES;

This will display all the tables created inside the database and from here you
can confirm that Student table has been successfully created.

2. Deleting a Table

If you no longer need a table, use:

DROP TABLE Student;

Explanation: This removes the Student table permanently from the


database.

SQL DROP DATABASE

The SQL DROP DATABASE statement is an important command used to


permanently delete a database from the Database Management System
(DBMS). When executed, this command removes the database and all
its associated objects, including tables, views, stored procedures, and
other entities.

In this article, we will explain the SQL DROP DATABASE statement,


its syntax, examples, best practices, and how to safely use it within
our database environment.

What is SQL DROP DATABASE?

The DROP DATABASE command in SQL is used to completely delete a


database and all of its objects, such as tables, indexes, views, and
other dependent objects. Once executed, this operation cannot be undone,
so it's crucial to back up the database before performing this action.

This command is typically used in scenarios where a database is no longer


required or needs to be removed for reorganization. Before running the
command, ensure that we have appropriate permissions to drop the
database, as only database administrators typically have the necessary
rights.

 Purpose: To remove a database from the DBMS permanently.

 Outcome: All data, schema, and database objects are erased.

Syntax

DROP DATABASE database_name;

 database_name: The name of the database you wish to drop.

Examples of SQL DROP DATABASE

To demonstrate the functionality of the SQL DROP DATABASE command,


Let's look at some examples of the DROP DATABASE statement in SQL

Step 1: Create a Sample Database

First, let's create a database on which we will run the query. This will allow
us to perform operations and test the SQL DROP DATABASE command.

CREATE DATABASE GeeksForGeeks;

Step 2: Verify the Database

To confirm that the GeeksForGeeks database was successfully created, use


the following command to list all databases:

Query:

SHOW DATABASES;
Output

List of Databases

Step 3: Drop the Database

Now that the database is confirmed to exist, let’s use the DROP
DATABASE command, to delete the database 'GeeksforGeeks'.

Query:

DROP DATABASE GeeksForGeeks;

Output

DROP DATABASE

Step 4: Verify the Deletion

After the database has been deleted/dropped successfully we will now


verify that whether the database exist in the system or not. So, we will once
again use the SHOW DATABASES command and verify that the
GeeksForGeeks database has been deleted or not.

Query

SHOW DATABASES;

Output

Deleted Data

SQL DROP DATABASE IF EXISTS

To avoid any error while running the DROP DATABASE command use the IF
EXISTS clause, which will delete the database only if it exists in the system.

Syntax

DROP DATABASE IF EXISTS Database_Name;

Example:

DROP DATABASE IF EXISTS GeeksForGeeks;

This command will check if the database exists before attempting to drop it,
making it safer to run in scripts or on production systems.

Important Points About SQL DROP DATABASE Statement

 Deleting a Database: Deleting a database is a permanent action and


will result in the loss of all information stored in the database.
 Backup: Its always been a good practice to take proper backup of the
database before performing any delete operation on it.

 Privileges: Make sure you have the necessary privilege to delete the
database. Usually an admin can delete the database.

 Database State: A database can be dropped regardless of its state:


offline, read-only, suspect, and so on.

 Database Snapshots: Dropping a database snapshot deletes the


database snapshot from an instance of SQL Server and deletes the
physical NTFS File System sparse files used by the snapshot.

 Replication: To drop a database published for transactional


replication, or published or subscribed to merge replication, you must
first remove replication from the database.

 System Databases: System databases cannot be directly dropped or


edited by the user.

Conclusion

The SQL DROP DATABASE statement is an essential tool for database


administrators to remove unnecessary databases from the system. While the
command is simple, it is important to use it with caution due to
its irreversible nature. Always ensure that a backup is taken, and only
execute this command with the correct privileges. In summary, the SQL
DROP DATABASE statement is a powerful way to delete databases from
a DBMS, and with the proper precautions, it can be used efficiently to
manage and maintain your databases.

SQL Query to Rename Database


Renaming a database in SQL is an essential task that database
administrators and developers frequently perform. Whether you’re
reorganizing your data, correcting naming conventions, or simply updating
your project structure, knowing how to rename a database properly is
critical.

In this article, we'll cover everything you need to know about renaming a
database using SQL, including the exact commands for various SQL-based
database management systems (DBMS) such as MySQL, PostgreSQL, and
SQL Server.

How to Rename Database in SQL?

To rename a database in SQL, we will need to use the ALTER


DATABASE command. The syntax varies slightly between
different SQL platforms, but the core functionality remains the same. The
ALTER DATABASE statement allows us to modify the properties of a database,
including its name.

However, it’s important to note that while SQL Server uses the ALTER
DATABASE statement with a MODIFY NAME clause, MySQL no longer
supports the RENAME DATABASE statement as of version 5.1.23. To
change the name of a database in SQL, use the following syntax:

SQL Server:

ALTER DATABASE [current_database_name]


MODIFY NAME = [new_database_name];

MySQL:

For MySQL versions 5.1.23 and later, the RENAME DATABASE command is
no longer supported. Instead, you need to follow an alternative approach to
rename the database. The steps involves creating a new database
and transferring the tables from the old database to the new one. Here's
how you can do it:

1. Create a new database:

CREATE DATABASE new_database_name;

2. Transfer all the tables from the old database to the new one:
RENAME TABLE old_database_name.table1 TO new_database_name.table1;
RENAME TABLE old_database_name.table2 TO new_database_name.table2;
-- Repeat for all tables in the old database

This process works because MySQL does not allow the RENAME DATABASE
command anymore due to potential issues with the operation. So, we need
to create a new database, transfer the data and then remove the old one.

PostgreSQL:

For PostgreSQL, you can rename a database using the ALTER


DATABASE command:

ALTER DATABASE current_database_name RENAME TO new_database_name;

SQL Rename Database Example

Let's look at an example of how to rename a database in SQL. First, we


will create a database which will be renamed in the example:

Step 1: Create a Database

CREATE DATABASE Test;

Output:

The test database is created.

Step 2: Rename Database in SQL Server


In this example, we will use the ALTER command with MODIFY NAME
clause to rename the database in SQL Server

ALTER DATABASE Test MODIFY NAME = Example

Output:

The database name is changed from Test to Example.

Important Considerations When Renaming a Database

 Database Availability: Please be aware that renaming a database


may temporarily render it inaccessible while the process is underway. It
is advisable to schedule this task during off-peak hours, particularly in
a production environment.

 Dependencies: Ensure that any applications, scripts, or users relying


on the database name are updated to reflect the new designation.

 Permissions: Confirm that you possess the requisite permissions to


rename the database, which typically necessitates administrative or
root-level access.

 Backups: Prior to renaming a database, it is prudent to create a


backup, especially in a production environment, to mitigate the risk of
data loss should any issues arise.
Troubleshooting Database Rename Issues

 Database is in Use: If you encounter an error saying that the


database is in use, you may need to disconnect active users or close
any applications connected to the database before renaming it.

 Insufficient Privileges: If you receive a permission error, ensure you


have administrative privileges or sufficient rights to modify the
database. You might need to check your user role and permissions.

 Database Name Constraints: Some DBMSs have restrictions on


certain characters or reserved words in database names. Ensure your
new database name adheres to the naming conventions for the
specific SQL system you are using.

Conclusion

Renaming a database in SQL is a straightforward process, but it requires


careful consideration and proper syntax to avoid errors. Whether you're
using SQL Server, MySQL, or PostgreSQL, knowing how to rename a database
using the correct SQL commands is essential for efficient database
management. Always ensure that you follow best practices, including making
backups and ensuring that all dependencies are updated, to minimize
disruptions when renaming your databases.

SQL Select Database


The USE DATABASE statement is a command in certain SQL-based
database management systems that allows users to select and set a specific
database as the default for the current session. By selecting a database,
subsequent queries are executed within the context of that database,
making it easier to interact with tables and other objects contained within it.

Additionally, the SELECT statement in SQL is used to query and retrieve


data from the tables within the selected database. In this article, We will
learn about SQL Select Database by understanding various examples in
detail and so on.
The USE DATABASE Statement

The USE DATABASE statement is not a standard SQL command, but rather
a variation of the USE command used in some SQL database
management systems (DBMS) to select a specific database for the
current session. Once the database is selected, subsequent queries are
executed within the context of that database, allowing you to interact with its
tables and objects more efficiently. This command sets the default database
for subsequent queries in that session.

Important Note: In some DBMS, such as PostgreSQL, the USE command is


not supported, and you need to connect to the database at the time of
establishing the connection, rather than using the USE command.

Syntax:

USE database_name;

Example of SQL Select Database

Let’s take a look at how to select a database in SQL, using MySQL as an


example. Suppose you have a database called company_db that contains
employee information.

1. Create a Database: To begin, you can create a new database if it


doesn’t already exist

CREATE DATABASE GeeksforGeeks;

2. Select the Database: To set GeeksforGeeks as the active database,


use the USE command

USE GeeksforGeeks;

Once you’ve selected the database, any queries you execute will be
performed within the context of GeeksforGeeks until you select another
database.

How to Query Data from the Selected Database

The SELECT statement in SQL is used to query and retrieve data from the
tables within the selected database. Here are some key ways to use
the SELECT statement effectively. Consider the following
table, employees as an example:
Table: employees

ag departm salar
id name e ent y

5000
1 Alice 30 Sales
0

6000
2 Bob 40 Marketing
0

Charli 5500
3 35 Sales
e 0

4500
4 David 28 HR
0

6500
5 Eve 45 Marketing
0

7000
6 Frank 50 HR
0

4800
7 Grace 29 IT
0

8 Hanna 38 IT 5300
ag departm salar
id name e ent y

h 0

1. Basic SELECT Statement

The most basic form of a query is the SELECT statement. It is used to


retrieve all columns and rows from a table.

SELECT * FROM employees;

Output:

ag departm salar
id name e ent y

5000
1 Alice 30 Sales
0

6000
2 Bob 40 Marketing
0

Charli 5500
3 35 Sales
e 0
ag departm salar
id name e ent y

4500
4 David 28 HR
0

6500
5 Eve 45 Marketing
0

7000
6 Frank 50 HR
0

4800
7 Grace 29 IT
0

Hanna 5300
8 38 IT
h 0

Explanation: Retrieves all columns and all rows from the employees table.

2. Selecting Specific Columns

We can select specific columns instead of retrieving all columns.

SELECT name, age FROM employees;

Output:

ag
name e

Alice 30

Bob 40
ag
name e

Charli
35
e

David 28

Eve 45

Frank 50

Grace 29

Hanna
38
h

Explanation: Retrieves only the name and age columns for all rows.

3. Filtering Results with WHERE

The WHERE clause filters the records based on a specified condition.

SELECT name, age FROM employees WHERE age >= 35;

Output:
ag
name e

Bob 40

Charli
35
e

Eve 45

Frank 50

Hanna
38
h

Explanation: Retrieves names and ages of employees older than 35.

4. Sorting Results with ORDER BY

The ORDER BY clause sorts the result set based on one or more columns.

SELECT name, age FROM employees ORDER BY age DESC;

Output:

ag
name e

Frank 50

Eve 45

Bob 40
ag
name e

Hanna
38
h

Charli
35
e

Alice 30

Grace 29

David 28

Explanation: Retrieves names and ages of all employees sorted by age in


descending order.

5. Limiting Results with LIMIT Clause

The LIMIT clause restricts the number of rows returned.

SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;

Output:

salar
name y

Fran 7000
k 0

Eve 6500
salar
name y

6000
Bob
0

Explanation: Retrieves the top 3 highest-paid employees, ordered by salary


in descending order.

6. Aggregating Data with GROUP BY and Aggregation Functions

The GROUP BY clause groups rows that have the same values into summary
rows, often used with aggregation functions like AVG, COUNT, MAX, MIN,
and SUM.

SELECT department, AVG(salary) AS average_salary FROM employees


GROUP BY department;

Output:

departm average_sal
ent ary

Sales 52500

Marketin
62500
g

HR 57500

IT 50500

Explanation: Calculates the average salary for each department.


Conclusion

The USE DATABASE statement and the SELECT query are fundamental
parts of working with SQL databases. By selecting a database, you set the
context for all subsequent queries within that session.
The SELECT statement, combined with filtering, sorting, and aggregation,
allows you to efficiently retrieve and manipulate data stored in your
database. Understanding these commands and their syntax will help you
create powerful queries and streamline data retrieval processes.

Chapter III
SQL Tables

Tables are the core data structures in databases, organizing data into rows
and columns. This section covers how to create, modify, and manage tables
effectively.

 CREATE TABLE

 DROP TABLE

 RENAME TABLE

 TRUNCATE TABLE

 COPY TABLE

 TEMP TABLE

 ALTER TABLE

SQL CREATE TABLE


Creating a table is one of the first and most important steps in building a
database. The CREATE TABLE command in SQL defines how your data will be
stored, including the table name, column names, data types, and rules
(constraints) such as NOT NULL, PRIMARY KEY, and CHECK.

 Defines a new table in the database.

 Specifies columns, their data types, and sizes.

 Applies constraints such as NOT NULL, PRIMARY KEY, and CHECK.

 Ensures accuracy, consistency, and organized data storage.

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.

Example: Create a Customer Table

Let’s walk through a practical example where we create a Customer table


that stores customer data. We will define various columns such as
CustomerID, CustomerName, Country, Age, and Phone with appropriate data
types and constraints.

Query:

CREATE TABLE Customer(

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

LastName VARCHAR(50),

Country VARCHAR(50),

Age INT CHECK (Age >= 0 AND Age <= 99),

Phone int(10)

);

Output:

Explanation:

 CustomerID is an integer and serves as the PRIMARY KEY, ensuring


each record is unique.

 CustomerName, LastName, and Country are VARCHAR fields to store


variable-length text.

 Age has a CHECK constraint, ensuring it’s within the range of 0 to 99.

 Phone is an integer field, although in real scenarios, a VARCHAR would


often be used for storing phone numbers to allow for leading zeros and
formatting.

Inserting Data into the Table

After creating the table, you can use INSERT INTO command to add data into
it. Here is how to add some sample records into the Customer table:
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,
Age, Phone)

VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),

(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),

(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),

(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),

(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

Note: If you are working with a large amount of data, consider using bulk
inserts or importing data from external files to optimize performance.

Create Table from Existing Table

We can also create a new table based on the structure (and optionally the
data) of an existing table. The CREATE TABLE AS SELECT command allows us
to duplicate an entire table or select specific columns to form a new one. The
following query creates a new table called SubTable that contains
CustomerID and CustomerName from the existing Customer table.

Syntax:

CREATE TABLE new_table_name AS

SELECT column1, column2, ...

FROM existing_table_name

WHERE ...;

In this example, we create a new table SubTable that contains just the
CustomerID and CustomerName columns from the Customer table. This
method is useful for creating backups or performing quick data migrations.

Query:

CREATE TABLE SubTable AS

SELECT CustomerID, CustomerName

FROM customer;

Output:

Note: We can use * instead of column name to copy whole table to another
table.

Key Tips for Using CREATE TABLE in SQL


To ensure the smooth creation and management of your tables, keep these
points in mind:

1. The CREATE TABLE statement can also define constraints like NOT NULL,
UNIQUE, and DEFAULT.

2. 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. Always define appropriate data types for each column


(e.g., VARCHAR(50) for names and INT for IDs) to optimize performance and
storage.

4. After creating a table, use the following command to view the structure of
your table:

DESC table_name;

4. 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

The DROP TABLE command in SQL is a powerful and essential tool used to
permanently delete a table from a database, along with all of its data,
structure, and associated constraints such as indexes, triggers, and
permissions. When executed, this command removes the table and all its
contents, making it unrecoverable unless backed up.

In this article, We will learn about SQL DROP TABLE by understanding its
examples, and cover important points to help you manage your database
tables effectively.

DROP TABLE in SQL

The DROP TABLE statement in SQL is used to delete a table and all of its
data from the database permanently. This operation cannot be undone, and
once the table is dropped all data in that table is lost. Once executed, this
operation removes the table definition and all of its rows, so the table can no
longer be accessed or used. This action is irreversible which means that
once a table is dropped, it cannot be recovered unless there is a backup.

Syntax:

DROP TABLE table_name;

The syntax of the command remains the same in Oracle, SQL Server and
MySQL.

Example of DROP TABLE in SQL

To demonstrate how to use the DROP TABLE command, let's first create a
database and a table, and then we will drop it.

Step1: Create a Database and Table

First, we will create a database and table on which the SQL queries will be
run.

CREATE DATABASE NewCafe;


USE NewCafe;

CREATE TABLE categories (


CategoryID INT NOT NULL PRIMARY KEY,
CategoryName NVARCHAR(50) NOT NULL,
ItemDescription NVARCHAR(50) NOT NULL
);

INSERT INTO categories (CategoryID, CategoryName, ItemDescription)


VALUES
(1, 'Beverages', 'Soft Drinks'),
(2, 'Condiments', 'Sweet and Savory Sauces'),
(3, 'Confections', 'Sweet Breads');

SELECT * FROM categories;

Output:
At this point, the categories table has been created with three rows of
sample data.

Step2: Drop the Table

Now, let’s use the DROP TABLE statement to delete the categories table
permanently

Query:

DROP TABLE categories;

Output:

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;

Conclusion

The DROP TABLE command is an essential SQL function that helps in


maintaining and cleaning up database environments. Its ability to
permanently remove tables and all related data makes it a powerful tool, but
it should be used cautiously to avoid accidental data loss. Understanding its
syntax, options for error prevention, and its role in managing both regular
and temporary tables is key to effective database management.

ALTER (RENAME) in SQL

In SQL, making structural changes to a database is often necessary.


Whether it's renaming a table or a column, adding new columns, or
modifying data types, the SQL ALTER TABLE command plays a critical role.
This command provides flexibility to manage and adjust database
schemas without affecting the existing data. In this article, we will explain
how to rename tables and columns in SQL using the ALTER TABLE
command, along with practical examples.

What is ALTER Command in SQL?

The ALTER TABLE command in SQL allows us to modify the structure of an


existing table. Whether we need to rename a table, rename a
column, add a new column, or change the data type of a column, this
command makes it easy to apply changes without affecting the data already
stored. The ALTER command is fundamental for database management and
is often used by developers to keep schemas aligned with evolving
application needs.

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;

4. Modifying a Column Data Type


ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;

Examples of ALTER Command in SQL

Below are practical examples to help us understand how to use the ALTER
command effectively in various scenarios. These examples
includes renaming tables or columns, adding new columns, or changing
column data types.

1. Create a Sample Table

First, let's create a sample Student table to demonstrate


the ALTER command:

CREATE TABLE Student (


id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(50),
phone VARCHAR(20)
);

2. Insert Sample Data into the Table

Let's insert some data and then perform ALTER operation to understand
better about alter command.

INSERT INTO Student (id, name, age, email, phone)


VALUES
(1, 'Amit', 20, '[email protected]', '9999999999'),
(2, 'Rahul', 22, '[email protected]', '8888888888'),
(3, 'Priya', 21, '[email protected]', '7777777777'),
(4, 'Sonia', 23, '[email protected]', '6666666666'),
(5, 'Kiran', 19, '[email protected]', '5555555555');

Output
Student Table

Example 1: Rename a Column

Change the name of column name to FIRST_NAME in table Student. To


change the column name of the existing table we have to use Column
keyword before writing the existing column name to change

Syntax

ALTER TABLE Student RENAME COLUMN Column_NAME TO FIRST_NAME;

Query:

ALTER TABLE Student RENAME Column name TO FIRST_NAME;

Output

Output

Example 2: Rename a Table

In this example, we want to rename the table


from Student to Student_Details using the ALTER TABLE command,
making the name more descriptive and relevant to its content.

Query:

ALTER TABLE Student RENAME TO Student_Details;


Output

Student_Details table

Example 3: Add a New Column

To add a new column to the existing table, we first need to select the table
with ALTER TABLE command table_name, and then we will write the name
of the new column and its datatype with ADD column_name datatype. Let's
have a look below to understand better.

Syntax

ALTER TABLE table_name


ADD column_name datatype;

Query:

ALTER TABLE Student ADD marks INT;

Output

output

5. Modify a Column Data Type


In the example, the phone column is updated
from VARCHAR(20) to BIGINT to store numerical data more efficiently and
ensure data integrity for phone numbers without unnecessary characters.

Syntax

ALTER TABLE table_name


MODIFY COLUMN column_name new_datatype;

Query:

ALTER TABLE Student_Details


MODIFY COLUMN phone BIGINT;

Output

nam ag
id e e email phone

99999999
1 Amit 20 [email protected]
99

Rahu [email protected] 88888888


2 22
l m 88

[email protected] 77777777
3 Priya 21
om 77

Soni [email protected] 66666666


4 23
a m 66

Kira [email protected] 55555555


5 19
n m 55

Explanation:

 The phone column now has a BIGINT data type, suitable for storing
large numeric values.
 Existing data remains unchanged but is stored as integers instead
of strings.

Additional ALTER Command Use Cases

1. Removing a Column: In some cases, we might need to remove a


column. To do that, you can use the DROP COLUMN syntax:

ALTER TABLE Student_Details

DROP COLUMN marks;

This command deletes the marks column entirely from the table

2. Changing a Column's Default Value: We can also modify a column’s


default value using the SET DEFAULT clause:

ALTER TABLE Student_Details

ALTER COLUMN age SET DEFAULT 18;

3. Renaming a Table or Column in Different Databases: Note that SQL


syntax can vary across different database systems. Here’s how we would
rename a table or column in MySQL, MariaDB, and Oracle:

 MySQL / MariaDB: The syntax for renaming a column is similar, but


you must also use the CHANGE COLUMN command to rename a
column:

ALTER TABLE Student

CHANGE COLUMN old_column_name new_column_name datatype;

 Oracle: Oracle supports the RENAME COLUMN syntax but requires


different syntax for renaming a table:

ALTER TABLE Student RENAME COLUMN old_column_name TO


new_column_name;

Conclusion

The SQL ALTER TABLE command is an effective way to modify the


structure of an already-existing tables in a database. When necessary,
we can use ALTER TABLE to rename the entire table, rename a specific
column in SQL, or change a column name to something more descriptive.
This command is important for database administration since it also
enables the addition of new columns and the modification of data types.

SQL TRUNCATE TABLE

The TRUNCATE TABLE statement in SQL is a powerful command used to


swiftly remove all rows from a table, leaving the table structure intact. This
operation is often favored over the DELETE statement for its efficiency,
especially when dealing with large datasets.

In this article, We will learn about SQL TRUNCATE TABLE in detail with the
help of various examples and so on.

SQL TRUNCATE TABLE

 The TRUNCATE TABLE statement in SQL is used to quickly remove all


rows from a table, effectively emptying the table.

 Unlike the DELETE statement, which removes rows one at a time and
can be rolled back (depending on the database support
for transactions).

 TRUNCATE TABLE is usually more efficient because it deallocates the


data pages used by the table, rather than performing individual row
deletions.

Note: The TRUNCATE command can not be used to Truncate a Column or


Database in SQL.

Syntax

TRUNCATE TABLE Syntax is:

TRUNCATE TABLE table_name;

Example of SQL TRUNCATE TABLE

Let's understand TRUNCATE in SQL with examples. Here we will look at


different examples of the SQL TRUNCATE TABLE command.

First, we will create a demo SQL database and table, on which we will use the
TRUNCATE TABLE command.

CREATE DATABASE GEEKSFORGEEKS;


USE GEEKSFORGEEKS;

CREATE TABLE EMPLOYEE(

EMP_ID INT(4),

NAME VARCHAR(20),

AGE INT(3),

DOB DATE,

SALARY DECIMAL(7,2));

INSERT INTO EMPLOYEE VALUES(121,'AJAY KUMAR',23,'1987-09-


12',23456.32);

INSERT INTO EMPLOYEE VALUES(132,'BOBBY DEOL',34,'1989-02-


19',84164.56);

INSERT INTO EMPLOYEE VALUES(246,'ELVISH SMITH',27,'1996-01-


29',51876.97);

INSERT INTO EMPLOYEE VALUES(955,'GEORGE CLARKE',31,'1992-09-


21',91451.64);

INSERT INTO EMPLOYEE VALUES(729,'MONICA GELLER',28,'1985-11-


18',98329.43);

The following table will be created.

Records in the table

Example of TRUNCATE TABLE in SQL


In this example, we will Truncate the created table.

Query:

TRUNCATE TABLE EMPLOYEE;

Output:

Truncating data

After truncating data of our table, the data of our table has been erased but
the structure is preserved so now if we perform SELECT * FROM EMPLOYEE
command on our table we will see everything is erased and an empty set is
being returned.

No data is returned

But let's now check whether the structure of the table is deleted or it has
been preserved so we again use the DESC command to see the structure of
the table and we will see that the structure remains as it is.

Structure is preserved
SQL TRUNCATE vs DELETE

Here's a comparison of the TRUNCATE and DELETE statements in SQL


presented in a tabular format:

Feature TRUNCATE TABLE DELETE

Removes rows based on


Removes all rows from a
Operation a WHERE clause or all rows
table
if no condition is specified

WHERE
Not supported Supported
Clause

Transaction Minimal logging (usually


Fully logged (can be slower)
Logging faster)

Rollback Generally cannot be


Can be rolled back if within
(Transaction rolled back in
a transaction
Support) some DBMS

Triggers Does not fire triggers Fires triggers


Feature TRUNCATE TABLE DELETE

Cannot truncate a table


Foreign Key referenced by a foreign Can delete rows in a table
Constraints key (without disabling the referenced by a foreign key
constraint)

Resets identity seed


Identity Does not reset the identity
value (auto-increment
Reset seed value
counter)

Generally faster for large Can be slower, especially


Performance
data volumes for large data volumes

Typically used to quickly Used to remove specific


Usage
empty a table rows based on a condition

Does not automatically


Releases the storage
Space reclaim space, may require
space used by the table
Reclamation a VACUUM or similar
rows
command

Retains the table


Table Retains the table structure,
structure, constraints,
Structure constraints, and indexes
and indexes

This table should help clarify the differences between TRUNCATE


TABLE and DELETE
SQL TRUNCATE vs DROP

Here's a comparison of the SQL TRUNCATE TABLE and DROP


TABLE commands in a tabular format:

Feature TRUNCATE TABLE DROP TABLE

Removes all rows from a


Deletes the entire table,
Operation table, leaving the structure
including its structure.
intact.

Generally faster Fast operation since it


Speed than DELETE since it removes both data and
deallocates data pages. structure.

Transactio Minimal logging; typically Fully logged; the entire table


n Log logs page deallocations only. drop is recorded.

Table Retained; only the data is Deleted; table structure and


Structure removed. data are both removed.
Feature TRUNCATE TABLE DROP TABLE

Auto- Resets the auto-increment


No impact, as the entire
increment counter to the seed value (if
table is removed.
Counter present).

Not applicable, as the table


Triggers Triggers are not fired.
no longer exists.

Foreign Cannot drop a table if other


Cannot truncate a table if it
Key tables reference it unless
is referenced by a foreign
Constraint the foreign key constraint is
key.
s removed first.

Used when you need to Used when you want to


Usage remove all data from a table completely remove the table
but keep the table itself. from the database.

Data cannot be recovered


The table and its data
unless a backup is available
Recovery cannot be recovered unless
(depends on the database
a backup is available.
system).

Permissio
Requires ALTER permission Requires DROP permission
ns
on the table. on the table.
Required

Important Points About SQL TRUNCATE TABLE

 TRUNCATE TABLE is used to empty a table by removing all rows, but it


retains the table structure.
 TRUNCATE TABLE is ideal for quickly removing all data from a table
without deleting the table structure, making it efficient for data
cleanup operations

 TRUNCATE TABLE is faster and uses fewer system and transaction logs
compared to DELETE.

 However, TRUNCATE TABLE typically cannot be rolled back if executed


within a transaction.

Conclusion

In conclusion, the TRUNCATE TABLE command is a highly efficient method for


quickly removing all rows from a table while preserving its structure. It is
particularly useful in scenarios where you need to clear a table without
deleting it, offering a performance advantage over the DELETE statement
due to minimal transaction logging.

SQL Cloning or Copying a Table


Cloning or copying a table in SQL is a common task in database
management. Whether we are creating backups, conducting testing, or
needing a duplicate table structure for various purposes, knowing how to
effectively clone or copy a table is an essential skill for database
administrators and developers.

In this article, we will explain different methods of cloning tables in


SQL, provide examples for each, and explain their real-world applications.
By the end of this article, we will be able to select the most suitable cloning
method based on our needs

What is a Copying or Cloning Table in SQL

SQL Cloning is an operation that means making a copy of a table. It's like
taking a photocopy of a document. This copy can include both the
table’s structure (column names, data types, constraints) and optionally
its data. The clone table is independent of the original and can be used
for testing, backups, or analysis without affecting the original table.
Cloning a table in SQL means making a duplicate copy of an existing
table. It's like making a backup so that we can experiment or work with
the data without affecting the original table. This saves our the time and
effort of creating a completely new table and re-entering all the same data.
Cloning can be done with or without data:

 With Data: The clone table includes the structure and rows of the
original table.

 Without Data: Only the structure of the original table is copied.

Real-Life Scenario Example

Imagine we are developing a library management system. If we want to


test new features without risking changes to the production table, we can
create a clone of the original table for safe experimentation.

Methods for Cloning Tables in SQL

There are three different methods to create a clone table in SQL:

1. Simple Cloning

2. Deep Cloning

3. Shallow Cloning

Step 1: Create the Original Table

We will use the following table named STUDENT for demonstrating cloning
techniques. After creating the table we used INSERT OPERATION to insert
the three entries in the "STUDENT" Table. Finally, we have used SELECT
OPERATION to fetch the data to see the output.

Query:
CREATE TABLE STUDENT(
student_id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
roll_no varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (student_id)
);

INSERT INTO STUDENT(student_id, name, roll_no)


VALUES (1, 'Ritwik Dalmia', 'S100');
INSERT INTO STUDENT(student_id, name, roll_no)
VALUES (2, 'Rohan Singh', 'S200');
INSERT INTO STUDENT(student_id, name, roll_no)
VALUES (3, 'Mohan Singh', 'S300');

SELECT * from STUDENT;

Output

STU
DENT TABLE

Explanation:

The above MySQL code is used to create a table called "STUDENT" which
has three columns student_id, name, and roll_no where student_id is defined
as PRIMARY KEY with AUTO_INCREMENT command and roll_no is defined
as UNIQUE KEY.
1. Simple Cloning

In this method, the clone table creates a copy of the original table’s structure
and data, but constraints like primary keys, unique keys, and auto-increment
properties are not preserved.

Syntax

CREATE TABLE clone_table SELECT * FROM original_table;

Example:

Let us see the example to understand how simple cloning syntax works

CREATE TABLE STUDENT_COPY AS SELECT * FROM STUDENT;


SELECT * FROM STUDENT_COPY;

Output

Simp
le Cloning

Let's see the property of both the tables STUDENT and


STUDENT_COPY respectively

EXEC sp_help 'employee'; - MS SQL


Property inherits while cloning the sql tables

Explanation:

As we can see that in original table "STUDENT", we have primary Key


and auto_increment command for student_id and unique key
for roll_no but in "STUDENT_COPY" clone table we do not have the primary
key, auto_increment, and unique key respectively.

Drawback Of Simple Cloning

Simple cloning in SQL lacks preservation of unique


constraints and auto-increment properties, potentially leading to data
integrity issues. Mitigation involves manually reapplying constraints and
resetting auto-increment settings. Consider alternative cloning methods for
better results.

Output
Drawback
of simple cloning

Explanation:

In the above output, you can see that in the original table "STUDENT" we
had set the student_no as a primary key but now in the simple clone
table "STUDENT_COPY" values, there are duplicate value for the last two
entries and Auto_increment command also becomes invalid here. To avoid
this, we will be using Shallow cloning technique.

2. Shallow Cloning

Shallow cloning is the method in which the clone table gets the same
structure as the original table but it does not inherits or copy the data from
the original table. In other words, we will have the empty table including
indices such as primary key, unique key, and auto_increment. It also
preserves constraints like primary keys and unique keys.

Syntax

CREATE TABLE clone_table LIKE original_table;

Example:

CREATE TABLE STUDENT_SHALLOW_CLONE LIKE STUDENT;


SELECT * FROM STUDENT_SHALLOW_CLONE;

Output
Shallow clone of student table (Original Table)

Insert Data into Shallow Clone:

INSERT INTO STUDENT_SHALLOW_CLONE(name, roll_no)


VALUES ('Ritwik Dalmia', 'S100');
INSERT INTO STUDENT_SHALLOW_CLONE(name, roll_no)
VALUES ( 'Rohan Singh', 'S200');
INSERT INTO STUDENT_SHALLOW_CLONE( name, roll_no)
VALUES ( 'Mohan Singh', 'S300');

Output

Shall
ow Clone

Explanation:

We can able to see that all the properties such as indices and
auto_increment command are inherited in this method as compare to
simple cloning method.

3. Deep Cloning
This method is widely used for creating the clone tables in SQL as it
inherits all the properties of original table including indices such
as primary key, unique, and auto_increment as well as inherits the
existing data from the original table.

Syntax

CREATE TABLE clone_table LIKE original_table;


INSERT INTO clone_table SELECT * FROM original_table;

Example:

CREATE TABLE STUDENT_DEEP_CLONE LIKE STUDENT;


INSERT INTO STUDENT_DEEP_CLONE SELECT * FROM STUDENT;
SELECT * FROM STUDENT_DEEP_CLONE;

Output

STU
DENT_DEEP_CLONE

The output of the "STUDENT_DEEP_CLONE" is exactly the same as


the "STUDENT" table. We can add new entries to the deep clone table to
confirm the preservation of constraints:

INSERT INTO STUDENT_DEEP_CLONE (name,roll_no)


VALUES ('mohini roy', 'S400');
INSERT INTO STUDENT_DEEP_CLONE (name,roll_no)
VALUES ('surbhi roy', 'S500');

SELECT * FROM STUDENT_DEEP_CLONE;

Output
New-STUDENT_DEEP_CLONE

Explanation:

In the above output, we performed the INSERT operation for two entries to
the "STUDENT_DEEP_CLONE" table to validate the functionality or
properties of the indices and the AUTO_INCREMENT function. Finally, we
clone the sql table.

Conclusion

Cloning is a useful method in SQL for creating a copy of an existing


table. There are three main methods of cloning a table: simple cloning,
shallow cloning, and deep cloning. Simple cloning only copies the basic
structure of the table, while shallow cloning copies the structure
without any data.

Deep cloning, on the other hand, copies all properties of the original
table, including indices like primary key, unique, and auto-increment, as well
as any existing data. Each cloning method has
its uses and benefits depending on the situation. Knowing the differences
between these cloning methods can help us choose the appropriate
method for our needs.
What is Temporary Table in SQL?

A temporary table in SQL is an important tool for maintaining intermediate


results during query execution. They help store temporary data without
affecting the underlying permanent tables.

In this article, we’ll explore temporary tables in SQL, their types (local vs.
global), and how to use them effectively in your database operations.

What Are Temporary Tables in SQL?

A temporary table in SQL is a special type of table that is created and


stored in the system's temporary database (such as TempDB in SQL Server).
This table is primarily used to store and generate important mediation
results when executing a query, stored procedure, or session.

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


Result:

id name

1 Lalit

Atharv
2
a

Types of Temporary Tables in SQL

There are 2 types of Temporary Tables: Local Temporary Table, and Global
Temporary Table. These are explained as following below.

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

Feature Local Temporary Table Global Temporary Table

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

Only the session that


Scope Available to all sessions
created it

Dropped when the last


Automatically dropped
Lifetime connection referencing the
when the session ends
table ends

Accessibil Only the creating session


All sessions can access it
ity can access it

Session-specific data Shared temporary data storage


Usage
storage for multiple sessions
Conclusion

Temporary tables in SQL are powerful tools for managing central data,
performing complex calculations, and improving query performance.
Whether you use local temporary tables for session-specific operations or
global temporary tables to share data across multiple sessions,
understanding how to use these tables effectively will inform your database
management processes simplified Temporary tables for storing and
manipulating data without impacting the permanent database structure
provide options , which make them ideal for tasks such as data manipulation,
backup and testing

SQL ALTER TABLE

SQL ALTER TABLE statement modify the structure of an existing table in a


database. Whether adding new columns, modifying existing ones, deleting
columns or renaming them. ALTER TABLE statement enables you to make
changes without losing data stored in the table.

Syntax:

ALTER TABLE table_name [ADD | DROP | MODIFY] column_name datatype;

Parameters:

 table_name: name of the table you want to modify.

 ADD: used to add a new column.

 DROP: used to remove an existing column.

 MODIFY: used to change datatype or definition of an existing column.


Common Use Cases for SQL ALTER TABLE

1. ADD

The ADD clause is used to add a new column to an existing table. You must
specify the name of the new column and its data type.

Syntax:

ALTER TABLE table_name


ADD column_name datatype;

Example:

ALTER TABLE Students


ADD Email varchar(255);

Here, we are adding a column named Email to Student table

2. MODIFY

The MODIFY (or ALTER COLUMN in some databases like SQL Server) clause is
used to modify the definition of an existing column, such as changing its data
type or size.

Syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Example:

ALTER TABLE Students


MODIFY COLUMN Address VARCHAR(100);

Here, we are modifying the column named Address datatype that


is VARCHAR(100).

3. DROP

The DROP clause allows you to remove a column from a table. Be cautious
when using this command as it will permanently remove the column and its
data.

Query:
ALTER TABLE table_name
DROP COLUMN column_name;

Example:

ALTER TABLE Students


DROP COLUMN Grade;

Here, we are removing a column named Grade from Student table

4. RENAME COLUMN

We can rename an existing column using RENAME COLUMN clause. This


allows you to change the name of a column while preserving its data type
and content.

Query:

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

Example:

ALTER TABLE Customer


RENAME COLUMN CustomerName TO FirstName;

This renames the column CustomerName to FirstName in the Customer


table.

5. RENAME TO

We can rename an entire table using the RENAME TO clause. This changes
the name of the table while preserving its structure and data.

Query:

ALTER TABLE table_name


RENAME TO new_table_name;

Example:

ALTER TABLE Customer


RENAME TO Clients;

This renames the table from Customer to Clients.


Example Queries

Let's explore ALTER TABLE queries using a Student table with


columns ROLL_NO and NAME and demonstrate various modifications such
as adding, modifying and dropping columns.

ROLL_N
O NAME

1 Emma

2 Travis

Jennife
3
r

Roxann
4
e

Here's how you can execute these operations:

1. Adding Columns (AGE and COURSE)

To add new columns AGE and COURSE to the Student table, use ALTER TABLE
statement with the ADD clause.

Query:

ALTER TABLE Student ADD


(AGE number (3), COURSE VARCHAR (40));

Explanation: This adds an AGE column (numeric) and a COURSE column


(VARCHAR(40)). Initially, these columns will be empty for existing rows.
Output

ROLL_N AG COURS
O NAME E E

1 Emma null null

2 Travis null null

Jennife
null null
3 r

Roxann
null null
4 e

2. Modify Column COURSE to Reduce its Size

To reduce the size of the COURSE column from VARCHAR(40) to


VARCHAR(20), use the MODIFY clause.

Query:

ALTER TABLE Student


MODIFY COURSE varchar(20);

Explanation: COURSE column will now allow a maximum of 20 characters


instead of 40.

3. Drop COURSE Column from Student Table

To remove the COURSE column from the Student table, use the DROP
COLUMN clause.

Query:
ALTER TABLE Student
DROP COLUMN COURSE;

Explanation: This permanently deletes the COURSE column from the table.

Output

ROLL_N AG
O NAME E

1 Emma null

2 Travis null

Jennife
null
3 r

Roxann
null
4 e
Chapter IV

SQL Queries

Master writing SQL queries to interact with and manipulate data stored in
your tables. This section covers common query types and operations.

 SELECT Statement

 INSERT INTO

 INSERT Multiple Rows

 UPDATE Statement

 DELETE Statement

 DELETE Duplicate Rows

SQL SELECT Query

SQL SELECT is used to retrieve data from one or more tables, either all
records or specific results based on conditions. It returns output in a tabular
format of rows and columns.

 Extracts data from tables.

 Targets specific or all columns (*).


 Supports filtering, sorting, grouping, and joins.

 Results are stored in a result set.

Syntax

SELECT column1,column2.... FROM table_name;

Parameters:

 column1, column2: columns you want to retrieve.

 table_name: name of the table you're querying.

Examples of SELECT Statement

Let us start by creating a sample table that we will use for our examples. We
will also insert some sample data to make the demonstration more practical.

CREATE TABLE Customer (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT(2),
Phone VARCHAR(10) );

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,


Age, Phone)
VALUES (1, 'Liam', 'Smith', 'USA', 23, 'xxxxxxxxxx'),
(2, 'Sophia', 'Miller', 'USA', 21, 'xxxxxxxxxx'),
(3, 'Akira', 'Tanaka', 'Japan', 24, 'xxxxxxxxxx'),
(4, 'Carlos', 'Hernandez', 'USA', 21, 'xxxxxxxxxx'),
(5, 'Isabella', 'Rossi', 'Italy', 22, 'xxxxxxxxxx');

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

xxxxxxx
1 Liam Smith USA 23
xxx
Customer CustomerNa LastNa Count Ag
ID me me ry e Phone

xxxxxxx
2 Sophia Miller USA 21
xxx

xxxxxxx
3 Akira Tanaka Japan 24
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

Example 1: Select Specific Columns

In this example, we will demonstrate how to retrieve specific columns from


the Customer table. Here we will fetch only CustomerName and LastName
for each record.

Query:

SELECT CustomerName, LastName


FROM Customer;

Output

CustomerNa LastNa
me me

Liam Smith

Sophia Miller
CustomerNa LastNa
me me

Akira Tanaka

Hernand
Carlos
ez

Isabella Rossi

Example 2: Select All Columns

In this example, we will fetch all the fields from table Customer:

Query:

SELECT * FROM Customer;

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

xxxxxxx
1 Liam Smith USA 23
xxx

xxxxxxx
2 Sophia Miller USA 21
xxx
Customer CustomerNa LastNa Count Ag
ID me me ry e Phone

xxxxxxx
3 Akira Tanaka Japan 24
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

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

Output

CustomerNa
me

Sophia

Carlos

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, we will count the number of
customers from each country.

Query:

SELECT Country, COUNT(*) AS customer_count


FROM Customer
GROUP BY Country;

Output

Count customer_co
ry unt

USA 3

Japan 1

Italy 1

Example 5: SELECT with DISTINCT Clause

In this example, we will use DISTINCT keyword to return only unique values
from a column. Here, we will fetch unique countries from the Customer table.

Query:

SELECT DISTINCT Country


FROM Customer;

Output
Count
ry

USA

Japan

Italy

Example 6: SELECT Statement with HAVING Clause

The HAVING clause is used to filter results after applying GROUP BY. In this
example, we will find countries that have 2 or more customers in the
Customer table.

Query:

SELECT Country, COUNT(*) AS customer_count


FROM Customer
GROUP BY Country
HAVING COUNT(*) >= 2;

Output

Count customer_co
ry unt

USA 3

Example 7: SELECT Statement with ORDER BY clause

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;

Output

Customer CustomerNa LastNa Count Ag


ID me me ry e Phone

xxxxxxx
3 Akira Tanaka Japan 24
xxx

xxxxxxx
1 Liam Smith USA 23
xxx

xxxxxxx
5 Isabella Rossi Italy 22
xxx

xxxxxxx
2 Sophia Miller USA 21
xxx

Hernand xxxxxxx
4 Carlos USA 21
ez xxx
SQL INSERT INTO Statement
INSERT INTO statement is used to add new rows to an existing table. It can
insert values into all columns, specific columns, or even copy data from
another table. This command is essential for populating databases with
meaningful records such as customers, employees or students.

Let’s explore different ways to use the INSERT INTO statement:

1. Inserting Data into All Columns

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, value3, ...);

Parameters:

 table_name: name of the table where data will be inserted

 value1, value2... : values that correspond to each column in order.

Example: Let’s see how the INSERT INTO statement works with practical
examples.

CREATE DATABASE StudentDB;


USE StudentDB;

CREATE TABLE Student (


ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15),
AGE INT );

INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)


VALUES (1, 'Liam', 'New York', 'xxxxxxxxxx', 18),
(2, 'Sophia', 'Berlin', 'xxxxxxxxxx', 18),
(3, 'Akira', 'Tokyo', 'xxxxxxxxxx', 20),
(4, 'Carlos', 'Tokyo', 'xxxxxxxxxx', 18);

Output

ROLL_N NAM ADDRE AG


O E SS PHONE E

New xxxxxxx
1 Liam 18
York xxx

Sophi xxxxxxx
2 Berlin 18
a xxx

xxxxxxx
3 Akira Tokyo 20
xxx

Carlo xxxxxxx
4 Tokyo 18
s xxx

If we don’t want to specify the column names (and you’re inserting data into
all columns), we can directly insert values in the order they appear in the
table structure. Here's an example:

Query:

INSERT INTO Student


VALUES (5, 'Isabella', 'Rome', 'xxxxxxxxxx', 19);

Output

ROLL_N ADDRE AG
O NAME SS PHONE E

1 Liam New xxxxxxx 18


ROLL_N ADDRE AG
O NAME SS PHONE E

York xxx

xxxxxxx
2 Sophia Berlin 18
xxx

xxxxxxx
3 Akira Tokyo 20
xxx

xxxxxxx
4 Carlos Tokyo 18
xxx

Isabell xxxxxxx
5 Rome 19
a xxx

2. Inserting Data into Specific Columns

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, value3, ...);

Parameters:

 table_name: name of the table.

 column1, column2..: name of first column, second column.

 value1, value2, value3..: the values for each specified column of


the new record.
Example: Let’s say we only want to insert the student's ID, name, and age
into the Student table, and leave the address and phone number as NULL
(the default value).

INSERT INTO Student (ROLL_NO, NAME, AGE)


VALUES (6, 'Hiroshi', 19);

Output

ROLL_N ADDRE AG
O NAME SS PHONE E

New xxxxxxx
1 Liam 18
York xxx

xxxxxxx
2 Sophia Berlin 18
xxx

xxxxxxx
3 Akira Tokyo 20
xxx

xxxxxxx
4 Carlos Tokyo 18
xxx

Isabell xxxxxxx
5 Rome 19
a xxx

Hirosh
6 NULL NULL 19
i

Note: Columns not included in INSERT statement are filled with default
values (typically NULL).

3. Inserting Multiple Rows at Once


Instead of running multiple INSERT INTO commands, you can insert multiple
rows into a table in a single query. This is more efficient and reduces the
number of database operations.

Syntax

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...), (value1, value2, ...), (value1, value2, ...);

Example: If we want to add multiple students to Student table in one go,


query would look like this:

INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)


VALUES
(7, 'Mateo Garcia', 'Madrid', 'xxxxxxxxxx', 15),
(8, 'Hana Suzuki', 'Osaka', 'xxxxxxxxxx', 18),
(9, 'Oliver Jensen', 'Copenhagen', 'xxxxxxxxxx', 17),
(10, 'Amelia Brown', 'London', 'xxxxxxxxxx', 17);

Output

ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxx
1 Liam New York 18
xxx

xxxxxxx
2 Sophia Berlin 18
xxx

3 Akira Tokyo xxxxxxx 20


ROLL_N AG
O NAME ADDRESS PHONE E

xxx

xxxxxxx
4 Carlos Tokyo 18
xxx

xxxxxxx
5 Isabella Rome 19
xxx

6 Hiroshi NULL NULL 19

Mateo xxxxxxx
7 Madrid 15
Garcia xxx

Hana xxxxxxx
8 Osaka 18
Suzuki xxx

Oliver Copenhag xxxxxxx


9 17
Jensen en xxx

Amelia xxxxxxx
10 London 17
Brown xxx

Explanation:

 Faster than multiple single inserts

 For very large data (>1000 rows), use bulk insert


4. Inserting Data from One Table into Another Table

We can also copy data from one table into another table using the INSERT
INTO SELECT statement. This is very useful when we want to move or
replicate data from one table to another without manually typing all the data.

Here, we are using below table OldStudent as another table and we will
insert its rows into Student table using different methods.

ROLL_N ADDRE AG
O NAME SS PHONE E

Arjun 99999999
101 Mumbai 21
Mehta 99

Emily 88888888
102 Sydney 22
Clark 88

77777777
103 Kenji Sato Tokyo 19
77

Method 1: Insert All Columns from Another Table

Inserts every column from source table into destination table

INSERT INTO target_table


SELECT * FROM source_table;

Example: If you want to copy all data from the OldStudent table into the
Student table, use this query:

INSERT INTO Student


SELECT * FROM OldStudent;

Output

ROLL_N AG
O NAME ADDRESS PHONE E

1 Liam New York xxxxxxxxx 18


ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
2 Sophia Berlin 18
x

xxxxxxxxx
3 Akira Tokyo 20
x

xxxxxxxxx
4 Carlos Tokyo 18
x

xxxxxxxxx
5 Isabella Rome 19
x

6 Hiroshi NULL NULL 19

Mateo xxxxxxxxx
7 Madrid 15
Garcia x

Hana xxxxxxxxx
8 Osaka 18
Suzuki x

Oliver Copenhag xxxxxxxxx


9 17
Jensen en x

Amelia xxxxxxxxx
10 London 17
Brown x
ROLL_N AG
O NAME ADDRESS PHONE E

Arjun 99999999
101 Mumbai 21
Mehta 99

88888888
102 Emily Clark Sydney 22
88

77777777
103 Kenji Sato Tokyo 19
77

Method 2: Insert Specific Columns from Another Table

Allows inserting only selected columns from the source table.

INSERT INTO target_table (col1, col2, ...)


SELECT col1, col2, ...
FROM source_table;

Example: Let’s say we want to copy only the Name and Age columns from
OldStudent into Student:

INSERT INTO Student (Name, Age)


SELECT Name, Age
FROM OldStudent;

Output
ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxx
Liam New York 18
1 xxx

xxxxxxx
Sophia Berlin 18
2 xxx

xxxxxxx
Akira Tokyo 20
3 xxx

xxxxxxx
Carlos Tokyo 18
4 xxx

xxxxxxx
Isabella Rome 19
5 xxx

6 Hiroshi NULL NULL 19

Mateo xxxxxxx
Madrid 15
7 Garcia xxx

Hana xxxxxxx
Osaka 18
8 Suzuki xxx

Oliver Copenhag xxxxxxx


17
9 Jensen en xxx

10 Amelia London xxxxxxx 17


ROLL_N AG
O NAME ADDRESS PHONE E

Brown xxx

Arjun
NULL NULL 21
NULL Mehta

NULL Emily Clark NULL NULL 22

NULL Kenji Sato NULL NULL 19

Note: Columns not included in INSERT statement (ROLL_NO, ADDRESS,


PHONE) are automatically filled with NULL in target table.

Method 3: Insert Specific Rows Based on Condition

You can also insert specific rows based on a condition by using the WHERE
clause with the SELECT statement.

INSERT INTO target_table


SELECT * FROM source_table
WHERE condition;

Example: If we want to copy only students older than 20 years from


OldStudent to Student, we would write:

INSERT INTO Student


SELECT * FROM OldStudent
WHERE Age > 20;

Output

ROLL_N AG
O NAME ADDRESS PHONE E

1 Liam New York xxxxxxxxx 18


ROLL_N AG
O NAME ADDRESS PHONE E

xxxxxxxxx
2 Sophia Berlin 18
x

xxxxxxxxx
3 Akira Tokyo 20
x

xxxxxxxxx
4 Carlos Tokyo 18
x

xxxxxxxxx
5 Isabella Rome 19
x

6 Hiroshi NULL NULL 19

Mateo xxxxxxxxx
7 Madrid 15
Garcia x

Hana xxxxxxxxx
8 Osaka 18
Suzuki x

Oliver Copenhag xxxxxxxxx


9 17
Jensen en x

Amelia xxxxxxxxx
10 London 17
Brown x
ROLL_N AG
O NAME ADDRESS PHONE E

Arjun 99999999
101 Mumbai 21
Mehta 99

88888888
102 Emily Clark Sydney 22
88

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.

In this article, We will learn different methods such as using basic INSERT
statements, utilizing INSERT INTO ... SELECT for bulk inserts, and handling
transactions for larger datasets. Additionally, we will discuss advanced
techniques like bulk inserts and optimization tips for efficiently inserting
data.

How to Insert Multiple Rows in SQL

Insertion in a table is a DML (Data manipulation language) operation in


SQL. When we want to store data we need to insert the data into the
database. We use the INSERT statement to insert the data into the
database.

Inserting multiple rows can be done in several ways. The most common
methods include using a simple INSERT statement with multiple value sets,
utilizing the INSERT INTO ... SELECT syntax, and using transactions for
batch inserts. Before we dive into these techniques, let’s first create a
sample table structure to work with.

Creating a Table: Create a table employee_details with 4 columns using


the following SQL query:

Query:
CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

EmployeeName VARCHAR(100),

Age INT,

Department VARCHAR(50)

);

This table, Employees, will serve as an example for all the insertion methods
discussed in this article. It includes four columns: EmployeeID,
EmployeeName, Age, and Department.

Basic INSERT for Multiple Rows

The simplest method to insert multiple rows is by using a single INSERT


INTO statement followed by multiple sets of values. This approach allows you
to insert multiple records in one go, improving efficiency.

Query:

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

Output:
Insert Multiple Rows

This query inserts four rows into the Employees table. It’s a simple, effective
method for adding multiple records at once, and it reduces the need for
multiple INSERT statements.

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. This method is often used for transferring data between
tables or inserting derived data into a target table.

NewEmployees table

CREATE TABLE NewEmployees (

EmployeeID INT PRIMARY KEY,

EmployeeName VARCHAR(100),

Age INT,

Department VARCHAR(50)

);
INSERT INTO NewEmployees (EmployeeID, EmployeeName, Age,
Department)

VALUES

(5, 'Alice Johnson', 29, 'HR'),

(6, 'Bob Martin', 32, 'Finance'),

(7, 'Charlie Baker', 28, 'Marketing'),

(8, 'David Lee', 40, 'Engineering'),

(9, 'Eva Davis', 22, 'Sales');

Output:

Employee EmployeeNa Ag Departm


ID me e ent

5 Alice Johnson 29 HR

6 Bob Martin 32 Finance

7 Charlie Baker 28 Marketing

Engineerin
8 David Lee 40
g

9 Eva Davis 22 Sales

In this example, the INSERT INTO ... SELECT statement copies data from the
NewEmployees table to the Employees table, but only inserts those records
where the employee’s age is greater than 30.

Query:

INSERT INTO Employees (EmployeeID, EmployeeName, Age, Department)


SELECT EmployeeID, EmployeeName, Age, Department

FROM NewEmployees

WHERE Age > 30;

Output:

Employee EmployeeNa Ag
ID me e Department

1 John Doe 30 Engineering

2 Jane Smith 28 Marketing

3 Sam Brown 35 Sales

Human
4 Lucy Green 25
Resources

6 Bob Martin 32 Finance

8 David Lee 40 Engineering

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;

Output:

Employee EmployeeNa Ag
ID me e Department

1 John Doe 30 Engineering

2 Jane Smith 28 Marketing

3 Sam Brown 35 Sales

4 Lucy Green 25 Human


Employee EmployeeNa Ag
ID me e Department

Resources

6 Bob Martin 32 Finance

8 David Lee 40 Engineering

35 Carlos Diaz 40 Engineering

36 Mia Clark 33 Sales

In this example, the BEGIN TRANSACTION starts the transaction, and the
COMMIT command commits the changes to the database. If any INSERT
operation fails, the transaction can be rolled back using ROLLBACK to avoid
partial data insertion.

Conclusion

Inserting multiple rows in SQL can be done in several ways depending on


your use case. Whether you’re using the basic INSERT INTO statement for
simple data entry or leveraging advanced techniques like transactions, bulk
inserts, and MERGE for complex scenarios, SQL provides powerful tools to
efficiently insert large volumes of data.

SQL UPDATE Statement

The UPDATE statement in SQL is used to modify existing records in a table


without deleting them. It allows updating one or multiple columns, with or
without conditions, to keep data accurate and consistent.

 Change specific column values in selected rows

 Apply targeted updates using WHERE


 Update single or multiple columns at once

 More efficient than deleting and re-inserting rows

 Maintains data integrity by modifying in place

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;

Parameters

 table_name: Name of the table you want to update.

 SET: The column(s) you want to update and their new values.

 WHERE: Filters the specific rows you want to update.

Note: The SET keyword assigns new values to columns, while the WHERE
clause selects which rows to update. Without WHERE, all rows will be
updated.

Examples of SQL UPDATE Statement

Let’s begin by creating a Customer table with some sample data. This table
contains each customer's unique ID, name, last name, phone number and
country. We will use it to demonstrate how the UPDATE statement works in
SQL.

Query:

CREATE TABLE Customer (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT,
Phone VARCHAR(15)
);

-- Insert sample data


INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,
Age, Phone)
VALUES
(1, 'Shubham', 'Thakur', 'India', 23, '9415536635'),
(2, 'Aman', 'Chopra', 'Australia', 21, '9812345678'),
(3, 'Naveen', 'Tulasi', 'Sri Lanka', 24, '9123456789'),
(4, 'Aditya', 'Arpan', 'Austria', 21, '9876543210'),
(5, 'Nishant', 'Jain', 'Spain', 22, '7012345678');

Output

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

94155366
1 Shubham Thakur India 23
35

Australi 98123456
2 Aman Chopra 21
a 78

Sri 91234567
3 Naveen Tulasi 24
Lanka 89

98765432
4 Aditya Arpan Austria 21
10

70123456
5 Nishant Jain Spain 22
78

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;

Output:
Explanation: Only the rows where Age is 22 will be updated, and the
CustomerName will be set to 'Nitin'.

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;

Output:

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

94155366
1 Satyam Thakur USA 23
35

Australi 98123456
2 Aman Chopra 21
a 78

Sri 91234567
3 Naveen Tulasi 24
Lanka 89

98765432
4 Aditya Arpan Austria 21
10

70123456
5 Nishant Jain Spain 22
78

Explanation: For the row where CustomerID is 1, both CustomerName and


Country will be updated simultaneously.
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';

Output

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

94155366
1 Shubham Thakur USA 23
35

Australi 98123456
2 Shubham Chopra 21
a 78

Sri 91234567
3 Shubham Tulasi 24
Lanka 89

98765432
4 Shubham Arpan Austria 21
10

70123456
5 Shubham Jain Spain 22
78

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 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.

SQL DELETE Statement

Last Updated : 25 Aug, 2025

The SQL DELETE statement is used to remove specific rows from a table
while keeping the table structure intact. It is different from DROP, which
deletes the entire table.

 Removes rows based on conditions.

 Retains table schema, constraints, and indexes.

 Can delete a single row or all rows.

 Useful for cleaning or managing datasets.

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.

Examples of SQL DELETE Statement

Assume we have created a table named GFG_Employee in SQL, which


contains the personal details of the Employee including their id, name, email
and department etc. as shown below.

CREATE TABLE GFG_Employees (


id INT PRIMARY KEY,
name VARCHAR (20) ,
email VARCHAR (25),
department VARCHAR(20)
);

INSERT INTO GFG_Employees (id, name, email, department) VALUES


(1, 'Jessie', '[email protected]', 'Development'),
(2, 'Praveen', '[email protected]', 'HR'),
(3, 'Bisa', '[email protected]', 'Sales'),
(4, 'Rithvik', '[email protected]', 'IT'),
(5, 'Suraj', '[email protected]', 'Quality Assurance'),
(6, 'Om', '[email protected]', 'IT'),
(7, 'Naruto', '[email protected]', 'Development');

Select * From GFG_Employees

Output

id name email department

1 Jessie [email protected] Development

Pravee praveen_dagger@yahoo
2 HR
n .com
id name email department

3 Bisa [email protected] Sales

4 Rithvik [email protected] IT

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

7 Naruto [email protected] Development

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

Output:

id name email department

1 Jessie [email protected] Development

Pravee praveen_dagger@yahoo
2 HR
n .com

3 Bisa [email protected] Sales


id name email department

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

7 Naruto [email protected] Development

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

Output

id name email department

Pravee praveen_dagger@yahoo
2 HR
n .com

3 Bisa [email protected] Sales

Quality
5 Suraj [email protected]
Assurance

6 Om [email protected] IT

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;

Output:

i nam ema departm


d e il ent

All of the records in the table will be deleted, there are no records left to
display. The table GFG_Employees will become empty.

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.

SQL Query to Delete Duplicate Rows

Duplicate rows in a database can cause inaccurate results,


waste storage space, and slow down queries. Cleaning duplicate records
from our database is an essential maintenance task for ensuring data
accuracy and performance. Duplicate rows in a SQL table can lead to data
inconsistencies and performance issues, making it crucial to identify and
remove them effectively
In this article, we will explain the process of deleting duplicate rows from
a SQL table step-by-step, using SQL Server, with examples and outputs.
We'll cover techniques using GROUP BY, CTE, and more, incorporating best
practices to help us effectively handle duplicates.

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.

Creating the Sample Table and Inserting Data

To effectively remove duplicate rows in SQL, we can follow a structured


approach. Let’s begin by creating a table called DETAILS and populating it
with some sample data, including duplicate rows.

Step 1: Create the Sample Table


We will create a table named DETAILS to demonstrate how
to identify and delete duplicate rows. This step helps in setting up the
necessary structure to store sample data and perform
operations like detecting duplicates and applying deletion techniques.

Query:

CREATE TABLE DETAILS (


SN INT IDENTITY(1,1) PRIMARY KEY,
EMPNAME VARCHAR(25) NOT NULL,
DEPT VARCHAR(20) NOT NULL,
CONTACTNO BIGINT NOT NULL,
CITY VARCHAR(15) NOT NULL
);

Step 2: Insert Data into the Table

Let’s insert some data, including duplicates, into the DETAILS table. This
step allows us to copy real-world scenarios where duplicate records might
occur, enabling us to demonstrate how to identify and remove them
effectively.

Query:
INSERT INTO DETAILS (EMPNAME, DEPT, CONTACTNO, CITY)
VALUES
('VISHAL', 'SALES', 9193458625, 'GAZIABAD'),
('VIPIN', 'MANAGER', 7352158944, 'BAREILLY'),
('ROHIT', 'IT', 7830246946, 'KANPUR'),
('RAHUL', 'MARKETING', 9635688441, 'MEERUT'),
('SANJAY', 'SALES', 9149335694, 'MORADABAD'),
('VIPIN', 'MANAGER', 7352158944, 'BAREILLY'),
('VISHAL', 'SALES', 9193458625, 'GAZIABAD'),
('AMAN', 'IT', 78359941265, 'RAMPUR');

Output

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

Output

Explanation: This query will return the duplicate records based on the
combination of EMPNAME, DEPT, CONTACTNO, and CITY.

Methods to Delete Duplicate Rows in SQL

There are several ways to delete duplicate rows in SQL. Here, we will explain
five methods to handle this task effectively.

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;

Output

S EMPNA CONTACT
N ME DEPT NO CITY

919345862
1 VISHAL SALES GAZIABAD
5

735215894
2 VIPIN MANAGER BAREILLY
4

783024694
3 ROHIT IT KANPUR
6

MARKETIN 963568844
4 RAHUL MEERUT
G 1

914933569 MORADABA
5 SANJAY SALES
4 D

783599412
8 AMAN IT RAMPUR
65
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;

Output

S EMPNA CONTACT
N ME DEPT NO CITY

919345862
1 VISHAL SALES GAZIABAD
5

735215894
2 VIPIN MANAGER BAREILLY
4

783024694
3 ROHIT IT KANPUR
6

MARKETIN 963568844
4 RAHUL MEERUT
G 1
S EMPNA CONTACT
N ME DEPT NO CITY

914933569 MORADABA
5 SANJAY SALES
4 D

783599412
8 AMAN IT RAMPUR
65

Method 3: Using Common Table Expressions (CTEs)

Using a Common Table Expression (CTE), we can delete duplicates in a


more structured way. CTEs provide a cleaner approach by allowing us to
define a temporary result set that can be referenced within
the DELETE statement. This method can be
more readable and maintainable, especially when dealing with complex
queries.

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;

Output

S EMPNA CONTACT
N ME DEPT NO CITY

919345862
1 VISHAL SALES GAZIABAD
5
S EMPNA CONTACT
N ME DEPT NO CITY

735215894
2 VIPIN MANAGER BAREILLY
4

783024694
3 ROHIT IT KANPUR
6

MARKETIN 963568844
4 RAHUL MEERUT
G 1

914933569 MORADABA
5 SANJAY SALES
4 D

783599412
8 AMAN IT RAMPUR
65

Method 4: Using Temporary Tables

You can create a temporary table to hold unique records and then replace
the original table with the new, clean data.

Steps:

1. Insert unique rows into a temporary table.

2. Truncate the original table.

3. Insert the unique rows back.


Query:

SELECT DISTINCT EMPNAME, DEPT, CONTACTNO, CITY


INTO #TempTable
FROM DETAILS;

TRUNCATE TABLE DETAILS;

INSERT INTO DETAILS (EMPNAME, DEPT, CONTACTNO, CITY)


SELECT EMPNAME, DEPT, CONTACTNO, CITY
FROM #TempTable;

DROP TABLE #TempTable;

Output

S EMPNA CONTACT
N ME DEPT NO CITY

919345862
1 VISHAL SALES GAZIABAD
5

735215894
2 VIPIN MANAGER BAREILLY
4

783024694
3 ROHIT IT KANPUR
6

MARKETIN 963568844
4 RAHUL MEERUT
G 1

914933569 MORADABA
5 SANJAY SALES
4 D

8 AMAN IT 783599412 RAMPUR


S EMPNA CONTACT
N ME DEPT NO CITY

65

Method 5: Using DISTINCT with INSERT INTO

You can use DISTINCT to select only unique rows and then insert them back
into the original table, effectively deleting duplicates.

Query:

DELETE FROM DETAILS;

INSERT INTO DETAILS (EMPNAME, DEPT, CONTACTNO, CITY)


SELECT DISTINCT EMPNAME, DEPT, CONTACTNO, CITY
FROM DETAILS;

Output

S EMPNA CONTACT
N ME DEPT NO CITY

919345862
1 VISHAL SALES GAZIABAD
5

735215894
2 VIPIN MANAGER BAREILLY
4

783024694
3 ROHIT IT KANPUR
6

4 RAHUL MARKETIN 963568844 MEERUT


S EMPNA CONTACT
N ME DEPT NO CITY

G 1

914933569 MORADABA
5 SANJAY SALES
4 D

783599412
8 AMAN IT RAMPUR
65

Best Practices to Prevent Duplicates

While identifying and removing duplicates is essential, preventing them is


even better. Here are some best practices to ensure that duplicates don’t
enter your database in the first place:

1. Use Primary Keys or Unique Constraints: These ensure that each


record is unique, preventing accidental duplication.

2. Data Validation: Implement validation rules in your application to


prevent duplicate entries.

3. Indexing: Create unique indexes on columns that must remain


unique, like contact numbers or email addresses.

4. Regular Data Cleaning: Periodically run data-cleaning queries to


identify and remove any newly inserted duplicates.

Conclusion

Duplicate rows in SQL databases can negatively


impact performance and data accuracy. Using methods like GROUP
BY, ROW_NUMBER(), and CTE, we can efficiently delete duplicate rows in
SQL while retaining unique records. Always test your queries on a backup or
development environment to ensure accuracy before applying them to
production databases. By Using these methods, we can confidently remove
duplicate rows in SQL, keeping our database clean and reliable.
Chapter V
SQL Clauses
Unlock powerful ways to filter, organize, and group your query results.
Clauses help you refine your data extraction.

 WHERE Clause

 WITH Clause

 HAVING Clause

 ORDER By Clause

 Group By Clause

 LIMIT Clause

 Distinct Clause

 FETCH
 Aliases

SQL - WHERE Clause

In SQL, the WHERE clause is used to filter rows based on specific conditions.
Whether you are retrieving, updating, or deleting data, WHERE ensures that
only relevant records are affected. Without it, your query applies to every
row in the table! The WHERE clause helps you:

 Filter rows that meet certain conditions

 Target specific data using logical, comparison and pattern-based


operators

 Control SELECT, UPDATE, DELETE or even INSERT statements

Syntax:

SELECT column1, column2


FROM table_name
WHERE column_name operator value;

Parameters:

 column1, column2: Columns you want to retrieve

 table_name: Table you are querying from

 operator: Comparison logic (e.g., =, <, >, LIKE)

 value: The value or pattern to filter against

Importance of WHERE Clause

The WHERE clause is critical for several reasons:

 Data Accuracy: Filters data to return only relevant rows

 Performance: Reduces the amount of scanned data

 Flexibility: Works with many operators and conditions

Examples of WHERE Clause in SQL

We will create a basic employee table structure in SQL for performing all the
where clause operation.
Query:

CREATE TABLE Emp1 (


EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age INT,
Mob VARCHAR(15)
);

INSERT INTO Emp1 VALUES


(1, 'Shubham', 'India', 23, '738479734'),
(2, 'Aman', 'Australia', 21, '436789555'),
(3, 'Naveen', 'Sri Lanka', 24, '34873847'),
(4, 'Aditya', 'Austria', 21, '328440934'),
(5, 'Nishant', 'Spain', 22, '73248679');

SELECT * FROM Emp1;

Output:

EmpI Count Ag
D Name ry e mob

Shubha 7384797
1 India 23
m 34

Australi 4367895
2 Aman 21
a 55

Sri 3487384
3 Naveen 24
lanka 7

3284409
4 Aditya Austria 21
34
EmpI Count Ag
D Name ry e mob

7324867
5 Nishant Spain 22
9

Example 1: Where Clause with Logical Operators

To fetch records of Employee with age equal to 24.

Query:

SELECT * FROM Emp1 WHERE Age=24;

Output:

EmpI Countr Ag
D Name y e Mob

Navee Sri 348738


3 24
n Lanka 47

Example 2: WHERE with Comparison Operators

To fetch the EmpID, Name and Country of Employees with Age greater than
21.

Query:

SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;

Output:

EmpI Countr
D Name y

1 Shubha India
EmpI Countr
D Name y

Sri
3 Naveen
Lanka

5 Nishant Spain

Example 3: Where Clause with BETWEEN Operator

The BETWEEN operator is used to filter records within a specified range, and
it includes both the start and end values. In this example, we want to find
employees whose age is between 22 and 24, including both 22 and 24.

Query:

SELECT * FROM Emp1


WHERE Age BETWEEN 22 AND 24;

Output:

EmpI Countr Ag
D Name y e Mob

Shubha 7384797
1 India 23
m 34

Sri 3487384
3 Naveen 24
Lanka 7

7324867
5 Nishant Spain 22
9
Example 4: Where Clause with LIKE Operator

It is used to fetch filtered data by searching for a particular pattern in the


where clause. In this example we want to find records of Employees where
Name starts with the letter. The '%'(wildcard) signifies the later characters
here which can be of any length and value.

Query:

SELECT * FROM Emp1 WHERE Name LIKE 'S%';

Output:

EmpI Count Ag
D Name ry e Mob

Shubha 7384797
1 India 23
m 34

To fetch records of Employees where Name contains the pattern 'M'.

Query:

SELECT * FROM Emp1 WHERE Name LIKE '%M%';

Output:

EmpI Count Ag
D Name ry e Mob

Shubha 7384797
1 India 23
m 34

Australi 4367895
2 Aman 21
a 55

Example 5: 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. Here we want to find the Names of Employees where Age is 21
or 23.

Query:

SELECT Name FROM Emp1 WHERE Age IN (21,23);

Output:

Name

Aman

Aditya

Shubha
m

List of Operators that Can be Used with WHERE Clause

Operator Description

> Greater Than

>= Greater than or Equal to

< Less Than

<= Less than or Equal to

= Equal to
Operator Description

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

SQL queries can sometimes be complex, especially when you need to deal
with multiple nested subqueries, aggregations, and joins. This is where
the SQL WITH clause also known as Common Table Expressions
(CTEs) comes in to make life easier. The WITH Clause is a powerful tool that
simplifies complex SQL queries, improves readability, and enhances
performance by defining temporary result sets that can be reused multiple
times.

Whether we're working on aggregating data, analyzing large datasets, or


building complex reports, understanding how to use the WITH clause in
SQL can significantly improve your querying experience. Let’s dive into the
basics and see how this powerful tool can simplify your SQL queries.

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.

Employee Table

Employee Sala
ID Name ry

5000
100011 Smith
0

9400
100022 Bill
0

7055
100027 Sam
0

Walde 8000
100845
n 0
Employee Sala
ID Name ry

6000
115585 Erik
0

6900
1100070 Kate
0

Query:

WITH temporaryTable (averageValue) AS (


SELECT AVG(Salary)
FROM Employee
)
SELECT EmployeeID,Name, Salary
FROM Employee, temporaryTable
WHERE Employee.Salary > temporaryTable.averageValue;

Output

Employee Sala
ID Name ry

9400
100022 Bill
0

Walde 8000
100845
n 0

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.

Pilot Table

Employee Nam Sala


ID Airline e ry

Airbus 6000
70007 Kim
380 0

2000
70002 Boeing Laura
0

Airbus 8005
10027 Will
380 0

Airbus Warre 8078


10778
380 n 0

2500
115585 Boeing Smith
0

114070 Airbus Katy 7800


Employee Nam Sala
ID Airline e ry

380 0

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;

Output

Airline

Airbus
380

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.

Conclusion

The SQL WITH clause (Common Table Expressions) is an essential tool for
simplifying complex queries in SQL. By breaking down queries into smaller,
more manageable parts, the WITH clause enhances
the readability, maintainability, and performance of SQL queries.
Whether we are calculating aggregates, filtering data, or
performing complex joins, the WITH clause can streamline our query logic
and improve execution efficiency.
SQL HAVING Clause

HAVING clause filters results after applying aggregate functions. Unlike


WHERE, which filters individual rows, HAVING works with aggregated results.

Its main features include:

 Filters results based on aggregate functions.

 Supports Boolean conditions (AND, OR).

 Applied after aggregate functions in the query.

 Useful for summary-level or aggregated filtering.

Syntax:

SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
HAVING condition;

Examples of HAVING Clause

First, we create the Employee table and insert sample data to demonstrate
the HAVING clause.

Query:

CREATE TABLE Employee (


EmployeeId int,
Name varchar(50),
Gender varchar(10),
Salary int,
Department varchar(20),
Experience int );

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department,


Experience)
VALUES (1, 'Emily Johnson', 'Female', 45000, 'IT', 2),
(2, 'Michael Smith', 'Male', 65000, 'Sales', 5),
(3, 'Olivia Brown', 'Female', 55000, 'Marketing', 4),
(4, 'James Davis', 'Male', 75000, 'Finance', 7),
(5, 'Sophia Wilson', 'Female', 50000, 'IT', 3);
SELECT * FROM Employee;

Output

Employe Gend Sala Departm Experien


eId Name er ry ent ce

Emily Femal 4500


1 IT 2
Johnson e 0

Michael 6500
2 Male Sales 5
Smith 0

Olivia Femal 5500


3 Marketing 4
Brown e 0

7500
4 James Davis Male Finance 7
0

Sophia Femal 5000


5 IT 3
Wilson e 0

Example 1: Filter Total Salary

In this Example we calculate the total salary of all employees and display it
only if it meets the specified condition.

Query:

SELECT SUM(Salary) AS Total_Salary


FROM Employee
HAVING SUM(Salary) >= 250000;

Output
Total_Sal
ary

290000

Example 2: Filter Average Salary

In this example, we calculate the average salary of all employees and display
it only if the average exceeds 55,000.

Query:

SELECT AVG(Salary) AS Average_Salary


FROM Employee
HAVING AVG(Salary) > 55000;

Output

Average_Sal
ary

58000

Example 3: Filter Maximum Salary

In this example, we find the highest salary among employees and display it
only if it exceeds 70,000.

Query:

SELECT MAX(Salary) AS Max_Salary


FROM Employee
HAVING MAX(Salary) > 70000;

Output
Max_Sal
ary

75000

Example 4: Filter Minimum Experience

In this example, we find the least experienced employee and display it only if
their experience is less than 3 years.

Query:

SELECT MIN(Experience) AS Min_Experience


FROM Employee
HAVING MIN(Experience) < 3;

Output

Min_Experie
nce

Example 5: Multiple Conditions

In this example, we calculate both the total and average salary of employees
and display the results only if the total salary is at least 250,000 and the
average salary exceeds 55,000.

Query:

SELECT SUM(Salary) AS Total_Salary, AVG(Salary) AS Average_Salary


FROM Employee
HAVING SUM(Salary) >= 250000 AND AVG(Salary) > 55000;

Output
Total_Sal Average_Sal
ary ary

290000 58000

SQL ORDER BY

The ORDER BY clause in SQL is used to sort query results based on one or
more columns in either ascending (ASC) or descending (DESC) order.
Whether you are presenting data to users or analyzing large datasets,
sorting the results in a structured way is essential.

 By default, it sorts in ascending order (lowest to highest).

 To sort in descending order, use the DESC keyword.

Syntax:

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.

SQL ORDER BY Clause Examples

We have created a Student table that stores student data including their
roll_no, name, age, addess, and phone. Let's look at some examples of the
SQL ORDER BY clause to understand it's working in SQL. We will use the
following table in examples.
roll_n ag
o e name address phone

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

98765432
2 18 Mohit Thakur 321 Main St, Mumbai
01

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

Now consider the above database table and find the results of different
queries.

Example 1 : Sort by a Single Column

In this example, we will fetch all data from the table Student and sort the
result in descending order according to the column ROLL_NO.

Query:

SELECT * FROM students ORDER BY ROLL_NO DESC;


Output:

roll_n ag
o e name address phone

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
2 18 Mohit Thakur 321 Main St, Mumbai
01

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

In the above example, if we want to sort in ascending order we have to use


ASC in place of DESC.

Example 2 : Sort by Multiple Columns

In this example, we will fetch all data from the table Student and then sort
the result in descending order first according to the column age and then in
ascending order according to the column name.
To sort according to multiple columns, separate the names of columns by the
(,) operator.

Query:

SELECT * FROM students ORDER BY age DESC , name ASC;

Output:

roll_n ag
o e name address phone

98765432
7 22 Nishant Jain 369 3rd St, Bengaluru
14

98765432
6 21 Aditya Arpan 246 5th Ave, Kolkata
13

789 Broadway, 98765432


5 20 Naveen Tulasi
Ahmedabad 12

98765432
3 19 Abhishek 567 New Way, Mumbai
19

98765432
4 19 Aman Chopra 456 Park Ave, Delhi
11

Shubham 98765432
1 18 123 Main St, Mumbai
Thakur 10

98765432
2 18 Mohit Thakur 321 Main St, Mumbai
01

The result is first sorted by Age in descending order. For rows with the same
Age, it’s further sorted by Name in ascending order.
Sorting By Column Number

Instead of using column names, you can sort results using the position of a
column in the SELECT list. The number must be greater than 0 and not
exceed the number of selected columns.

 Using column numbers in ORDER BY reduces query readability.

 Referring to columns by name is clearer and easier to understand.

 Changing column order in SELECT doesn’t affect ORDER BY when using


names.

 Prefer column names over numbers for maintainable SQL code.

Syntax:

ORDER BY Column_Number asc/desc;

Example of Sorting By Column Number

Here we take an example to sort a database table according to column 1 i.e


Roll Number. For this a query will be:

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

Output:

Roll_n
o Name Address

1 HARSH DELHI
Roll_n
o Name Address

2 PRATIK BIHAR

3 RIYANKA SILIGURI

RAMNAGA
4 DEEP
R

SAPTAR
5 KOLKATA
HI

DHANRA BARABAJA
6
J R

GHAZIABA
7 ROHIT
D

8 NIRAJ ALIPUR

Explanation: ORDER BY 1 means sorting values according to first column in


the SELECT statement.

SQL GROUP BY

GROUP BY statement groups rows that have the same values in one or more
columns. It is commonly used to create summaries, such as total sales by
region or number of users by age group.

Its main features include:

 Used with the SELECT statement.


 Groups rows after filtering with WHERE.

 Can be combined with aggregate functions like SUM(), COUNT(), AVG(),


etc.

 Filter grouped results using the HAVING clause.

 Comes after WHERE but before HAVING and ORDER BY.

Query execution order: FROM -> WHERE -> GROUP BY -> HAVING ->
SELECT -> ORDER BY.

Syntax:

SELECT column1, aggregate_function(column2)


FROM table_name
WHERE condition
GROUP BY column1, column2;

Parameters:

 aggregate_function: function used for aggregation, e.g., SUM(),


AVG(), COUNT().

 table_name: name of the table from which data is selected.

 condition: Optional condition to filter rows before grouping (used with


WHERE).

 column1, column2: Columns on which the grouping is applied.

Examples of GROUP BY

Let's assume that we have a Student table. We will insert some sample data
into this table and then perform operations using GROUP BY to understand
how it groups rows based on a column and aggregates data.

CREATE TABLE student (


name VARCHAR(50),
year INT,
subject VARCHAR(50) );

INSERT INTO student (name, year, subject) VALUES


('Avery', 1, 'Mathematics'),
('Elijah', 2, 'English'),
('Harper', 3, 'Science'),
('James', 1, 'Mathematics'),
('Charlotte', 2, 'English'),
('Benjamin', 3, 'Science');

Output

ye
name ar subject

Mathemati
Avery 1
cs

Elijah 2 English

Harper 3 Science

Mathemati
James 1
cs

Charlott
2 English
e

Benjami
3 Science
n

Example 1: Group By Single Column

When we group by a single column, rows with the same value in that column
are combined. For example, grouping by subject shows how many students
are enrolled in each subject.

Query:

SELECT subject, COUNT(*) AS Student_Count


FROM Student
GROUP BY subject;
Output

Student_Co
subject unt

English 2

Mathemati
2
cs

Science 2

Explanation: Each subject appears twice in the table, so the count for
English, Mathematics and Science is 2.

Example 2: Group By Multiple Columns

Using GROUP BY with multiple columns groups rows that share the same
values in those columns. For example, grouping by subject and year will
combine rows with the same subject–year pair and we can count how many
students fall into each group.

Query:

SELECT subject, year, COUNT(*)


FROM Student
GROUP BY subject, year;

Output

ye count(
subject ar *)

English 2 2

Mathemati 1 2
ye count(
subject ar *)

cs

Science 3 2

Explantion: Students with the same subject and year are grouped together.
Since each subject–year pair occurs twice, the count is 2 for every group.

HAVING Clause in GROUP BY Clause

HAVING clause is used to filter results after grouping, especially when


working with aggregate functions like SUM(), COUNT() or AVG(). Unlike
WHERE, it applies conditions on grouped data.

In this section, we will use Employee table(emp) first insert some sample
data, then perform GROUP BY queries combined with HAVING.

CREATE TABLE emp (


emp_no INT PRIMARY KEY,
name VARCHAR(50),
sal DECIMAL(10,2),
age INT );

INSERT INTO emp (emp_no, name, sal, age) VALUES


(1, 'Liam', 50000.00, 25),
(2, 'Emma', 60000.50, 30),
(3, 'Noah', 75000.75, 35),
(4, 'Olivia', 45000.25, 28),
(5, 'Ethan', 80000.00, 32),
(6, 'Sophia', 65000.00, 27),
(7, 'Mason', 55000.50, 29),
(8, 'Isabella', 72000.75, 31),
(9, 'Logan', 48000.25, 26),
(10, 'Mia', 83000.00, 33);

SELECT * FROM emp;


Output

emp_ ag
no name sal e

50000.
Liam 25
1 00

60000.
Emma 30
2 50

75000.
Noah 35
3 75

45000.
Olivia 28
4 25

80000.
Ethan 32
5 00

65000.
Sophia 27
6 00

55000.
Mason 29
7 50

Isabell 72000.
31
8 a 75

48000.
Logan 26
9 25
emp_ ag
no name sal e

83000.
Mia 33
10 00

Example 1: Filter by Total Salary

In this query, we group employees by name and display only those whose
total salary is greater than 50,000.

SELECT NAME, SUM(sal) FROM Emp


GROUP BY name
HAVING SUM(sal)>50000;

Output

SUM(s
name al)

60000.
Emma
50

75000.
Noah
75

80000.
Ethan
00

Sophi 65000.
a 00

Mason 55000.
SUM(s
name al)

50

Isabell 72000.
a 75

83000.
Mia
00

Explanation: Only employees whose total salary exceeds 50,000 appear in


the result.

Example 2: Filter by Average Salary

In this query, we group employees by age and display only those age groups
where average salary is above 60,000.

SELECT age, AVG(sal) AS Average_Salary


FROM emp
GROUP BY age
HAVING AVG(sal) > 60000;

Output

ag Average_Sal
e ary

2
65000.00
7

3
60000.50
0
ag Average_Sal
e ary

3
72000.75
1

3
80000.00
2

3
83000.00
3

3
75000.75
5

Explanation: This query groups employees by age and calculates average


salary for each age. Only those age groups where average salary is greater
than 60,000 are displayed.

SQL LIMIT Clause

The LIMIT clause in SQL is used to control the number of rows returned in a
query result. It is particularly useful when working with large datasets,
allowing us to retrieve only the required number of rows for analysis or
display.

Whether we're looking to paginate results, find top records, or just display
a sample of data, the LIMIT clause is an essential tool for controlling query
output. In this article, we will explain what the LIMIT Clause is, how to use it,
and cover practical examples that show its power in everyday SQL Queries.

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

Let's look at some examples of the LIMIT clause in SQL to understand it's
working. Imagine we have a Student table with a list of students, and we
just want to retrieve the first 3 students from the table. Here's how you can
do that using LIMIT:

Query:

CREATE TABLE student (


id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
INSERT INTO student (id, name, age)
VALUES (1, 'Shubham Thakur', 18),
(2, 'Aman Chopra', 19),
(3, 'Bhavika uppala', 20),
(4,'Anshi Shrivastava',22);

Output:

Student Table

Query:

SELECT * FROM student


LIMIT 3;

Output:

LIMIT Clause Example

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). The LIMIT operator can be used in situations like these, where we
need to find the top 3 students in a class and do not want to use any
conditional statements.

Query:

SELECT * FROM Student


ORDER BY Grade DESC
LIMIT 3;

Output:

LIMIT with ORDER BY Clause

Explanation: This query first orders the students by their grades in


descending order, then limits the results to just the top 3 students. It's an
excellent way to get the "best" records from a dataset without needing
complex filtering or conditions.

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;

Output:

SQL LIMIT OFFSET Example Output

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;

Output:
SQL LIMIT to Get the nth Highest Value Example Output

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.

Example: Fetching a Limited Set of Students Based on ID

For example, let's say we want to find the youngest student with an ID less
than 4.

Query:

SELECT age
FROM Student
WHERE id<4
ORDER BY age
LIMIT 2, 1;

Output:

LIMIT with WHERE Clause Example Output

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.

Conclusion

The LIMIT clause is a powerful tool for optimizing query performance


by restricting the number of rows retrieved. It is widely used in
pagination, data sampling, and retrieving top-N records.
Combining LIMIT with ORDER BY, OFFSET, and WHERE allows for
more flexible and efficient data retrieval. Additionally, using LIMIT helps
reduce the load on databases by fetching only the necessary data, improving
query execution speed.

SQL Distinct Clause

The DISTINCT keyword in SQL is used to retrieve only unique values,


eliminating duplicates from query results. It ensures data accuracy and is
often used with the SELECT statement for clean, precise reporting.
 Removes duplicate rows

 Ensures accurate, clean results

 Works on single or multiple columns

Syntax:

SELECT DISTINCT column1, column2


FROM table_name

Parameters:

 column1, column2: Names of the fields of the table.

 Table_name: Table from where we want to fetch the records.

Note: If used on multiple columns, DISTINCT returns unique combinations of


values across those columns.

Examples of DISTINCT in SQL

Let’s create a sample table and populate it with some duplicate entries. We
will see some examples of using the DISTINCT keyword with a sample
students table.

Query:

CREATE TABLE students (

ROLL_NO INT,

NAME VARCHAR(50),

ADDRESS VARCHAR(100),

PHONE VARCHAR(20),

AGE INT

);

INSERT INTO students (ROLL_NO, NAME, ADDRESS, PHONE, AGE)

VALUES
(1, 'Shubham Kumar', '123 Main Street, Bangalore', '9876543210', 23),

(2, 'Shreya Gupta', '456 Park Road, Mumbai', '9876543211', 23),

(3, 'Naveen Singh', '789 Market Lane, Delhi', '9876543212', 26),

(4, 'Aman Chopra', '246 Forest Avenue, Kolkata', '9876543213', 22),

(5, 'Aditya Patel', '7898 Ocean Drive, Chennai', '9876543214', 27),

(6, 'Avdeep Desai', '34 River View, Hyderabad', '9876543215', 24),

(7, 'Shubham Kumar', '123 Main Street, Bangalore', '9876543210', 23), --


Duplicate

(8, 'Shreya Gupta', '456 Park Road, Mumbai', '9876543211', 23), --


Duplicate

(9, 'Naveen Singh', '789 Market Lane, Delhi', '9876543212', 26), --


Duplicate

(10, 'Aditya Patel', '7898 Ocean Drive, Chennai', '9876543214', 27), --


Duplicate

(11, 'Aman Chopra', '246 Forest Avenue, Kolkata', '9876543213', 22), --


Duplicate

(12, 'Avdeep Desai', '34 River View, Hyderabad', '9876543215', 24); --


Duplicate

Output:

ROLL_N AG
O NAME ADDRESS PHONE E

Shubham 123 Main Street, 98765432


1 23
Kumar Bangalore 10

2 Shreya Gupta 456 Park Road, 98765432 23


ROLL_N AG
O NAME ADDRESS PHONE E

Mumbai 11

98765432
3 Naveen Singh 789 Market Lane, Delhi 26
12

246 Forest Avenue, 98765432


4 Aman Chopra 22
Kolkata 13

7898 Ocean Drive, 98765432


5 Aditya Patel 27
Chennai 14

34 River View, 98765432


6 Avdeep Desai 24
Hyderabad 15

Shubham 123 Main Street, 98765432


7 23
Kumar Bangalore 10

456 Park Road, 98765432


8 Shreya Gupta 23
Mumbai 11

98765432
9 Naveen Singh 789 Market Lane, Delhi 26
12

7898 Ocean Drive, 98765432


10 Aditya Patel 27
Chennai 14

11 Aman Chopra 246 Forest Avenue, 98765432 22


ROLL_N AG
O NAME ADDRESS PHONE E

Kolkata 13

34 River View, 98765432


12 Avdeep Desai 24
Hyderabad 15

Example 1: Fetch Unique Names from the NAME Field.

The query returns only unique names, eliminating the duplicate entries from
the table.

Query:

SELECT DISTINCT NAME FROM students;

Output:

output

Example 2: Fetching Unique Combinations of Multiple Columns

This query retrieves distinct combinations of NAME and AGE — if two rows
have the same name and age, only one of them will appear in the result set.

Query:

SELECT DISTINCT NAME, AGE FROM students;

Output:
AG
NAME E

Shubham
23
Kumar

Shreya Gupta 23

Naveen Singh 26

Aman Chopra 22

Aditya Patel 27

Avdeep Desai 24

Example 3: Using DISTINCT with the ORDER BY Clause

We can combine the DISTINCT keyword with the ORDER BY clause to filter
unique values while sorting the result set. This query retrieves the unique
ages from the students table and sorts them in ascending order

Query:

SELECT DISTINCT AGE FROM students ORDER BY AGE;

Output:

AG
E

2
2
AG
E

2
3

2
4

2
6

2
7

Example 4: Using DISTINCT with Aggregate Functions (e.g.,


COUNT())

Here, we will check the COUNT() function with a DISTINCT clause, which will
give the total number of students by using the COUNT() function.

Query:

SELECT COUNT(DISTINCT ROLL_NO) FROM Students ;

Output:

COUNT(DISTINCT
AGE)

Example 5: DISTINCT with NULL Values


In SQL, the DISTINCT keyword treats NULL as a unique value. NULL is treated
as a distinct value, so it will appear only once if there are multiple NULLs.

Query:

INSERT INTO students (ROLL_NO, NAME, ADDRESS, PHONE, AGE)

VALUES (13, 'John Doe', '123 Unknown Street', '9876543216', NULL);

SELECT DISTINCT AGE FROM students;

Output:

AGE

23

26

22

27

24

NUL
L

SQL TOP, LIMIT, FETCH FIRST Clause

SQL TOP, LIMIT, and FETCH FIRST clauses are used to retrieve a specific
number of records from a table. These clauses are especially useful in large
datasets with thousands of records.
Each of these SQL clauses performs a similar operation of limiting the
results returned by a query, but different database management
systems support them. In this article, we’ll explore the differences between
these statements, provide syntax examples, and describe supporting
databases.

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. This
article will provide examples and guidance on how to use the SQL TOP, LIMIT,
and FETCH FIRST clauses in different SQL environments.

SQL SELECT TOP Clause

The SELECT TOP clause in SQL only returns the specified number of rows
from the table. It is valuable on enormous tables with a large number of
records. Returning countless records can affect execution.

Note: Not all database systems support the SELECT TOP clause.

The SQL TOP keyword is utilized with these database systems:

 SQL Server

 MS Access

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.

SQL SELECT TOP Clause Example

Let’s understand this using an example of SQL SELECT TOP statement.

We will use the following table for this example:

Demo SQL Table

Write the following SQL queries to create this table

CREATE TABLE Employee (

EmpId INTEGER PRIMARY KEY,

EmpName VARCHAR(225) NOT NULL,

Email VARCHAR(225) NOT NULL,

Address VARCHAR(225) NOT NULL,

Age INT NOT NULL,

Salary MONEY NOT NULL

);

INSERT INTO Employee (EmpId, EmpName, Email, Address, Age, Salary)

VALUES (1, 'Shubham', '[email protected]', 'India', 23, 50000.00),


(2, 'Aman', '[email protected]', 'Australia', 21, 45000.00),

(3, 'Naveen', '[email protected]', 'Sri Lanka', 24, 55000.00),

(4, 'Aditya', '[email protected]', 'Austria', 21, 42000.00),

(5, 'Nishant Saluja', '[email protected]', 'Spain', 22, 48000.00);

Example 1: Using SELECT TOP Clause in SQL

In this example, we will fetch the top 4 rows from the table.

Query:

SELECT TOP 4*

FROM Employee;

Output:

SELECT TOP Clause Output

Example 2: SQL SELECT TOP with ORDER BY Clause

In this example, we will use the SQL SELECT TOP clause with ORDER BY
clause to sort the data in the results set.

Query

SELECT TOP 4*

FROM Employee

ORDER BY Salary DESC;

Output:
SQL SELECT TOP with ORDER BY Clause Example Output

Example 3: SQL SELECT TOP Clause with WHERE Clause Example

In this example, we will use the SELECT TOP clause with WHERE clause to
filter data on specific conditions

Query:

SELECT TOP 2*

FROM Employee

WHERE Salary>2000

ORDER BY Salary;

Output:

The above query will select all the employees according to the given
condition (i.e. all Employees except the employee whose salary is less than
2000 will be selected) then the result will be sorted by Salary in ascending
order (The ORDER BY keyword sorts the records in ascending order by
default). Finally, the first 2 rows would be returned by the above query.

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;
Output:

SQL SELECT TOP PERCENT Clause Example Output

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;

Output:

SQL TOP PERCENT with WHERE Clause Example Output

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

SQL LIMIT Clause Example

Since the LIMIT Clause is not supported in SQL Server we need to create a
table in MySQL/PostgreSQL/SQLite. We will use the LIMIT clause in MySQL
CREATE TABLE Employee (

EmpId INTEGER PRIMARY KEY,

EmpName VARCHAR(225) NOT NULL,

Email VARCHAR(225) NOT NULL,

Address VARCHAR(225) NOT NULL,

Age INT NOT NULL,

Salary MONEY NOT NULL

);

INSERT INTO Employee (EmpId, EmpName, Email, Address, Age, Salary)

VALUES (1, 'Shubham', '[email protected]', 'India', 23, 50000.00),

(2, 'Aman', '[email protected]', 'Australia', 21, 45000.00),

(3, 'Naveen', '[email protected]', 'Sri Lanka', 24, 55000.00),

(4, 'Aditya', '[email protected]', 'Austria', 21, 42000.00),

(5, 'Nishant Saluja', '[email protected]', 'Spain', 22, 48000.00);

SELECT * FROM Employee ;

Output:

Demo Table Created

Example 1: SELECT LIMIT Clause in SQL

In this example, we will use the SELECT LIMIT clause to display only 2 results.

Query:

SELECT * FROM Employee


WHERE Salary = 45000

LIMIT 2;

Output:

LIMIT Clause in SQL Example Ouptut

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 4 records from the Employee
table with a given condition.

Query:

SELECT * FROM Employee

WHERE Salary = 45000

LIMIT 2;

Output:

SQL LIMIT with WHERE Clause Example Output

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;

Output:
SQL LIMIT With OFFSET Clause Example Output

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

We will use the same "Employee" table as used in previous examples.

FETCH FIRST clause in SQL Example

In this example, we will fetch the first 3 rows from the table.

Query:

SELECT * FROM Employee FETCH FIRST 3 ROWS ONLY;

Output:
FETCH FIRST Clause in SQL Example Output

Here, the above query will fetch the first 3 rows only from the table. We can
also include some situations using the FETCH FIRST PERCENT and WHERE
Clause in the above query.

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;

Output:

SQL FETCH FIRST PERCENT Example Output

Here, the above query fetches the first 50% of the total number of rows (i.e.,
2 rows) from the table.

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;


Output:

SQL FETCH FIRST with WHERE CLAUSE Example Output

Here, the above query fetches the first 1 row from the table, with the
condition that the salary is 45000 (i.e., it returns 1 row only).

Conclusion

SQL TOP, LIMIT and FETCH FIRST clause are used for a same purpose of
limiting the data returned in results set. All three of these queries are not
supported by all SQL DBMS. Each of them is supported by only some of the
DBMS and depending on the DBMS you use, the query can differ.

We have explained all TOP, LIMIT and FETCH FIRST clause in SQL with
examples, and also mentioned their supported DBMS to avoid confusion.
Users should check if the clause is supported by their DBMS before using
them.

SQL | Aliases

In SQL, aliases are temporary names given to columns or tables to make


queries easier to read and write. They don’t change the actual names in the
database and exist only for the duration of that query.

 Make long or complex names readable

 Simplify joins and subqueries

 Improve clarity in result sets

 Avoid naming conflicts in multi-table queries

There are two types of aliases in SQL:

 Column Aliases: Temporary names for columns in the result set.

 Table Aliases: Temporary names for tables used within a query.

Example of SQL Aliases


We will use the following Customer table to demonstrate all SQL alias
concepts. This table contains customer information such as ID, name,
country, age, and phone number.

CREATE TABLE Customer (

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

LastName VARCHAR(50),

Country VARCHAR(50),

Age INT,

Phone VARCHAR(15)

);

-- Inserting sample data into the Customer table

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,


Age, Phone)

VALUES

(1, 'Shubham', 'Thakur', 'India', 23, '9876543210'),

(2, 'Aman', 'Chopra', 'Australia', 21, '9876543211'),

(3, 'Naveen', 'Tulasi', 'Sri Lanka', 24, '9876543212'),

(4, 'Aditya', 'Arpan', 'Austria', 21, '9876543213'),

(5, 'Nishant', 'Jain', 'Spain', 22, '9876543214');

Output:

Customer CustomerNa LastNa Countr Ag


ID me me y e Phone

98765432
1 Shubham Thakur India 23
10
Customer CustomerNa LastNa Countr Ag
ID me me y e Phone

Australi 98765432
2 Aman Chopra 21
a 11

Sri 98765432
3 Naveen Tulasi 24
Lanka 12

98765432
4 Aditya Arpan Austria 21
13

98765432
5 Nishant Jain Spain 22
14

1. Column Aliases

A column alias is used to rename a column just for the output of a query.
They are useful when:

 Displaying aggregate data

 Making results more readable

 Performing calculations

Syntax:

SELECT column_name AS alias_name

FROM table_name;

The following table explains the arguments in detail:

 column_name: column on which we are going to create an alias


name.

 alias_name: temporary name that we are going to assign for the


column or table.
 AS: It is optional. If you have not specified it, there is no effect on the
query execution.

Example 1: Column Alias for Renaming a Column

To fetch the CustomerID and rename it as id in the result set

SELECT CustomerID AS id

FROM Customer;

Output:

id

2. Table Aliases

A table alias is used when you want to give a table a temporary name for the
duration of a query. Table aliases are especially helpful in JOIN operations to
simplify queries, particularly when the same table is referenced multiple
times (like in self-joins).

Example 2: Table Alias for Joining Tables

We want to join the Customer table with itself to find customers who have
the same country and are aged 21. We will use table aliases for each
instance of the Customer table.

Query:
SELECT c1.CustomerName, c1.Country

FROM Customer AS c1, Customer AS c2

WHERE c1.Age = c2.Age AND c1.Country = c2.Country;

Output:

CustomerNa Countr
me y

Shubham India

Australi
Aman
a

Sri
Naveen
Lanka

Aditya Austria

Nishant Spain

Here, c1 and c2 are aliases for two instances of the Customer table.

Combining Column and Table Aliases

We want to fetch customers who are aged 21 or older and rename the
columns for better clarity. We will use both table and column aliases.

Query:

SELECT c.CustomerName AS Name, c.Country AS Location

FROM Customer AS c

WHERE c.Age >= 21;

Output:
Locati
Name on

Shubha
India
m

Australi
Aman
a

Sri
Naveen
Lanka

Aditya Austria

Nishant Spain

Practical Uses of SQL Aliases

 Better Readability: Makes complex names shorter and easier to


understand.

 Simplifies Queries: Reduces repetition, especially in joins.

 Clear Output: Renames columns for more meaningful results.

 Avoids Conflicts: Prevents naming clashes in multi-table queries.


Chapter VI
SQL Operators
SQL Operators" refers to the fundamental symbols and keywords within the
SQL that enable users to perform various operations. Operators let you build
complex query conditions.

 AND Operator

 OR Operator

 Logical Operators

 LIKE Operator

 IN Operator

 NOT Operator

 NOT EQUAL Operator


 IS NULL Operator

 UNION Operator

 UNION ALL Operator

 EXCEPT Operator

 BETWEEN Operator

 ALL and ANY

 INTERSECT Operator

 EXISTS Operator

 CASE Operator

SQL AND and OR Operators

Last Updated : 23 Jul, 2025

The SQL AND and OR operators are used to filter data based on multiple
conditions. These logical operators allow users to retrieve precise results
from a database by combining various conditions in SELECT, INSERT,
UPDATE, and DELETE statements.

In this article, we'll learn the AND and OR operators, demonstrate their usage
with examples, and provide insights on combining them for complex
queries.

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.

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

SQL AND and OR Operator Examples

Let's look at some examples of AND and OR operators in SQL and


understand their working.

Now, we consider a table database to demonstrate AND & OR operators with


multiple cases.
Student Table

Example 1: SQL AND Operator

If suppose we want to fetch all the records from the Student table where Age
is 18 and ADDRESS is Delhi.

Query:

SELECT * FROM Student

WHERE Age = 18 AND ADDRESS = 'Delhi';

Output:

ROLL_N ADDRE Ag
O NAME SS PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

SURES XXXXXXXX
4 Delhi 18
H XX

Example 2: SQL OR Operator

To fetch all the records from the Student table where NAME is Ram or NAME
is SUJIT.
Query:

SELECT * FROM Student

WHERE NAME = 'Ram' OR NAME = 'SUJIT';

Output:

ROLL_N NAM ADDRE Ag


O E SS PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

XXXXXXXX
3 SUJIT ROHTAK 20
XX

XXXXXXXX
3 SUJIT ROHTAK 20
XX

Combining AND and OR Operators in SQL

Combining AND and OR Operators in SQL allows the creation of complex


conditions in queries. This helps in filtering data on multiple conditions.

Syntax:

Syntax to use AND and OR operator in one statement in SQL is:

SELECT * FROM table_name


WHERE condition1 AND (condition2 OR condition3);

Example

Let's look at example of combining AND and OR operators in a single


statement. In this example we will fetch all the records from the Student
table where Age is 18, NAME is Ram or RAMESH.

Query:

SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ram' OR NAME


= 'RAMESH');

Output:
ROLL_N ADDRES Ag
O NAME S PHONE e

XXXXXXXX
1 Ram Delhi 18
XX

RAMES GURGAO XXXXXXXX


2 18
H N XX

Important Points About SQL AND and OR Operators

 The SQL AND operator is used to combine multiple conditions, where


all the conditions must be true for the row to be included in the result
set.

 The OR operator is used to combine multiple conditions, where at least


one of the conditions must be true for the row to be included in the
result set.

 Any kind of condition, including equality, inequality, comparison, and


logical operators, can be utilized with the AND and OR operators.

 The AND operator is more important than the OR operator. In other


words, when both are used in the same SQL statement, the AND
operator will be executed first. To change the order of evaluation,
parentheses can be used.

 You can employ the AND and OR operators inside of other conditions
because they can both be nested.

Conclusion

The AND and OR operators are essential tools for filtering data in SQL. By
combining multiple conditions, you can create powerful and efficient queries
to retrieve exactly the data you need. Remember to use parentheses for
clarity and control the order of evaluation, especially when combining both
operators. By mastering these logical operators, you’ll be able to handle
complex queries and data filtering tasks more effectively.
SQL - Logical Operators

SQL Logical Operators are used to test conditions in queries, returning results
as TRUE, FALSE, or UNKNOWN. They help in combining, negating, and
comparing conditions, enabling precise data retrieval and filtering.

 Combine multiple conditions in a query.

 Control query execution flow.

 Support complex filtering and comparison.

 Return boolean results for decision-making.

 Useful for highly specific data retrieval.

Employee Table for Examples

We will use the following employee table throughout the examples. This
table represents employee details, including their unique ID, name, city, and
country.

employee Table

Below is the comprehensive list of SQL Logical Operators along with their
meanings, detailed explanations, and practical examples:

1. AND Operator

The AND operator is used to combine two or more conditions in an SQL


query. It returns records only when all conditions specified in the query are
true. This operator is commonly used when filtering data that must satisfy
multiple criteria simultaneously.
Example

Retrieve the records of employees from the employees table who are located
in 'Allahabad' and belong to 'India', ensuring that both conditions are met.

Query:

SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country


= 'India';

Output

output

Explanation:

In the output, both conditions (emp_city = 'Allahabad' and emp_country =


'India') are satisfied for the listed employees, so these records are returned
by the query.

2. IN Operator

The IN operator streamlines checking whether a value matches any value


from a specified list, making queries more concise and readable than using
multiple OR conditions. It is especially useful for filtering results by several
possible values in a column, helping reduce query complexity

Example

Retrieve the records of employees from the employee table who are located
in either 'Allahabad' or 'Patna'.

Query:

SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');

Output
output

Explanation:

In this query, the IN operator checks if the value of the emp_city column
matches any value in the list ('Allahabad', 'Patna'). The query returns all
employees who are located in either of these two cities.

3. NOT Operator

The NOT operator is used to reverse the result of a condition, returning TRUE
when the condition is FALSE. It is typically used to exclude records that
match a specific condition, making it useful for filtering out unwanted data.

Example

Retrieve the records of employees from the employee table whose city
names do not start with the letter 'A'.

Query:

SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';

Output

output

Explanation:

In this query, the NOT operator negates the LIKE condition. The LIKE operator
is used to match patterns in string data, and the 'A%' pattern matches any
city name that starts with the letter 'A'. By using the NOT operator, we
exclude cities starting with 'A' from the result set.

4. OR Operator
The OR operator combines multiple conditions in a SQL query and returns
TRUE if at least one of the conditions is satisfied. It is ideal for situations
where you want to retrieve records that meet any of several possible
conditions.

Example

Retrieve the records of employees from the employee table who are either
from 'Varanasi' or have 'India' as their country.

Query

SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country =


'India';

Output

output

Explanation:

In this case, the output includes employees from 'Varanasi' as well as those
who have 'India' as their country, even if they are from different cities. The
query returns all records where at least one of the conditions is true.

5. LIKE Operator

The LIKE operator in SQL is used in the WHERE clause to search for a
specified pattern in a column. It is particularly useful when we want to
perform pattern matching on string data. The LIKE operator works with two
main wildcards:

 %: Represents zero or more characters. It allows matching any


sequence of characters in the string.
 _: Represents exactly one character. It is used when you want to match
a specific number of characters at a given position.

Example

Retrieve the records of employees from the employee table whose city
names start with the letter 'P'.

Query:

SELECT * FROM employee WHERE emp_city LIKE 'P%';

Output

output

Explanation:

In this case, the output includes only those employees whose emp_city starts
with 'P'. The % wildcard ensures that the query matches any city name
starting with the specified letter, regardless of how many additional
characters follow it.

6. BETWEEN Operator

The BETWEEN operator in SQL allows us to test if a value or expression lies


within a specified range.

 Inclusive Range – Includes both the lower and upper limits in the
result set.

 Versatile Use – Works with numbers, dates, and text values.

 Efficient Filtering – Ideal for selecting data within a defined range.

Example

Retrieve the records of employees from the employee table


whose emp_id values fall within the range of 101 to 104 (inclusive).

Query:

SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;

Output
output

Explanation:

In this query, the BETWEEN operator is used to filter employees


with emp_id values ranging from 101 to 104. Since the BETWEEN operator is
inclusive, employees with emp_id values of 101, 102, 103, and 104 will be
included in the result set.

7. ALL Operator

The ALL operator in SQL is used to compare a value to all values returned by
a subquery.

 Returns TRUE only if the condition is TRUE for all values returned by
the subquery.

 Commonly used with SELECT, WHERE, and HAVING clauses.

 Ensures a value meets the specified condition when compared to an


entire result set.

Example

Retrieve the records of employees whose emp_id is equal to


all emp_id values in the employees table where the emp_city is 'Varanasi'.

Query:

SELECT * FROM employee WHERE emp_id = ALL

(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

Output
output

Explanation:

The query checks whether emp_id in the outer query is equal to


every emp_id from the subquery (which retrieves emp_id values from
employees in 'Varanasi'). In this case, the output will include employees
whose emp_id matches all the values in the subquery.

8. ANY Operator

The ANY operator in SQL is used to compare a value with the results of
a subquery.

 Returns TRUE if the value meets the condition with any value from the
subquery results.

 Useful for checking if a value matches at least one item in a set.

 Provides flexibility when comparing against multiple possible values.

Example

Retrieve the records of employees whose emp_id matches any of


the emp_id values in the employees table where the emp_city is 'Varanasi'.

Query:

SELECT * FROM employee WHERE emp_id = ANY

(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

Output
Explanation:

The output shows employees whose emp_id matches at least


one emp_id from employees in 'Varanasi' (e.g., 101, 102, 106).

9. EXISTS Operator

The EXISTS operator in SQL is used to check whether a subquery returns any
rows.

 Returns TRUE if the subquery returns one or more rows.

 Commonly used with SELECT, UPDATE, INSERT, and DELETE


statements.

 Helps check if any matching rows exist for a given condition.

 Often used in correlated subqueries referencing the outer query.

Example

Retrieve the names of employees from the employee table if there are any
employees in the employee table who are located in 'Patna'.

Query

SELECT emp_name FROM employee WHERE EXISTS

(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

Output
output

Explanation:

The EXISTS operator returns TRUE if the subquery finds any employees from
Patna, so all employee names are included. The query lists all employees as
long as at least one is from Patna.

10. SOME Operator

 Used with comparison operators (<, >, =, <=, etc.) to compare a value
against subquery results.

 Returns TRUE if the condition is satisfied for at least one value from the
subquery.

 Useful for matching a value against multiple possible results instead of


just one.

Example

Retrieve the records of employees from the employee table where


the emp_id is less than any of the emp_id values from employees located
in 'Patna'.

Query:

SELECT * FROM employee WHERE emp_id < SOME

(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

Output
output

Explanation:

The query returns employees whose emp_id is less than at least


one emp_id of employees from Patna.

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.

In this article, we will explain the SQL LIKE operator, its syntax, uses, and
practical examples. It also dives into advanced concepts like case sensitivity
and wildcard characters, helping you optimize your queries for better
performance and relevance.

What is the SQL LIKE Operator?

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%'

This following query will only return products whose name starts with "apple"
and is spelled exactly like that, without capital letters.

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'

'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.

'_wow Match strings that contain the substring 'wow' in them at the
%' 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.

Examples of SQL LIKE Operator

In this tutorial on SQL LIKE Operator, we will use the following table in the
examples.

Supplier Table

CREATE TABLE Supplier (

SupplierID CHAR(2) PRIMARY KEY,

Name VARCHAR(50),

Address VARCHAR(100)
);

INSERT INTO Supplier (SupplierID, Name, Address)

VALUES

('S1', 'Paragon Suppliers', '21-3, Okhla, Delhi'),

('S2', 'Mango Nation', '21, Faridabad, Haryana'),

('S3', 'Canadian Biz', '6/7, Okhla Phase II, Delhi'),

('S4', 'Caravan Traders', '2-A, Pitampura, Delhi'),

('S5', 'Harish and Sons', 'Gurgaon, NCR'),

('S6', 'Om Suppliers', '2/1, Faridabad, Haryana');

Supplier
ID Name Address

Paragon
S1 21-3, Okhla, Delhi
Suppliers

21, Faridabad,
S2 Mango Nation
Haryana

6/7, Okhla Phase II,


S3 Canadian Biz
Delhi

Caravan
S4 2-A, Pitampura, Delhi
Traders

Harish and
S5 Gurgaon, NCR
Sons

2/1, Faridabad,
S6 Om Suppliers
Haryana
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%';

Output:

S 6/7, Okhla Phase II,


Canadian Biz
3 Delhi

S Caravan
2-A, Pitampura, Delhi
4 Traders

Example 2: Match Addresses Containing 'Okhla'

Retrieve entire table, where address contains OKHLA.

SELECT *

FROM Supplier

WHERE Address LIKE '%Okhla%';

Output:

S Paragon
21-3, Okhla, Delhi
1 Suppliers

S 6/7, Okhla Phase II,


Canadian Biz
3 Delhi
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%';

Output:

S Mango 21, Faridabad,


2 Nation Haryana

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%';

Output:

Supplier
ID Name Address

6/7, Okhla Phase II,


S3 Canadian Biz
Delhi

Caravan
S4 2-A, Pitampura, Delhi
Traders

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%';

Output:

Supplier
ID Name Address

Paragon
S1 21-3, Okhla, Delhi
Suppliers

6/7, Okhla Phase II,


S3 Canadian Biz
Delhi

Caravan
S4 2-A, Pitampura, Delhi
Traders

Harish and
S5 Gurgaon, NCR
Sons

2/1, Faridabad,
S6 Om Suppliers
Haryana

SQL LIKE Application

The LIKE operator is extremely resourceful in situations such as address


filtering wherein we know only a segment or a portion of the entire address
(such as locality or city) and would like to retrieve results based on that. The
wildcards can be resourcefully exploited to yield even better and more
filtered tuples based on the requirement.

Key Takeaways About LIKE Operator

 LIKE operator is used to search for specific patterns in a column.

 It is mostly used with WHERE clause for finding or filtering specific


data.
 Like Operator is case-insensitive by default, to make it case sensitive,
we can use BINARY keyword.

 LIKE operator has 4 wild cards, which we can use with LIKE operator to
specify the filter. The wild cards are: %,_,[] and -.

Conclusion

The SQL LIKE operator is a powerful tool for pattern matching, allowing you
to perform flexible searches within columns. By combining wildcards and
logical operators, you can craft complex queries to find the data you need
with precision. Understanding how to optimize the use of LIKE with indexes
and case sensitivity will help improve query performance.

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.

In this article, we will learn about the IN operator in SQL by understanding


its syntax and examples.

IN Operator

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:

The Syntax of the IN operator is as follows:

SELECT column_name FROM table_name

WHERE condition IN (condition_value1, condition_value2 .....);


Here, we select the column column_name from the
table table_name where the condition is checked in all
the condition_values passed with the IN operator.

Example of SQL IN Operator

We will use the following SQL table for our examples below:

CREATE TABLE Employee (


Fname VARCHAR(50),
Lname VARCHAR(50),
Ssn INT,
Bdate DATE,
Address VARCHAR(100),
Sex CHAR(1),
Salary DECIMAL(10, 2)
);
INSERT INTO Employee (Fname, Lname, Ssn, Bdate, Address, Sex, Salary)
VALUES
('Chiranjeev', 'Singh', 1, '2002-07-31', 'Delhi', 'M', 1111789.00),
('Harry', 'Stark', 2, '1990-07-31', 'Delhi', 'M', 3333.00),
('Meghna', 'Gururaani', 5, '2002-04-04', 'Almora', 'F', 3433.00),
('Aniket', 'Bhardwaj', 6, '2001-05-05', 'Ponta', 'M', 56564.00),
('Vritti', 'Goel', 7, '2002-03-05', 'Delhi', 'F', 7565.00),
('Aashish', 'Kumar', 8, '2002-08-04', 'Himachal', 'M', 44657.00),
('Siddharth', 'Chaturvedi', 9, '2003-11-10', 'Lucknow', 'M', 244322.00);

Output:

Ss Addres Se
Fname Lname n Bdate s x Salary

Chiranje 2002-07- 1111789.


Singh 1 Delhi M
ev 31 00

1990-07-
Harry Stark 2 Delhi M 3333.00
31

Meghna Gururaan 5 2002-04- Almora F 3433.00


Ss Addres Se
Fname Lname n Bdate s x Salary

i 04

2001-05-
Aniket Bhardwaj 6 Ponta M 56564.00
05

2002-03-
Vritti Goel 7 Delhi F 7565.00
05

2002-08- Himach
Aashish Kumar 8 M 44657.00
04 al

Siddhart Chaturve 2003-11- Luckno 244322.0


9 M
h di 10 w 0

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

Output:
Lnam
Fname e

Chiranje
Singh
ev

Harry Stark

Vritti Goel

Kuma
Aashish
r

In this query, we fetched the Fname and Lname of all the employees whose
address is either Delhi or Himachal. To do so, we use the IN operator to pass
these values to the WHERE clause.

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

Output:
Fname

Meghn
a

Aniket

Aashis
h

Here, we have created a query to fetch the Fname of all employees whose
address is neither Delhi nor Lucknow. We used the NOT operator with IN to
exclude these values.

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 Departm
n ent

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


Output:

Ss Addre Se
Fname Lname n Bdate ss x Salary

Chiranje 2002-07- 1111789.


Singh 1 Delhi M
ev 31 00

Gururaa 2002-04-
Meghna 5 Almora F 3433.00
ni 04

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.

Conclusion

The SQL IN operator is a powerful tool for filtering data based on multiple
values. By eliminating the need for multiple OR conditions, it makes your
queries more concise and readable. Whether you’re filtering records from a
list of values or using a subquery, the IN operator offers an elegant and
efficient solution. Mastering the IN operator can help you write cleaner and
more efficient SQL queries that scale with your data.

SQL NOT Operator

The SQL NOT Operator is a logical operator used to negate or reverse the
result of a condition in SQL queries. It is commonly used with the WHERE
clause to filter records that do not meet a specified condition, helping you
exclude certain values from your results.

In this article, we will learn everything you need to know about the SQL NOT
operator, from basic usage to advanced examples.

What is the 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;

Examples of SQL NOT Operator

CREATE TABLE Customers (

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

City VARCHAR(50),

PostalCode VARCHAR(10),

Country VARCHAR(50)

);
INSERT INTO Customers (CustomerID, CustomerName, City, PostalCode,
Country)

VALUES

(1, 'John Wick', 'New York', '1248', 'USA'),

(2, 'Around the Horn', 'London', 'WA1 1DP', 'UK'),

(3, 'Rohan', 'New Delhi', '100084', 'India');

Customer Customer PostalCo Count


ID Name City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn

New
3 Rohan 100084 India
Delhi

Example 1: Using SQL NOT to Exclude a Specific Value

The following SQL statement selects all fields from Customers table where
the country is not UK.

Query:

SELECT *

FROM Customers

WHERE NOT Country = 'UK';

Output:
Customer Customer PostalCo Count
ID Name City de ry

New
1 John Wick 1248 USA
York

New
3 Rohan 100084 India
Delhi

In this example, the NOT operator filters out customers from the UK and
returns all other customers.

Example 2: Using SQL NOT with IN Operator

The NOT operator can also be used with the IN condition to exclude multiple
values from the result set.

Query:

SELECT *

FROM Customers

WHERE NOT Country IN ('USA', 'UK');

Output:

Customer Customer PostalCo Count


ID Name City de ry

New
3 Rohan 100084 India
Delhi

Here, the NOT IN condition filters out customers from both the USA and UK
and returns only customers from other countries.

Example 3: Using SQL NOT with LIKE Operator

We can also combine NOT with the LIKE operator to exclude records that
match a certain pattern.
Query:

SELECT *

FROM Customers

WHERE NOT CustomerName LIKE 'R%';

Output:

Customer CustomerNa PostalCo Count


ID me City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn

In this query, the NOT LIKE condition filters out customers whose name starts
with the letter 'R', returning all others.

Example 4: Using SQL NOT with NULL Values

To exclude records where a column has a NULL value, combine NOT with the
IS NULL condition.

Query:

SELECT *

FROM Customers

WHERE NOT PostalCode IS NULL;

Output:
Customer CustomerNa PostalCo Count
ID me City de ry

New
1 John Wick 1248 USA
York

Around the
2 London WA1 1DP UK
Horn

New
3 Rohan 100084 India
Delhi

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

Output:

Customer CustomerNa PostalCo Count


ID me City de ry

New
3 Rohan 100084 India
Delhi

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.

Conclusion

The SQL NOT operator is an essential tool for SQL developers. Whether
you're excluding specific records, filtering null values, or creating more
complex logical conditions, the NOT operator helps you fine-tune your
queries. Understanding how to combine it with other SQL operators will
improve your ability to write more efficient and precise SQL queries.

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. It helps filter out records that
match certain conditions, making it a valuable tool in SQL queries.

In this article, We will explore the SQL NOT EQUAL operator, including its
syntax, use cases, and examples for both beginners and advanced users.

NOT EQUAL Operator in SQL

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;

Examples of NOT EQUAL Operator

Let's look at some examples of the NOT EQUAL Operator in SQL, and
understand its working.

First, we will create a demo SQL database and table on which we will use the
NOT EQUAL operator.

Query:

CREATE TABLE geeksforgeeks(

user_id varchar(100) PRIMARY KEY,

name varchar(100),

contest_score int,

rank int,

coding_streak int

);

INSERT INTO geeksforgeeks(user_id,name,contest_score,rank,coding_streak)

VALUES('vish3001','Vishu',100,01,150);

INSERT INTO geeksforgeeks(user_id,name,contest_score,rank,coding_streak)

VALUES('neeraj119','Neeraj',99,02,125);

INSERT INTO geeksforgeeks(user_id,name,contest_score,rank,coding_streak)

VALUES('ayush105','Aayush',98,03,110);

INSERT INTO geeksforgeeks(user_id,name,contest_score,rank,coding_streak)

VALUES('sumit85','Sumit',99,02,100);

INSERT INTO geeksforgeeks(user_id,name,contest_score,rank,coding_streak)


VALUES('harsh05','Harsh',98,03,95);

Output:

contest_sc ran coding_str


user_id name ore k eak

vish300
Vishu 100 1 150
1

neeraj1 Neera
99 2 125
19 j

ayush10 Aayus
98 3 110
5 h

sumit85 Sumit 99 2 100

harsh05 Harsh 98 3 95

Example 1: SQL NOT EQUAL Operator For String

In this example, we will display all those rows which do not have a name
equal to 'Harsh'. We will use NOT EQUAL with WHERE clause in this case.

Query:

SELECT *

FROM students

WHERE name != 'Harsh';


Output:

SQL NOT operator For String

In the above image, we can see we have all those rows displayed which do
not have their name equal to 'Harsh'.

Note: The NOT EQUAL comparison is case-sensitive for strings. Meaning


"geeks" and "GEEKS" are two different strings for NOT EQUAL operator.

Example 2: SQL NOT EQUAL Operator with Multiple Condition

In this example, we will display all those rows which do not have their
contest score as 98 and rank as 3 and the coding streak should be greater
than or equal to 100. Using AND or OR operator you can use the SQL NOT
operator for multiple values.

Query:

SELECT * FROM geeksforgeeks

WHERE contest_score != 98 AND rank != 3

AND coding_streak >= 100;

Output:
SQL NOT EQUAL Operator with Multiple Condition

In the above image, we can observe that all those rows are displayed which
have followed all three conditions.

Example 3: SQL NOT EQUAL Operator with GROUP BY Clause

In this example, we will display all those ranks with their count that do not
have their contest score as 100 using GROUP BY clause.

Query:

SELECT rank, COUNT(*) as count_score

FROM geeksforgeeks

WHERE contest_score <> 100

GROUP BY rank;

Output:

SQL NOT
EQUAL Operator with GROUP BY Clause

In the above image, we can see ranks 2, and 3 have a count of 2 and, 2
respectively.

Also Read: EQUAL Operators in SQL


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.

Conclusion

The SQL NOT EQUAL operator is a powerful comparison operator that helps
filter records where values do not match a given condition. It can be used
with various data types (strings, numbers, dates) and combined with other
logical operators for complex querying. By understanding and implementing
the NOT EQUAL operator in SQL, we can write more efficient and accurate
queries to exclude specific data from your result set.

SQL IS NULL

The SQL IS NULL operator is a logical operator used to identify


and filter out rows with NULL values in a column. A NULL value represents
missing or undefined data in a database. It is different from a zero value
or blank space, and it indicates that the value is unknown.

In this article, we will learn how to use the IS NULL operator in SQL, with
practical examples to help you understand its functionality.

What is the SQL IS NULL Operator?

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.

SQL IS NULL Examples

Let's look at some examples of the IS NULL operator in SQL. These examples
will help in understanding the working of IS NULL in SQL.

First, we will create a demo SQL database and table, on which we will use the
IS NULL operator.

Query:

CREATE TABLE geeksforgeeks(

user_id int PRIMARY KEY,

name varchar(100),

problems_solved int,

coding_score int,

email varchar(100)

);

INSERT INTO geeksforgeeks (user_id, name, problems_solved, coding_score,


email)

VALUES

(101, 'Vishu', 20, 100, '[email protected]'),

(102, 'Sumit', 19, 99, NULL),

(103, 'Neeraj', 18, 98, '[email protected]'),

(104, 'Aayush', 17, 97, NULL),

(105, 'Harsh', 16, NULL, '[email protected]'),


(106, 'Rahul', 15, NULL, '[email protected]'),

(107, 'Vivek', 14, 90, NULL);

SELECT* FROM geeksforgeeks;

Output:

user_i problems_sol coding_sc


d name ved ore email

[email protected]
101 Vishu 20 100
om

102 Sumit 19 99

Neera [email protected]
103 18 98
j om

Aayus
104 17 97
h

[email protected]
105 Harsh 16
om

[email protected]
106 Rahul 15
om

107 Vivek 14 90

Example 1: IS NULL with WHERE clause

To filter rows where the email column contains NULL, use the IS NULL
operator in a WHERE clause:

Query:
SELECT *

FROM students

WHERE email IS NULL;

Output:

IS NULL with WHERE clause

Example 2: IS NULL Operator on Multiple Columns

We can use the IS NULL operator with multiple columns. For instance, to filter
rows where either email or coding_score is NULL, use the OR operator:

Query:

SELECT *

FROM students

WHERE email IS NULL OR coding_score IS NULL;

Output:

IS NULL Operator on Multiple Columns

Example 3: IS NULL with COUNT() Function


The COUNT() function can be used to count the number of NULL values in a
column. For example, to count how many rows have a NULL value in the
coding_score column

SELECT COUNT(*) AS count_empty_coding_score

FROM students

WHERE coding_score IS NULL;

Output:

IS NULL with COUNT() Function

We can clearly see in our table that we have 2 rows that have NULL values in
their coding score column i.e. user_id: 105,106.

Example 4: IS NULL with UPDATE Statement

We can update NULL values using the IS NULL operator in


an UPDATE statement. For example, let's set a default email for all users with
a NULL value in the email column

Query:

UPDATE students

SET email = '[email protected]'

WHERE email IS NULL;

Output:
IS NULL with UPDATE Statement

As we can see user_id's: 102, 104, and 107 previously contain NULL values in
their emails column but now they have a default value i.e.
"[email protected]".

Example 5: IS NULL with DELETE Statement

We can also use the IS NULL operator to delete rows where a column
contains NULL values. For example, to delete rows where coding_score is
NULL

Query:

DELETE FROM students

WHERE coding_score IS NULL;

Output:

IS NULL with the DELETE Statement


We can notice clearly that all those rows deleted have a null value in their
coding score column.

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.

Conclusion

The SQL IS NULL operator is essential for handling missing data in SQL
queries. Whether you're filtering results, counting missing values, or
updating/cleaning data, understanding how to use IS NULL effectively is
crucial for working with databases. By mastering this operator, you can write
more precise and efficient SQL queries, especially when dealing with
incomplete or sparse data.

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. It is a powerful tool in SQL
that helps aggregate data from multiple tables, especially when the tables
have similar structures.

In this guide, we'll explore the SQL UNION operator, how it differs
from UNION ALL, and provide detailed examples to demonstrate its usage.

What is SQL UNION Operator?

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.

Examples of SQL UNION

Let's look at an example of UNION operator in SQL to understand it better.

Let's create two tables "Emp1" and "Emp2";

Emp1 Table

Write the following SQL query to create Emp1 table.

CREATE TABLE Emp1(

EmpID INT PRIMARY KEY,

Name VARCHAR(50),

Country VARCHAR(50),

Age int(2),

mob int(10)

);

-- Insert some sample data into the Customers table


INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)

VALUES (1, 'Shubham', 'India','23','738479734'),

(2, 'Aman ', 'Australia','21','436789555'),

(3, 'Naveen', 'Sri lanka','24','34873847'),

(4, 'Aditya', 'Austria','21','328440934'),

(5, 'Nishant', 'Spain','22','73248679');

SELECT* FROM Emp1;

Output:

Emp1 Table

Emp2 Table

Write the following SQL query to create Emp2 table

CREATE TABLE Emp2(

EmpID INT PRIMARY KEY,

Name VARCHAR(50),

Country VARCHAR(50),

Age int(2),

mob int(10)

);

-- Insert some sample data into the Customers table


INSERT INTO Emp2 (EmpID, Name,Country, Age, mob)

VALUES (1, 'Tommy', 'England','23','738985734'),

(2, 'Allen', 'France','21','43678055'),

(3, 'Nancy', 'India','24','34873847'),

(4, 'Adi', 'Ireland','21','320254934'),

(5, 'Sandy', 'Spain','22','70248679');

SELECT * FROM Emp2;

Output:

Emp2 Table

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;

Output:
output

Example 2: SQL UNION ALL

In the below example, we will find the cities (duplicate values also) from both
the "Emp1" and the "Emp2" tables:

Query:

SELECT Country FROM Emp1

UNION ALL

SELECT Country FROM Emp2

ORDER BY Country;

Output:

Country

Australi
a

Austria

Englan
Country

France

India

India

Ireland

Spain

Spain

Sri
lanka

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 "Geeks1" and the "Geeks2" tables:

Query:

SELECT Country, Name FROM Emp1

WHERE Name='Aditya'
UNION ALL

SELECT Country, Name FROM Emp2

WHERE Country='Ireland'

ORDER BY Country;

Output:

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.

Conclusion

The SQL UNION operator is a powerful tool for combining multiple SELECT
statements into one result set. Whether you need to eliminate duplicates or
include them, UNION and UNION ALL provide flexible options for aggregating
data from multiple tables. Understanding how and when to use these
operators will make your SQL queries more efficient and effective for data
retrieval and analysis.
SQL UNION ALL

UNION ALL Operator is used to combine the results of two or


more SELECT statements into a single result set. Unlike the UNION operator,
which eliminates duplicate records and UNION ALL includes all duplicates.
This makes UNION ALL it faster and more efficient when we don't need to
remove duplicates.

In this article, we will learn the SQL UNION ALL operator, how it compares
with UNION, and practical examples to demonstrate its usage in real
applications.

SQL UNION ALL Operator

 The SQL UNION ALL command combines the result of two or


more SELECT statements in SQL.

 For performing the UNION ALL operation, it is necessary that both


the SELECT statements should have an equal number
of columns/fields, otherwise, the resulting expression will result in an
error.

Syntax:

The syntax for the SQL UNION ALL operation is:

SELECT columns FROM table1

UNION ALL

SELECT columns FROM table2;

Examples of SQL UNION ALL

Let's look at some examples of the UNION ALL command in SQL to


understand its working. First, let's create a demo SQL database and tables on
which UNION ALL will be performed.

Demo SQL Database

In this tutorial on the UNION ALL operator, we will use the following table in
examples.

STUDENTS table:
ROLL_N AG
O NAME DOB E

DEV 2001-08-
1 17
SHARMA 16

AMAN 2002-01-
2 16
VERMA 04

KRISH 2000-11-
3 18
VATSA 29

TRIP_DETAIL Table:

ROLL_N AG
O NAME DOB E

DEV 2001-08-
1 17
SHARMA 16

AMAN 2002-01-
2 16
VERMA 04

KRISH 2000-11-
3 18
VATSA 29

VARUN 2003-09-
4 15
GOYAL 21

Example 1: Single Field With Same Name


We want to combine the names from both
the STUDENTS and TRIP_DETAIL tables, including all names, even if there are
duplicates.

SELECT NAME FROM STUDENTS

UNION ALL

SELECT NAME FROM TRIP_DETAIL;

Output:

NAME

DEV
SHARMA

AMAN
VERMA

KRISH
VATSA

DEV
SHARMA

AMAN
VERMA

KRISH
VATSA

VARUN
GOYAL
Explanation: The UNION ALL operator combines all rows from
the NAME column in both tables. It includes all names, including duplicates.
In this case, "DEV SHARMA", "AMAN VERMA", and "KRISH VATSA" appear
twice because they exist in both tables.

Example 2: Different Field Names

Suppose We want to combine the ROLL_NO from both tables and align the
column names for consistency.

Query:

SELECT ROLL_NO AS Identifier FROM STUDENTS

UNION ALL

SELECT ROLL_NO AS Identifier FROM TRIP_DETAIL;

Output:

Identifi
er

4
Explanation: Here, ROLL_NO from both tables is selected and aliased
as Identifier. The UNION ALL operator combines all roll numbers from both
tables, including duplicates. Each ROLL_NO from STUDENTS appears twice
because it also exists in TRIP_DETAIL.

Important Points About SQL UNION All

 UNION ALL command helps us to combine results of two or


more SELECT statements from different tables.

 The UNION ALL command includes the duplicate records from the
SELECT statements whereas the UNION command does not include
duplicate records otherwise both the commands are same.

 For performing the UNION ALL operation, it is necessary that both the
SELECT statements should have equal number of columns otherwise
the resulting expression will result in an error.

SQL UNION All vs UNION

Here is the comparison between UNION ALL and UNION Operator:

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 When duplicates need to


Use Case
acceptable or needed be removed

SELECT columns FROM table1 SELECT columns FROM


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

Memory Generally lower, since no Higher, due to additional


Feature UNION ALL UNION

extra processing for


Usage steps for duplicate removal
duplicates

Combined rows from Combined rows from


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

Useful for large datasets


Useful when data integrity
Applicabilit where performance is critical
requires unique records in
y and duplicates are
the result set
acceptable

Conclusion

The UNION ALL operator is a powerful tool for combining results from
multiple queries while preserving all rows, including duplicates. It is
particularly useful when you need to aggregate data from similar sources or
when duplicates are not a concern. The examples provided illustrate
how UNION ALL works with columns of the same and different names.

Can UNION ALL be used with different data types?

No, the columns being combined with UNION ALL must have compatible data
types. If they differ, you may need to cast or convert the data types to make
them compatible.

How does UNION ALL handle NULL values?

UNION ALL will include NULL values in the result set. If NULL values exist in
the result sets of the queries being combined, they will appear in the final
result set.

Can UNION ALL be used with more than two tables?

Yes, UNION ALL can combine results from more than two SELECT queries.
You can chain multiple SELECT queries with UNION ALL to aggregate data
from several sources.
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.

In this article, we will learn how the SQL EXCEPT operator works, and its
syntax, and compare it with similar operators like NOT IN. We will also look
at practical examples to help you better understand its usage.

What is SQL EXCEPT?

The SQL EXCEPT operator allows you to return the rows that exist in the
first result set but not in the second. It is useful for finding records in one
table that do not have corresponding records in another table.

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.

Examples of SQL EXCEPT

Let’s consider two tables, Students and Teaching Assistant. We will


perform all the examples based on these two tables.

Students Table

-- Create Students Table

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

Name VARCHAR(100),
Course VARCHAR(100)

);

-- Insert Data into Students Table

INSERT INTO Students (StudentID, Name, Course) VALUES

(1, 'Rohan', 'DBMS'),

(2, 'Kevin', 'OS'),

(3, 'Mansi', 'DBMS'),

(4, 'Mansi', 'ADA'),

(5, 'Rekha', 'ADA'),

(6, 'Megha', 'OS');

Output:

Student Nam Cours


ID e e

Roha
1 DBMS
n

2 Kevin OS

Mans
3 DBMS
i

Mans
4 ADA
i

Rekh
5 ADA
a
Student Nam Cours
ID e e

Megh
6 OS
a

Teaching Assistant Table

-- Create Teaching Assistant Table

CREATE TABLE TA (

StudentID INT PRIMARY KEY,

Name VARCHAR(100),

Course VARCHAR(100)

);

-- Insert Data into TA Table

INSERT INTO TA (StudentID, Name, Course) VALUES

(1, 'Kevin', 'TOC'),

(2, 'Sita', 'IP'),

(3, 'Manik', 'AP'),

(4, 'Rekha', 'SNS');

Output:
Student Nam Cours
ID e e

Kevi
1 TOC
n

2 Sita IP

Mani
3 AP
k

Rekh
4 SNS
a

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;

Output:

Name

Mans
i

Megh
Name

Roha
n

Explanation: The EXCEPT operator returns the names that are present in
the Students table but not in the TA table. Notice that "Rohan", "Mansi", and
"Megha" are returned, as these students are not listed in the TA table.

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 NameFROM StudentsEXCEPTSELECT NameFROM TA;

Output:

Name

Roha
n

Mans
i

Mans
i

Megh
Name

Explanation: In this case, "Mansi" appears twice in the output because it


appears twice in the Students table and is not in the TA table. EXCEPT ALL
retains duplicates from the first result set.

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 Retains duplicates in the


Handling the result result

Generally more efficient for May be slower for large


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

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


Use Case that exist in one result set specific column’s values
but 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.

Conclusion

The SQL EXCEPT operator is a powerful tool for excluding rows from one
query that exist in another. It helps eliminate unwanted data, making it
valuable for various analytical tasks. Understanding how EXCEPT works, as
well as its differences from other operators like NOT IN, allows you to make
better decisions when structuring your SQL queries for optimal performance.

SQL BETWEEN Operator

The BETWEEN operator in SQL is used to filter records within a specific


range. Whether applied to numeric, text, or date columns it simplifies the
process of retrieving data that falls within a particular boundary.

In this article, we will explore the SQL BETWEEN operator with examples.

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.

Examples of BETWEEN Operator

To understand the SQL BETWEEN Operator we will use the below


below employees table with the various examples and their output.

Employee FirstNa LastNa Ag Sala HireDat


ID me me e ry e

5000 2021-01-
1 John Doe 28
0 15

6000 2020-03-
2 Jane Smith 34
0 22

7500 2018-07-
3 Sam Brown 45
0 10

4 Sue Wilson 25 4800 2021-10-


Employee FirstNa LastNa Ag Sala HireDat
ID me me e ry e

0 01

6800 2019-05-
5 Tom Harris 38
0 12

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

Output:

FirstNa LastNa
me me

Jane Smith

Sue Wilson

Explanation:
The query retrieves employees whose last names fall outside the
alphabetical range of 'B' to 'S'. Only Tom Harris qualifies, as 'Harris' comes
after 'B' but before 'S'.

Example 2: BETWEEN Dates

Find employees hired between January 1, 2020 and December 31, 2021.

Query:

SELECT FirstName, LastName, HireDate

FROM Employees

WHERE HireDate BETWEEN '2020-01-01' AND '2021-12-31';

Output:

FirstNa LastNa HireDat


me me e

2020-03-
Jane Smith
22

2021-01-
John Doe
15

2021-10-
Sue Wilson
01

Explanation:

This query returns employees who were hired during the years 2020 and
2021. The BETWEEN operator is used to filter the HireDate field, returning
records within the specified date range.

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;

Output:

FirstNa LastNa Ag
me me e

John Doe 28

Sam Brown 45

Sue Wilson 25

Explanation:

This query retrieves employees whose age does not fall between 30 and 40.
The NOT BETWEEN operator is used here to exclude employees within that
age range. John, Sam, and Sue meet this condition, as their ages are outside
the 30-40 range.

Example 4: BETWEEN with IN

Find employees whose salaries are between 50,000 and 70,000 and
whose first names are either 'John', 'Sue', or 'Tom'.

Query:

SELECT FirstName, LastName, Salary

FROM Employees

WHERE Salary BETWEEN 50000 AND 70000

AND FirstName IN ('John', 'Sue', 'Tom');


Output:

FirstNa LastNa Sala


me me ry

5000
John Doe
0

4800
Sue Wilson
0

Explanation:

This query filters employees with salaries between 50,000 and 70,000 and
also checks if their first names are in the list ('John', 'Sue', 'Tom'). Only John
and Sue satisfy both conditions.

Conclusion

The SQL BETWEEN operator is an efficient and easy-to-use tool for filtering
data across a range. Whether used for text values, numbers, or dates, its
inclusiveness and flexibility make it an essential tool for SQL queries. With its
capability to combine with other operators like NOT and IN, it allows for
complex data retrieval while maintaining simplicity.

SQL | ALL and ANY

In SQL, the ALL and ANY operators are logical operators used to compare
a value with a set of values returned by a subquery. These operators provide
powerful ways to filter results based on a range of conditions.

In this article, we will explore ALL and ANY in SQL, their differences, and
how to use them effectively to boost your query performance and
efficiency.

What is the 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.

How to Use SQL ALL with SELECT, WHERE, and HAVING

The ALL operator can be used in conjunction with SELECT, WHERE,


and HAVING statements to refine your data filtering.

lets Consider the following Products Table and OrderDetails Table for
explaining the examples.

Products Table
OrderDetails Table

Queries

Example 1 : Retrieve all product names from the Products table.

Query:

SELECT ALL ProductName

FROM Products

WHERE TRUE;
Output:

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

Output:

This query ensures that the product names returned have ALL quantities of 6
or 2 in the OrderDetails table.
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);

Output:

ANY

This query filters out OrderIDs where the maximum quantity is greater than
the average quantity of the orders.

What is the 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);

Output:

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

Output:

product names

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.

Conclusion

The ALL and ANY operators in SQL are essential for advanced filtering based
on dynamic conditions. The key differences lie in how they evaluate the
conditions across the results of the subquery. ALL requires the condition to
be true for all values in the subquery, while ANY only needs the condition to
be true for one value. By mastering these operators, you can write more
efficient and flexible SQL queries.

SQL | INTERSECT Clause

In SQL, the INTERSECT clause is used to retrieve the common


records between two SELECT queries. It returns only the rows that are
present in both result sets. This makes INTERSECT an essential clause when
we need to find overlapping data between two or more queries.

In this article, we will explain the SQL INTERSECT clause, its syntax, key
characteristics, and examples. We will also explore its usage with
conditions like BETWEENand LIKE, along with performance considerations
and alternatives.

What is SQL INTERSECT?

The INTERSECT clause in SQL is used to combine two SELECT statements but
the dataset returned by the INTERSECT statement will be the intersection
of the data sets of the two SELECT statements. In simple words, the
INTERSECT statement will return only those rows that will be common to
both of the SELECT statements.

The INTERSECT operator is a set operation in SQL, similar to UNION


and EXCEPT. While UNION combines results from two queries and removes
duplicates, 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

Examples of SQL INTERSECT

Let’s consider two tables: the Customers table, which holds customer
details, and the Orders table, which contains information about customer
purchases. By applying the INTERSECToperator, we can retrieve customers
who exist in both tables, meaning those who have made purchases.
Customers Table

Customers Table

Orders Table

Orders Table

Example 1: Basic INTERSECT Query


In this example, we retrieve customers who exist in both
the Customers and Orders tables. The INTERSECT operator ensures that
only those customers who have placed an order appear in the result.

Query:

SELECT CustomerID
FROM Customers
INTERSECT
SELECT CustomerID
FROM Orders;

Output:

Customer
ID

Explanation:

 The query returns only those customers who appear in both


the Customers and Orders tables.

 If a customer exists in Customers but has never placed an order, they


won’t appear in the result.
 Customer IDs 2, 3, 5, 6, 7, and 8 appear in both
the Customers and Orders tables

Example 2: Using INTERSECT with BETWEEN Operator

In this example, we apply the INTERSECT operator along with


the BETWEEN condition to filter records based on a specified range. The
query retrieves customers whose CustomerID falls between 3 and 8 and
who have placed an order. The result contains only the
common CustomerID values that meet both conditions.

Query:

SELECT CustomerID
FROM Customers
WHERE CustomerID BETWEEN 3 AND 8
INTERSECT
SELECT CustomerID
FROM Orders;

Output:

Customer
ID

8
Explanation:

 The first SELECT statement filters customers with CustomerIDbetween


3 and 8.

 The INTERSECT operator ensures that only customers from this filtered
set who have placed an order are included in the result.

 Customers 3, 5, 6, 7, and 8 fall within the specified range (3 to 8).

Example 3: Using INTERSECT with LIKE Operator

In this example, we use the INTERSECT operator along with


the LIKE operator to find common customers whose FirstName starts with
the letter 'J' in both the Customers and Orders tables.

Query:

SELECT CustomerID
FROM Customers
WHERE FirstName LIKE 'J%'
INTERSECT
SELECT CustomerID
FROM Orders;

Output:

Customer
ID

Explanation:

 The query finds customers whose first name starts with 'J'
in both the Customers and Orders tables.
 The INTERSECT operator ensures that only those customers who have
placed an order are included in the result.

 The final output includes Customer 2 (Jane) only, as per the given
example.

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 usingINNER JOIN.

Conclusion

TheINTERSECT clause is a powerful SQL operator that allows users to find


overlapping data between queries efficiently. By understanding its syntax
and practical use cases, we can efficiently analyze overlapping data in a
structured manner. Whether we are filtering customer data, analyzing
orders, or handling complex datasets, INTERSECT ensures that you
retrieve only the common records between two result sets.
Use INTERSECT along with conditions (WHERE, BETWEEN, LIKE) to refine
results and extract meaningful insights from our database.

SQL | EXISTS

The SQL EXISTS condition is used to test whether a correlated


subquery returns any results. If the subquery returns at least one row, the
EXISTS condition evaluates to TRUE; otherwise, it evaluates to FALSE. The
EXISTS operator can be used in various SQL statements like SELECT,
UPDATE, INSERT, and DELETE to filter data based on whether certain
conditions are met.

What is 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.

Examples of SQL EXISTS

Consider the following two relation "Customers" and "Orders".


Customers Table

Orders Table:

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


Output:

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

Output:

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;

Output:

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;


Output:

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.

Conclusion
The SQL EXISTS condition is an essential tool for database professionals,
helping to test the existence of records in a subquery. By using EXISTS, you
can perform various operations such as SELECT, UPDATE, INSERT, and
DELETE based on the presence of related data. Whether you're checking if
customers have placed orders or performing data integrity checks, EXISTS
provides a powerful, efficient way to filter and manipulate data.

SQL CASE Statement

Last Updated : 10 Dec, 2024

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.

In this article, we'll learn the SQL CASE statement in detail, with clear
examples and use cases that show how to leverage this feature to improve
your SQL queries.

CASE Statement in SQL

 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:

To use CASE Statement in SQL, use the following syntax:


CASE case_value
WHEN condition THEN result1
WHEN condition THEN result2
...
Else result
END CASE;

Example of SQL CASE Statement

Let's look at some examples of the CASE statement in SQL to understand it


better.

Let's create a demo SQL table, which will be used in examples.

Demo SQL Database

We will be using this sample SQL table for our examples on SQL CASE
statement:

Customer LastNa Countr Ag


ID CustomerName me y e Phone

xxxxxxx
1 Shubham Thakur India 23
xxx

Australi xxxxxxx
2 Aman Chopra 21
a xxx

Sri xxxxxxx
3 Naveen Tulasi 24
Lanka xxx

xxxxxxx
4 Aditya Arpan Austria 21
xxx

Nishant. Salchichas xxxxxxx


5 Jain Spain 22
S.A. xxx
You can create the same Database in your system, by writing the following
MySQL query:

CREATE TABLE Customer(

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50),

LastName VARCHAR(50),

Country VARCHAR(50),

Age int(2),

Phone int(10)

);

-- Insert some sample data into the Customers table

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country,


Age, Phone)

VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),

(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),

(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),

(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),

(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

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;
Output:

Ag National
CustomerName e ity

Shubham 23 Indian

Aman 21 Foreign

Naveen 24 Foreign

Aditya 21 Foreign

Nishant. Salchichas
22 Foreign
S.A.

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;

Output:
Ag
CustomerName e QuantityText

The Age is greater


Shubham 23
than 22

Aman 21 The Age is 21

The Age is greater


Naveen 24
than 22

Aditya 21 The Age is 21

Nishant. Salchichas
22 The Age is over 30
S.A.

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

Output:
Count
CustomerName ry

Australi
Aman
a

Aditya Austria

Nishant. Salchichas
Spain
S.A.

Sri
Naveen
lanka

Shubham India

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.

Conclusion

The CASE statement provides a robust mechanism for incorporating


conditional logic in SQL queries. By using this statement, you can handle
various conditions and customize the output of your queries effectively.
Understanding how to implement CASE expressions allows you to perform
more sophisticated data manipulation and reporting, making your SQL
queries more dynamic and responsive to different scenarios.

Chapter- VII
SQL Aggregate Functions
Whether you are calculating the total sales revenue for a particular product,
finding the average age of customers, or determining the highest value in a
dataset, SQL Aggregate Functions make these tasks straightforward and
manageable.

 Aggregate Function

 Count() Function

 SUM() Function

 MIN() Function

 MAX() Function

 AVG() Function

SQL Aggregate functions

SQL Aggregate Functions are used to perform calculations on a set of rows


and return a single value. These functions are particularly useful when we
need to summarize, analyze or group large datasets in SQL databases.

They are often used with GROUP BY clause in SQL to summarize data for
each group. Commonly used aggregate functions include COUNT(), SUM(),
AVG(), MIN() and MAX().

Key Features of 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, 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()

It is used to count the number of rows in a table. It helps summarize data by


giving the total number of entries. It can be used in different ways depending
on what you want to count:

 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()

It is used to calculate the total of a numeric column. It adds up all non-NULL


values in that column for Example, SUM(column_name) returns sum of all
non-NULL values in the specified 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()

It is used to calculate average value of a numeric column. It divides sum of


all non-NULL values by the number of non-NULL rows for
Example, AVG(column_name) returns average of all non-NULL values in the
specified 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.

Examples:

-- Find the highest salary


SELECT MAX(Salary) AS HighestSalary FROM Employee;

-- Find the lowest salary


SELECT MIN(Salary) AS LowestSalary FROM Employee;

Examples Queries

Let's consider a demo Employee table to demonstrate SQL aggregate


functions. This table contains employee details such as their ID, Name and
Salary.
Nam Sala
Id e ry

1 A 802

2 B 403

3 C 604

4 D 705

5 E 606

6 F NULL

1. Count Total Number of Employees

SELECT COUNT(*) AS TotalEmployees FROM Employee;

Output:

TotalEmploy
ees

2. Calculate Total Salary

SELECT SUM(Salary) AS TotalSalary FROM Employee;

Output:
TotalSal
ary

3120

3. Find Average Salary

SELECT AVG(Salary) AS AverageSalary FROM Employee;

Output:

AverageSal
ary

624

4. Find Highest and Lowest Salary

SELECT MAX(Salary) AS HighestSalary FROM Employee;

Output:

HighestSal
ary

802

SQL Count() Function

In the world of SQL, data analysis often requires us to get counts of rows or
unique values. The COUNT() function is a powerful tool that helps us
perform this task. Whether we are counting all rows in a table, counting rows
based on a specific condition, or even counting unique values,
the COUNT() function is essential for summarizing data.
In this article, we will cover the COUNT() function in detail, including
its syntax, examples, and different use cases such as counting rows with
conditions and using it with GROUP BY and HAVING.

What is the SQL COUNT() Function?

The COUNT() function in SQL is an aggregate function that returns the


number of rows that match a specified condition in a query. It can count all
rows in a table, count distinct values in a column, or count rows based on
certain criteria. It is often used in reporting and analysis to aggregate data
and retrieve valuable insights. The COUNT() function is often used
in reporting, analytics, and business intelligence queries to summarize
large datasets, helping us draw conclusions from them.

Syntax

COUNT(expression)

1. Count all rows:

SELECT COUNT(*) FROM table_name;

2. Count distinct values in a column:

SELECT COUNT(DISTINCT column_name) FROM table_name;

Key Terms

 expression: This can be a column name, an asterisk (*), or a


condition.

 COUNT(*): Counts all rows.

 COUNT(DISTINCT column_name): Counts distinct values in the


specified column.

Examples of SQL Count Function

Now, let’s dive into practical examples of using the COUNT() function in
SQL. We will use a Customers table as our sample dataset, which contains
details about customers, including
their CustomerID, CustomerName, City, and Country.
Customers Table

1. Counting the Number of Rows with COUNT(*)

When we want to count all the rows in a table, regardless of the column
values, we can use COUNT(*). It counts every row, including rows with NULL
values.

Query:

SELECT COUNT(*)
FROM Customers;

Output

COUNT(
*)

Explanation:
 This query counts all the rows in the Customers table, including those
with NULL values in any column.

 The result 9 indicates that there are 9 rows in the Customers table.

2. Counting Unique Values with COUNT(DISTINCT …)

Sometimes, we may need to count only the distinct values in a column.


The COUNT(DISTINCT column_name) function allows us to count only
unique entries in a column, ignoring duplicates.

Query:

SELECT COUNT(DISTINCT Country) FROM Customers;

Output

COUNT(DISTINCT
Country)

Explanation:

 This query counts the number of unique countries in


the Customers table.

 The result 4 indicates that there are four distinct countries listed in the
table (Spain, Mexico, India, and Germany).

3. Count Rows That Match a Condition Using COUNT() with CASE


WHEN

We can use the COUNT() function along with CASE WHEN to count rows
that match a specific condition. This is helpful when we want to count rows
based on certain criteria without filtering the rows out of the result set.

Query:

SELECT COUNT(CASE WHEN Age > 30 THEN 1 ELSE NULL END) AS Adults
FROM Customers;
Output

Adul
ts

Explanation:

 This query counts the number of customers whose age is greater than
30.

 The CASE WHEN expression checks if the condition Age > 30 is met. If
it is, the value 1 is returned (otherwise, NULL is returned).

 The COUNT() function then counts the non-NULL values, giving us the
total number of customers over 30 years old.

 The result 5 shows that five customers are older than 30 years.

4. Count Rows in Groups Using COUNT() with GROUP BY

We can use the COUNT() function with GROUP BY to count rows within
groups based on a column. This is useful when we want to categorize data
and then count how many records exist in each category.

Query:

SELECT Country, COUNT(*) AS CustomerCount


FROM Customers
GROUP BY Country;

Output

CustomerCo
Country unt

Spain 4
CustomerCo
Country unt

Mexico 2

India 2

Germa
1
ny

Explanation:

 This query groups the rows in the Customers table by


the Country column and then counts how many customers belong to
each country.

 The result shows the number of customers from each country: 4 from
Spain, 2 from Mexico, 2 from India, and 1 from Germany

5. Filter Groups Using COUNT() with GROUP BY and HAVING

We can combine the COUNT() function with HAVING to filter the results
after grouping. The HAVING clause is used to specify conditions on groups,
similar to the WHERE clause, but for groups.

Query:

SELECT Country, COUNT(*) AS CustomerCount


FROM Customers
GROUP BY Country
HAVING COUNT(*) > 2;

Output
Count CustomerCo
ry unt

Spain 4

Explanation:

 This query counts the number of customers from each country and
filters out countries with fewer than 3 customers.

 The result only includes Spain, as it is the only country with more than
2 customers.

Best Practices for Using the COUNT() Function

The COUNT() function is a powerful and versatile tool in SQL, but like any
tool, it works best when used correctly. To ensure our queries are efficient
and maintainable, it's important to follow a few best practices. Below are
some key tips to get the most out of the COUNT() function in SQL:

1. Use COUNT(*) for Complete Row Counts:

When we need to count every row in a table, including rows


with NULL values, use COUNT(*). This counts all rows, regardless of the
data in them

Example:

SELECT COUNT(*)
FROM Customers;

Explanation:

This query will count all rows in the Customers table, even if some of those
rows have NULL values in their columns. COUNT(*) is the best choice when
we're looking for the total number of records in a table.

2. Use COUNT(DISTINCT column_name) to Count Unique Values:

If we only need to count the number of unique (distinct) values in a specific


column, use COUNT(DISTINCT column_name). This is useful when we
want to know how many different values exist in a column, like counting
distinct countries, cities, or customer types.
Example:

SELECT COUNT(DISTINCT Country)


FROM Customers;

Explanation:

This query counts how many unique countries are listed in


the Customers table, excluding any duplicates.
Using COUNT(DISTINCT) ensures that only distinct values are counted,
which is helpful for analyzing unique data points.

3. Optimize Queries for Large Datasets:

When we're working with large datasets, COUNT() can become slow if the
query scans the entire table. To improve performance, ensure that the
columns you're querying are properly indexed. Indexing can significantly
speed up the counting process by allowing the database to quickly locate
and retrieve the necessary data.

Example:

If we frequently count values in the Country column, consider adding an


index to the Country column:

CREATE INDEX idx_country


ON Customers(Country);

Explanation:

By creating an index on the Country column, you reduce the time the
database takes to count the rows matching certain conditions, especially on
large tables with millions of rows

4. Avoid Complex COUNT Queries for Large Tables:

When dealing with very large tables, complex COUNT() queries involving
multiple conditions or subqueries can take a long time to execute. It's often
better to break the query down into smaller, more manageable parts.
This reduces the load on the database and can help improve
performance.

Example:

SELECT COUNT(*)
FROM Customers
WHERE (Country = 'Spain' OR Country = 'France')
AND Age > 30
AND City = 'Barcelona';

Explanation:

By breaking the query into smaller parts, the database only needs to process
smaller datasets at a time, reducing the overall processing time.

Conclusion

The COUNT() function is an essential tool in SQL for aggregating data. It


allows us to count rows, count unique values, and filter based on specific
conditions. Whether we’re working with COUNT() in a SELECT statement or
using it with GROUP BY or HAVING to aggregate data, this function is crucial
for data analysis and reporting. By following best practices like indexing
and breaking down complex queries, we can optimize our COUNT() function
usage to ensure high performance and accurate results.

SQL SUM() Function

The SUM() function in SQL is one of the most commonly used aggregate
functions. It allows us to calculate the total sum of a numeric column,
making it essential for reporting and data analysis tasks. Whether we're
working with sales data, financial figures, or any other numeric
information, the SUM() function can help us quickly compute the sum of
values based on specific conditions.

In this article, we will explain the SUM() function in detail, provide multiple
examples, and highlight its use in various SQL queries to enhance our
understanding.

What is the SQL SUM() Function?

The SUM() function in SQL is used to calculate the total of a numeric


column or expression. This aggregate function sums the values in the
specified column and returns a single result. It is commonly used in
combination with other SQL clauses like WHERE, GROUP BY, and HAVING to
refine the data set and calculate sums based on specific conditions.

Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Key Terms

 column_name: The numeric column whose values you want to sum.

 table_name: The name of the table from which to retrieve the data.

 condition: (Optional) A condition to filter the rows before performing


the aggregation.

Examples of SQL SUM() Function

In this section, we will demonstrate the usage of the SUM() function with
examples using a sample table called Sales, which stores sales data such as
the Product, Quantity, and Price. This simple dataset will help us
understand how the SUM() function works in SQL to calculate totals, sums
of distinct values, and more.

Sales Table

Example 1: Using SUM() with One Column

In this example, we will use the SUM() function to calculate the total value
of a specific column, such as total sales or total salary.

Query:

SELECT SUM(Salary) AS TotalSalary


FROM Employees;

Output
TotalSal
ary

450,000

Explanation:

This query calculates the sum of the Salary column in the Employees table.
This output shows the total salary paid to employees in the database.

Example 2: Using SUM() with an Expression

We can also use the SUM() function with an expression to calculate sums
based on some logic or mathematical operations.

Query:

SELECT SUM(Price * Quantity) AS TotalRevenue


FROM Sales;

Output

TotalReve
nue

1,200,000

Explanation:

This query multiplies Price and Quantity for each record in the Sales table
and then calculates the sum of those values. This is useful for calculating the
total revenue generated from sales.

Example 3: Using SUM() with GROUP BY

When we want to calculate the sum of values within groups, we can use
the GROUP BY clause along with SUM(). This is particularly useful for
grouping data by categories such as departments, products, or cities.

Query:
SELECT Department, SUM(Salary) AS DepartmentSalary
FROM Employees
GROUP BY Department;

Output

Departm DepartmentSa
ent lary

HR 200,000

Sales 300,000

IT 250,000

Explanation:

This query groups employees by their Department and then calculates the
total salary for each department.

Example 4: Using SUM() with DISTINCT

If we want to sum only the distinct values in a column, we can use


the DISTINCT keyword with the SUM() function.

Query:

SELECT SUM(DISTINCT Price) AS TotalDistinctPrice


FROM Products;

Output:
TotalDistinctP
rice

500,000

Explanation:

This query sums only the unique values in the Price column of
the Products table. Duplicate values are excluded from the sum.

Example 5: Using SUM() with HAVING

The HAVING clause can be used in combination with GROUP BY to filter


groups based on the result of the SUM() function. This allows you to apply
conditions to the grouped data after the aggregation.

Query:

SELECT Department, SUM(Salary) AS DepartmentSalary


FROM Employees
GROUP BY Department
HAVING SUM(Salary) > 200,000;

Output

Departm DepartmentSa
ent lary

Sales 300,000

IT 250,000

Explanation:
This query calculates the total salary per department and then filters the
result to include only those departments where the total salary is greater
than 200,000.

Best Practices for Using the SQL SUM() Function

 Use with Indexes: When summing a large dataset, it’s important to


have indexes on the columns you’re filtering by, such as dates or
categories. This will improve the performance of your query.

 Use GROUP BY to Categorize Data: The SUM() function works


perfectly with GROUP BY. It helps you summarize data efficiently by
different categories like departments or regions.

 Avoid Summing Non-Numeric Values: Ensure that the column you


are summing contains only numeric values. Summing non-numeric
values can result in errors.

 Consider Using Aliases: Always use aliases for SUM() results for
better readability and clarity in your output.

Conclusion

The SQL SUM() function is a powerful tool for aggregating numeric data.
Whether we need to calculate the total salary, revenue, or count items,
the SUM() function simplifies these tasks and helps us derive valuable
insights from our database. By using it with different clauses
like DISTINCT, GROUP BY, and HAVING, we can tailor our queries to
specific conditions, making our analysis more efficient. The SUM() function is
especially useful for generating summary reports and
analyzing financial, sales, or inventory data.

SQL MIN() Function

The MIN() function in SQL is a powerful tool that allows us to determine the
smallest or lowest value from a specified column or expression. It is widely
used in data analysis to extract minimum values for decision-making,
reporting, and business insights. This function automatically
excludes NULL values during its computation, ensuring accurate results.

The MIN() function in SQL is a built-in aggregate function that returns the
smallest value from a specified column or dataset. It is commonly used in
queries to identify the minimum numeric, date, or string value within a
table. The function automatically skips NULL values, ensuring precise results.

We can use it with various clauses like WHERE, GROUP BY, HAVING, or in
subqueries to refine its output. The MIN() function is flexible and supports
multiple use cases, from finding the lowest invoice amount to filtering
groups based on conditions. It is a fundamental tool for data analysis and
reporting in SQL.

Syntax:

SELECT MIN(column_name)
FROM table_name
[WHERE condition];

Key Terms:

 MIN(): Returns the smallest value in the column.

 NULL values: Ignored by the MIN() function during computation.

 Aggregate functions: Functions like MAX(), AVG(), and SUM() that


perform operations on a set of values.

Examples of SQL MIN() Function

In this section, we will demonstrate the usage of the MIN() function with
examples using a two sample tables. Employee Table, which stores details
about employees, including their ID, name, city, designation, and
associated PersonID. The Sales table records the month, price, product,
and the corresponding employee responsible for the sale.

Employee Table:

Empl
oyee Table

Sales Table:
Sales Table

Example 1: Find the Lowest Invoice Amount in a Month

To determine the smallest invoice price processed in a specific month.


This query is particularly useful when analyzing monthly trends or
identifying the least expensive transaction in a given period.

Query:

SELECT MIN(price) AS [Lowest Invoice]


FROM Sales
WHERE InvoiceMonth = 'July';

Output:

Lowest
Invoice

$299

Explanation: The output displays the lowest price from the Sales table for
invoices processed in July. The MIN(price) function evaluates all price
entries within the filtered rows and returns the smallest value, which is $299.

Example 2: Find the Lowest Invoice in Specific Months

The IN clause allows for filtering data across multiple specified values,
making it convenient to analyze trends or minimum values across a range
of categories or time periods.

Query:
SELECT MIN(price) AS [Lowest Invoice]
FROM Sales
WHERE InvoiceMonth IN ('June', 'July');

Output

Lowest
Invoice

$99

Explanation: The output shows the lowest invoice price from


the Sales table for the months of June and July. The MIN(price) function
evaluates all price entries for these months and identifies $99 as the
smallest value, ensuring NULL values are excluded during the computation.

Using SQL MIN() Function with GROUP BY

The GROUP BY clause in SQL is used to organize rows into groups based
on one or more columns. When combined with the MIN() function, it
calculates the smallest value for each group. This is especially helpful when
analyzing grouped data, such as finding the lowest transaction amounts
for different categories, time periods, or regions.

Example 1: Minimum Invoice per Month

The GROUP BY clause is useful when we need to aggregate data into


meaningful groups, such as months, categories, or regions, and perform
calculations like finding the minimum value within each group.

Query:

SELECT InvoiceMonth, MIN(price) AS [Lowest Invoice]


FROM Sales
GROUP BY InvoiceMonth;

Output:
InvoiceMo Lowest
nth Invoice

June $99

July $299

Explanation: The output displays the lowest invoice price for each month
in the Sales table. The GROUP BY InvoiceMonth clause organizes the data
by month, and the MIN(price) function calculates the smallest value for
each group, resulting in $99 for June and $299 for July. This provides a clear
comparison of minimum prices across months.

Example 2: Filtered Grouping

This query demonstrates how filtering and grouping can be combined to


extract targeted insights. By using the WHERE clause, you limit the dataset
to specific months, and the GROUP BY clause allows analysis within
those filtered groups.

Query:

SELECT InvoiceMonth, MIN(price) AS [Lowest Invoice]


FROM Sales
WHERE InvoiceMonth IN ('June', 'July')
GROUP BY InvoiceMonth;

Output:

InvoiceMo Lowest
nth Invoice

June $99

July $299
Explanation: The output provides the lowest invoice prices for June and July.
The WHERE clause filters the data to include only the specified months,
while the GROUP BY InvoiceMonth organizes the data into separate
groups for June and July. The MIN(price) function then computes
the smallest price within each group, returning $99 for June and $299 for
July

Using SQL MIN() with ORDER BY

The ORDER BY clause is used to sort query results


in ascending or descending order. When paired with the MIN() function,
it helps prioritize groups based on their smallest values, making the output
more organized and easier to interpret.

Example 1: Sort by Minimum Invoice Amount

To sort groups by their minimum invoice price in ascending order, the query
uses the combination of GROUP BY and ORDER BY clauses:

Query:

SELECT InvoiceMonth, MIN(price) AS [Lowest Invoice]


FROM Sales
GROUP BY InvoiceMonth
ORDER BY MIN(price);

Output:

InvoiceMo Lowest
nth Invoice

June $99

July $299
InvoiceMo Lowest
nth Invoice

Explanation: The query groups the data by InvoiceMonth and calculates


the lowest invoice price for each group using the MIN(price) function.
The ORDER BY MIN(price) clause ensures that the results are displayed
in ascending order of the minimum invoice amounts. As a result, June, with
the lowest value of $99, appears before July, which has a minimum
value of $299.

Using SQL MIN() with HAVING Clause

The HAVING clause is used to filter grouped data based on aggregate


conditions. Unlike WHERE, which filters rows before
grouping, HAVING applies conditions after the groups are formed. This
method is effective for pinpointing groups that meet specific aggregate
conditions.

Example 1: Minimum Invoice Greater Than $150

This query filters groups where the smallest invoice price exceeds $150.

Query:

SELECT InvoiceMonth, MIN(price) AS [Lowest Invoice]


FROM Sales
GROUP BY InvoiceMonth
HAVING MIN(price) > 150;

Output:
InvoiceMo Lowest
nth Invoice

July $299

Explanation:

The GROUP BY clause groups data by InvoiceMonth, and


the MIN(price) function calculates the smallest invoice price for each group.
The HAVING clause filters out groups where the minimum price is $150 or
less, leaving only July, where the lowest invoice is $299.

Example 7: Minimum Invoice Less Than $150

This query filters groups where the smallest invoice price is below $150.

Query:

SELECT InvoiceMonth, MIN(price) AS [Lowest Invoice]


FROM Sales
GROUP BY InvoiceMonth
HAVING MIN(price) < 150;

Output:

InvoiceMo Lowest
nth Invoice

June $99

Explanation:

The GROUP BY clause groups data by InvoiceMonth, and


the MIN(price) function computes the smallest invoice price for each
group. The HAVING clause filters out groups where the minimum price
is $150 or higher, leaving only June, where the lowest invoice is $99.
Combining MIN() with Other Aggregate Functions

The MIN() function can be combined with other aggregate functions such
as MAX(), AVG(), and SUM() to generate a more comprehensive view of
your data. This approach helps in summarizing key metrics in a single
query.

Example 8: Aggregate Analysis

This query calculates the lowest, highest, average, and total invoice amounts
for each month.

Query:

SELECT InvoiceMonth,
MIN(price) AS [Lowest Invoice],
MAX(price) AS [Highest Invoice],
AVG(price) AS [Average Invoice],
SUM(price) AS [Total Invoice]
FROM Sales
GROUP BY InvoiceMonth;

Output:

InvoiceMo Lowest Highest Average Total


nth Invoice Invoice Invoice Invoice

June $99 $500 $299.5 $899

July $299 $299 $299.0 $299

Explanation:

This query calculates multiple aggregate values for each month by


grouping data with the GROUP BY clause. The MIN(price) retrieves the
lowest invoice amount, MAX(price) provides the
highest, AVG(price) calculates the average, and SUM(price) totals all invoice
prices for each month. .

Using SQL MIN() IN Subqueries


Subqueries can be used with the MIN() function to fetch detailed information
about the record that has the smallest value in a column. This technique is
useful for isolating specific rows based on aggregate results.

Example 9: Fetch Record with Minimum Price

This query retrieves the complete record associated with the lowest invoice
price.

Query:

SELECT *
FROM Sales
WHERE price = (SELECT MIN(price) FROM Sales);

Output:

InvoiceMo Pric Produ Person


nth e ct ID

June $99 Laptop 101

Explanation:

The subquery (SELECT MIN(price) FROM Sales) identifies the smallest


price, $99, in the Sales table. The main query retrieves the complete record
matching this price, providing detailed insights into the transaction with the
lowest invoice amount.

Using SQL MIN() Within the WHERE Clause

The MIN() function can be directly used within the WHERE clause to filter
rows based on the smallest value in a column. This approach allows precise
targeting of records that match specific criteria.

Example 10: Details of Invoice with Minimum Price

This query retrieves detailed information about the invoice associated with
the lowest price.

Query:

SELECT e.Name, e.City, e.Designation, s.InvoiceMonth, s.Price, s.Product


FROM Sales AS s
JOIN Employee AS e
ON e.ID = s.PersonID
WHERE s.Price = (SELECT MIN(price) FROM Sales);

Output:

Nam Designati InvoiceMo Pric Produ


e City on nth e ct

Alic New
Manager June $99 Laptop
e York

Explanation:

The query joins the Employee and Sales tables to fetch detailed information
about the invoice with the minimum price.

Conclusion

The SQL MIN() function is an essential aggregate function that simplifies


data analysis by identifying the smallest value in a dataset. It can be used
independently or combined with clauses like GROUP BY, ORDER
BY, and HAVING to solve complex business requirements. From basic
queries to advanced scenarios involving multiple aggregate functions,
the MIN() function is a versatile tool in SQL. Use the examples and tips in
this guide to apply the MIN() function effectively in our SQL projects.

SQL MAX() Function

The MAX() function in SQL is a powerful aggregate function used to


retrieve the maximum (highest) value from a specified column in a table. It
is commonly employed for analyzing data to identify the largest numeric
value, the latest date, or other maximum values in various datasets.
The MAX() function automatically excludes NULL values from its
computation, ensuring accuracy.

In this article, we will cover the syntax, use cases, sample tables, and
practical examples with detailed explanations of how to use
the MAX() function effectively. Whether we are a beginner or an advanced
SQL user, this guide will help us understand and apply
the MAX() function confidently.

Syntax:

SELECT MAX(column_name)
FROM table_name
[WHERE condition];

Key Terms:

 column_name: The column for which you want to find the maximum
value.

 table_name: The table containing the data.

 condition (optional): Filters rows before calculating the maximum


value.

Examples of SQL MAX() Function

In this section, we will demonstrate the usage of the MAX() function with
examples using a two sample tables. Product Prices table
contains product IDs and their corresponding prices.
The Sales table contains sales data with sale IDs, product IDs, sale dates,
and amounts.

Product Prices Table


Prod
uct Prices Table

Sales Table

Sales Table

Example 1: Find the Maximum Price in a Table

To find the highest price in the product_prices table. This query is simple
yet effective for identifying the most expensive product in the dataset. It
excludes NULL values, ensuring only valid prices are considered.

Query:

SELECT MAX(price) AS [Highest Price]


FROM product_prices;

Output

Highest
Price

199.99
Explanation: The MAX(price) function evaluates all the values in
the price column and returns the largest value, $199.99.

Example 2: Find the Maximum Sale Amount

To determine the highest sale amount from the Sales table. This query is
commonly used in sales data analysis to find the most significant
transaction in terms of value. It helps businesses track their peak sales
performances.

Query:

SELECT MAX(amount) AS [Highest Sale]


FROM Sales;

Output:

Highest
Sale

1500.00

Explanation: The MAX(amount) function scans the amount column in


the Sales table and identifies the largest sale, which is $1500.00

Example 3: Use MAX() with a Condition

Find the maximum price for products under a specific category, e.g.,
Electronics: This query is valuable for targeted analysis such as identifying
the product with highest price within a specific category.

Query:

SELECT MAX(price) AS [Highest Price in Electronics]


FROM product_prices
WHERE category = 'Electronics';

Output:

Highest Price in
Electronics

149.95
Highest Price in
Electronics

Explanation: The WHERE clause filters rows to include only products in the
'Electronics' category. The MAX(price) function then calculates the maximum
price within this subset.

Example 4: Find the Latest Sale Date

To find the most recent sale date in the Sales table. This query is
particularly useful for tracking the last activity in a dataset, such as
identifying the latest transaction or update.

Query:

SELECT MAX(sale_date) AS [Latest Sale Date]


FROM Sales;

Output:

Latest Sale
Date

2023-02-01

Explanation: The MAX(sale_date) function evaluates all dates in


the sale_date column and returns the most recent one, 2023-02-01

Example 5: Using MAX() with GROUP BY

Find the highest sale amount for each product. This query is helpful for
analyzing performance metrics at the product level, allowing businesses to
track the best-performing products.

Query:

SELECT product_id, MAX(amount) AS [Highest Sale]


FROM Sales
GROUP BY product_id;
product_ Highest
id Sale

1 500.00

2 1500.00

3 300.00

Explanation: The GROUP BY clause groups rows by product_id, and


the MAX(amount) function calculates the highest sale amount for each
group.

Example 6: Using MAX() in Subqueries

Retrieve details of the product with the highest price. The main query
retrieves the full record associated with this maximum price, providing
detailed information about the most expensive product.

Query:

SELECT *
FROM product_prices
WHERE price = (SELECT MAX(price) FROM product_prices);

Output:

product_
id price

199.9
4
9

Explanation: The subquery (SELECT MAX(price) FROM


product_prices) determines the highest price ($199.99). The main query
fetches all records matching this price.

Conclusion
The MAX() function in SQL is a fundamental tool for data
analysis, enabling users to find the highest value in a column. It can be
used independently or in combination with other SQL clauses
like WHERE, GROUP BY, and subqueries to handle complex data
requirements. By mastering the MAX() function, WE can efficiently analyze
and summarize data in various scenarios, such as identifying maximum
prices, latest dates, or highest scores.

AVG() Function in SQL

SQL is an RDBMS system in which SQL functions become very essential to


provide us with primary data insights. One of the most important functions is
called AVG() and is particularly useful for the calculation of averages
within datasets.

In this, we will learn about the AVG() function, and its syntax by
understanding various examples and their output with explanation and so
on.

AVG() Function in SQL

The SQL function AVG() is designed for calculating the average value of any
numeric column within a certain data set. It does this by adding up all the
values of the column and then dividing the resulting number by the number
of non-null values of the column.

Thus, the function is best suited to propose a typical value of a given data
set which helps to analyze the data-set features.

Syntax:

The syntax of the AVG() function is straightforward:

SELECT AVG(column_name)

FROM table_name;
Here, column_name represents the column from which you want to
compute the average, and table_name is the name of the table containing
the data. Optionally, you can use the WHERE clause to specify conditions for
filtering the data before calculating the average.

Set Up an Environment

CREATE TABLE student_scores (


student_id INT,
subject VARCHAR(50),
score INT
);

INSERT INTO student_scores (student_id, subject, score) VALUES


(1, 'Math', 85),
(2, 'Science', 78),
(3, 'English', 92),
(4, 'Math', 90),
(5, 'Science', 82),
(6, 'English', 88),
(7, 'Math', 75),
(8, 'Science', 80),
(9, 'English', 85);

Output:

| student_id | subject | score |


|------------|------------|-------|
|1 | Math | 85 |
|2 | Science | 78 |
|3 | English | 92 |
|4 | Math | 90 |
|5 | Science | 82 |
|6 | English | 88 |
|7 | Math | 75 |
|8 | Science | 80 |
|9 | English | 85 |

Example 1: Calculating Average Score per Subject

SELECT subject, AVG(score) AS average_score


FROM student_scores
GROUP BY subject;
Output:

| subject | average_score |
|------------|---------------|
| Math | 83.3333 |
| Science | 80 |
| English | 88.3333 |

Explanation: In this example, we're using the AVG() function to compute the
average score for each subject. The GROUP BY clause is used to group the
results by the subject column. The output will display two columns: subject
and average_score.

Example 2: Calculating Overall Average Score

SELECT AVG(score) AS overall_average_score


FROM student_scores;

Output:

| overall_average_score |
|-----------------------|
| 83.88888888888889 |

Explanation: Here, we're computing the average score across all subjects
using the AVG() function without any grouping. This will give us a single
value representing the overall average score of all students

Example 3: Calculating Average Score for a Specific Subject

SELECT AVG(score) AS average_science_score


FROM student_scores
WHERE subject = 'Science';

Output:

| average_science_score |
|-----------------------|
| 80 |

Explanation: In this example, we're filtering the data using


the WHERE clause to focus only on the "Science" subject. Then, we use the
AVG() function to calculate the average score for that specific subject

Considerations
While the AVG() function is a powerful tool for data analysis, there are some
considerations to keep in mind:

 Handling NULL Values: AVG () function by default


ignore NULL values when calculating the total. However, they have to
be careful in how they interpret the results of the study, especially
when missing values are relevant to your study.

 Data Type Compatibility: Make sure the function of AVG() is applied


to the column that contains numbers as the values. The usage of it
beyond numerical columns will result in erroneous results hence.

 Precision and Rounding: Since rounding is used in different cases,


you can either keep the result of the AVG() function as it is, or you
may round it to a specific number of decimal places so that the result
is clear and consistent

Conclusion

In SQL, the AVG() function is a good function for studying numerical data. It
enables analysts as well as data experts to carry out easy calculations and
thereby give a clear understanding regarding various vital factors in their
datasets. Whether you are deciding on sales figures, evaluating student
performance or monitoring website statistics AVG() gives you the statistics
with facts on which you can depend when making important decisions.

Chapter VIII
Data Constraints
Constraints act as rules or conditions imposed on the data, dictating what
values are permissible and what actions can be taken. They play a crucial
role in maintaining the quality and coherence of the database by preventing
errors.

 NOT NULL Constraints

 Primary Key Constraints

 Foreign Key Constraints

 Composite Key

 Unique Constraints

 Alternate Key

 CHECK Constraints

 DEFAULT Constraints

SQL NOT NULL Constraint

In SQL, NOT NULL constraint in SQL ensures a column must always contain a
value and cannot be left empty. Unlike a PRIMARY KEY, which uniquely
identifies each record and also disallows NULLs, NOT NULL only enforces the
presence of data without requiring uniqueness.

 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,

....

);

In the above syntax:

 CREATE TABLE table_name: creates a new table.

 column1 data_type(size): defines a column with its name, data


type, and size.

 NOT NULL: ensures the column cannot have NULL (empty) values.

 Repeat for other columns as needed.

SQL NOT NULL Constraint Syntax

The syntax for applying the NOT NULL constraint can be as follows:

1. During Table Creation:

CREATE TABLE table_Name (

column1 data_type(size) NOT NULL,

column2 data_type(size) NOT NULL,

...

);

2. Modifying an Existing Table:

You can also add a NOT NULL constraint to an existing column in a table
using the ALTER TABLE statement:

ALTER TABLE table_name

MODIFY column_name data_type(size) NOT NULL;

Example 1: Applying NOT NULL in Table Creation

Let’s look at an example where we create an EMPLOYEES table with a NOT


NULL constraint applied to the EmpID column to ensure that each employee
has a unique, non-null ID.
Query:

CREATE TABLE Emp (

EmpID INT NOT NULL PRIMARY KEY,

Name VARCHAR(50),

Country VARCHAR(50),

Age INT(2),

Salary INT(10)

);

In this table:

 EmpID is a mandatory field, ensuring no employee record can exist


without an ID.

Example 2: Adding NOT NULL to an Existing Table

If you have an existing table, you can add a NOT NULL constraint to a
column using the ALTER TABLE statement. Let’s assume the Emp table
already exists, and we now want to make the Name column non-nullable.

Query:

ALTER TABLE Emp

MODIFY Name VARCHAR(50) NOT NULL;

 Now, the Name column will not accept NULL values, meaning every
employee record must have a name.

Real-World Use Case of NOT NULL

Consider an Orders table in an e-commerce database. For each order, you


would likely have mandatory fields such
as OrderID, CustomerID, ProductID, and OrderDate. These fields should
never be NULL, as they represent essential information for tracking and
processing orders.

Example Orders Table:

CREATE TABLE Orders (

OrderID INT NOT NULL PRIMARY KEY,


CustomerID INT NOT NULL,

ProductID INT NOT NULL,

OrderDate DATE NOT NULL

);

This table ensures that:

 Every order has a unique OrderID.

 CustomerID, ProductID, and OrderDate must always be provided.

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint in SQL is one of the most important


constraints used to ensure data integrity in a database table. A primary
key uniquely identifies each record in a table, preventing duplicate or NULL
values in the specified column(s). Understanding how to properly implement
and use the primary key constraint is crucial for managing relational data
effectively.

PRIMARY KEY in SQL

PRIMARY KEY in SQL is a column (or group of columns) that uniquely


identifies the records in that table. A primary key must contain unique
values and can not have any NULL value.

There can only be one primary key in a table, but that primary key can
consist of one or more columns. When there are two or more columns in the
primary key it is called a composite key.

A primary key automatically has a UNIQUE constraint defined on it, and it


ensures that there are no duplicate or NULL values in that column.

SQL PRIMARY KEY Properties

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

SQL primary key syntax with CREATE TABLE statement is:

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
...,
CONSTRAINT pk_constraint_name PRIMARY KEY (column1, column2, ...)
);

SQL PRIMARY KEY with ALTER TABLE

SQL primary key syntax with ALTER TABLE statement is

ALTER TABLE table_name


ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);

SQL PRIMARY KEY Examples

Let's look at some examples of the PRIMARY KEY Constraint in SQL, and
understand it's working.
Create PRIMARY KEY in SQL Example

In this example, we will create primary key in a new table using CREATE
TABLE statement.

Query

CREATE TABLE Persons (

PersonID int NOT NULL PRIMARY KEY,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int

);

Verify SQL Primary key creation

To verify if the primary key has been successfully created, we will try adding
duplicate values in primary key column, and SQL should return an error.

Query

INSERT INTO Persons VALUES

(1,"Thakur", "Aditya", 22),

(1, "Kumar", "Shubham", 21);

Output

Error: UNIQUE constraint failed: Persons.PersonID

Add PRIMARY KEY to a Table Example

In this example, we will add primary key to a already existing table using
ALTER TABLE command.

Let's consider previous table, and create it without primary key this time.

CREATE TABLE Persons (

PersonID int,

LastName varchar(255) NOT NULL,


FirstName varchar(255), Age int);

This query will add primary key to 'Persons' table

ALTER TABLE Persons

ADD CONSTRAINT PK_Person PRIMARY KEY (PersonID);

Important Points About SQL PRIMARY KEY

 A primary key is a column or a set of columns in a table that uniquely


identifies each row.

 It ensures data integrity by preventing duplicate records and null


values.

 A primary key can be defined on a single column (simple primary key)


or multiple columns (composite primary key).

 Creating a primary key automatically creates a unique index on the


key column(s), improving query performance.

 Establishing relationships between tables using SQL primary key and


foreign key improve database design, reduce data redundancy, and
improve data consistency.

Benefits of Using Primary Keys

 Data Integrity: The primary key enforces data integrity by ensuring


each record is unique.

 Efficient Querying: Since a primary key automatically creates an


index, querying for records by the primary key is faster.

 Referential Integrity: Primary keys are used to establish


relationships between tables (via foreign keys), ensuring consistency
across related data.

Common Issues and Best Practices

 Avoid NULL values: Always ensure that the columns involved in the
primary key do not accept NULL values.

 Choose meaningful primary keys: If possible, choose a primary key


that naturally fits the data and serves as a meaningful identifier, like
an ID field.
 Composite Keys: Be cautious when using composite keys. While they
are useful in some scenarios, they can make queries more complex. If
possible, use a simple key or generate an artificial primary key (like an
ID).

 Changing Primary Keys: Once a primary key is established,


changing it can be difficult because of the interdependencies with
other tables (foreign key constraints). Always plan ahead when
designing your database schema.

Conclusion

The PRIMARY KEY constraint is a fundamental concept in relational databases


that ensures each record in a table is unique and identifiable. By using the
primary key effectively, you can maintain data integrity, improve query
performance, and establish meaningful relationships between tables.
Whether you are working with simple or composite keys, it is important to
understand the properties and best practices to ensure a well-designed and
efficient database structure.

SQL FOREIGN KEY Constraint

A FOREIGN KEY constraint is a fundamental concept in relational databases,


ensuring data integrity by enforcing relationships between tables. By linking
a child table to a parent table, the foreign key establishes referential
integrity. This constraint ensures that the values in the foreign key column
match the primary key values in the referenced table, thereby maintaining
consistent and valid data across the database.

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

Implementing Foreign Key

To implement foreign keys in a column of a table, follow the below mentioned


steps and make sure to have MYSQL workbench or MYSQL command line
client installed in your systems.

Step 1: To get started with foreign keys we need to create a new database
first and inside the database we will create two tables and link them. We use
the CREATE DATABASE command to create a new database.

Query:
CREATE DATABASE GEEKSFORGEEKS;

Step 2: Now we will Use or Select the database after creating it. We use the
USE command in order to select our database.

Query:

USE GEEKSFORGEEKS;

Selecting database

Step 3: As we have selected our database now we will create a table in our
database. To create a table we use CREATE TABLE command. As an example
we are creating a table Courses and Students and then we will link them with
foreign key. Then we will look at the structure of the tables also.

Query:

CREATE TABLE STUDENT(


STUDENT_ID INT PRIMARY KEY,
NAME VARCHAR(20),
ADDRESS VARCHAR(20),
AGE INT,
DOB DATE);

DESC STUDENTS;
Output:

Creating table Student

CREATE TABLE COURSES(


COURSE_NAME VARCHAR(20),
INSTRUCTOR VARCHAR(20),
REFERENCE_ID INT,
CONSTRAINT FK_REFER FOREIGN KEY (REFERENCE_ID)
REFERENCES STUDENT(STUDENT_ID));

DESC COURSES;

MS SQL : sp_helpdb table_name ;


Output:

Creating courses table

We have successfully implemented Foreign Key in our tables. We have


referenced the REFERENCE_ID column of table COURSES with
the STUDENT_ID column of the table STUDENT and as we have learnt that
Foreign Keys are used for referential integration of two columns.

SQL Foreign Key Constraint Example

In this example, we create a foreign key during the table creation.

Query:

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

INSERT INTO Customers (CustomerID, CustomerName)


VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob');

INSERT INTO Orders (OrderID, OrderNumber, CustomerID)


VALUES (1, 101, 1), (2, 102, 2), (3, 103, 3);

The following query will create the 'customers' and 'orders' table.

CustomerID CustomerNa
(Primary Key) me

1 John

2 Jane

3 Bob

OrderID (Primary OrderNum CustomerID


Key) ber (Foreign Key)

1 101 1

2 102 2

3 103 3

Example 1: Insert Value in Foreign Key Table

If a corresponding value in the foreign table doesn't exist, a record in the


child table cannot be inserted.
Query:

INSERT INTO Orders (OrderID, OrderNumber, CustomerID)


VALUES (4, 104, 4);

Output :

Error: FOREIGN KEY constraint failed.

Example 2: Delete a value in Foreign Key Table

When a record in the master table is deleted and the corresponding record in
the child table exists, an error message is displayed and prevents
the DELETE operation from going through.

Query:

DELETE FROM Customers


WHERE CustomerID = "3";

Output:

Error: FOREIGN KEY constraint failed

Important Points About SQL FOREIGN KEY Constraint

 A FOREIGN KEY is a field (or collection of fields) in one table, that


refers to the PRIMARY KEY in another table.

 The table containing the foreign key is called the child table, and the
table containing the candidate key is called the referenced or parent
table.

 A table can have multiple FOREIGN KEY constraints.

 When defining a FOREIGN KEY constraint, you can specify what


happens when a referenced row in the parent table is deleted or
updated. This is done using the ON DELETE and ON UPDATE clauses
followed by the CASCADE, SET NULL, or NO ACTION option.

 The FOREIGN KEY constraint in SQL is used to maintain the referential


integrity of data within the database.
Conclusion

The FOREIGN KEY constraint is an essential tool for ensuring referential


integrity between related tables in a relational database. By enforcing
relationships between tables, it ensures that data is consistent and that
invalid or orphaned records cannot be inserted or maintained in the child
table.

By using foreign keys, you create a more robust and reliable database
structure that ensures the integrity of the relationships between different
entities in your database. Whether you're designing tables from scratch or
adding foreign keys to an existing schema, understanding how to use foreign
keys properly will help you manage your data more effectively and prevent
common data-related errors.

Composite Key in SQL

A composite key is a primary key that is made up of more than one column
to uniquely identify records in a table. Unlike a single-column primary key,
a composite key combines two or more columns to ensure uniqueness. While
any of the individual columns in a composite key might not be unique on
their own, together they form a unique combination that can uniquely
identify each row in the table.

Key Points to Remember:

 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.

Composite Key Example

Creating a database:

CREATE School;

Using database:
USE School;

Creating a table with a composite key:

CREATE TABLE student

(rollNumber INT,

name VARCHAR(30),

class VARCHAR(30),

section VARCHAR(1),

mobile VARCHAR(10),

PRIMARY KEY (rollNumber, mobile));

In this example, we have made the composite key as the combination of two
columns i.e. rollNumber and mobile because all the rows of the table student
can be uniquely identified by this composite key.

Inserting records in the table:

INSERT INTO student (rollNumber, name, class, section, mobile)

VALUES (1, "AMAN","FOURTH", "B", "9988774455");

INSERT INTO student (rollNumber, name, class, section, mobile)

VALUES (2, "JOHN","FIRST", "A", "9988112233");

INSERT INTO student (rollNumber, name, class, section, mobile)

VALUES (3, "TOM","FOURTH", "B", "9988777755");

INSERT INTO student (rollNumber, name, class, section, mobile)

VALUES (4, "RICHARD","SECOND", "C", "9955663322");

Querying the records:

SELECT * FROM student;

OUTPUT:
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.

Conclusion

A composite key is a powerful tool in SQL, allowing you to create unique


constraints across multiple columns. This can be especially helpful in
situations where individual columns do not provide sufficient uniqueness. By
combining multiple attributes into one primary key, you can ensure that each
row in a table is uniquely identifiable.

This key is typically used when there's a natural relationship between the
columns, and it’s often employed in cases where the table contains many-to-
many relationships, requiring the combination of columns to uniquely identify
records.

SQL | UNIQUE Constraint

The UNIQUE constraint in SQL ensures that values in a column or set of


columns are distinct, preventing duplicates. Unlike a PRIMARY KEY, it allows
multiple NULL values since each NULL is treated as unique, while a primary
key requires all values to be unique and non-NULL.
Features of UNIQUE Constraint

 Prevents Duplicates: Ensures column(s) have unique values.

 Allows NULLs: Multiple NULLs are permitted.

 Single or Multiple Columns: Can apply to one or more columns.

 Index Not Required: Does not automatically create an index (though


many databases do for performance).

 Modifiable: Can be added or removed using ALTER TABLE.

Syntax:

CREATE TABLE table_name (

column1 datatype UNIQUE,

column2 datatype,

...

);

In the above syntax:

 CREATE TABLE table_name: creates a new table.

 column1 datatype UNIQUE: defines a column with a data type and


enforces unique values.

 column2 datatype: defines another column without the unique


constraint.

 Repeat for additional columns as needed.

Example of Using the SQL UNIQUE Constraint

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)

);

In this case, each customer must have a unique email address. If you try to
insert a duplicate email, SQL will raise an error.

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (1, 'John Doe', '[email protected]', 'USA');

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (2, 'Jane Smith', '[email protected]', 'Canada');

-- This will fail because '[email protected]' already exists

INSERT INTO Customers (CustomerID, Name, Email, Country)

VALUES (3, 'Alice Johnson', '[email protected]', 'UK');

The third insert will fail because the Email [email protected] already
exists in the Customers table.

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)

);
In this example, the combination of CustomerID and ProductID must be
unique, meaning a customer cannot order the same product more than once.

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

);

In this example, we check if there are any duplicate OrderID values for each
customer in the Orders table. If the subquery returns unique values, the
CustomerID will be selected.

Important Points

 Evaluates to true on an empty subquery.

 Returns true only if there are unique tuples present as the output of
the sub-query (two tuples are unique if the value of any attribute of the
two tuples differs).

 Returns true if the sub-query has two duplicate rows with at least one
attribute as NULL.

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.
In other words, we can define the Alternate key as the set of Candidate Keys
other than the Primary Key. There can be many Candidate Keys for a given
table, and out of all these, the Database Administrator selects only one as
the Primary Key. Hence, the other Candidate Keys that are not used as a
Primary Key are the "Alternate Keys."

Some important points about Alternate Keys are as follows :

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.

Creating an Alternate Key in SQL

we are going to see how to create an ALTERNATE Key in SQL using sample
tables as shown.

Consider two tables, Product Information and Customer Information.


We will assume that we are creating a customer information system where
we want to keep track of customers' orders. In this case, we use the Product
ID as a Foreign Key in the Customer Information table to reference products
purchased by customers.

Product Information

Product Product Pric


ID Name e

Washing
1001 25
Soap

1020 Shampoo 150


Product Information

Product Product Pric


ID Name e

1030 Notebook 200

100
1045 Headphone
0

Customer Information

Custom
Custom er Email Shipping Pan Produ
er ID Name Address Address Number ct ID

XYZ-
Madhulik [email protected] XXABX100
1 Colony, 1030
a m 11
Patna

ABC-
[email protected] DDABX100
2 Tanmoy Colony, 1001
m 34
Guwahati

XYZ_Street ACQBX105
3 Ritik [email protected] 1045
, Chennai 55

[email protected] Park_Stree ZZABX200


4 Satadru 1045
om t, Kolkata 35
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 }

Say, the Data Base Administrator of this E-Commerce site picked Customer
ID as the Primary Key. Therefore, PAN Number and E-Mail Address will be
Alternate Keys or Secondary Keys. Alternate Key has all the properties to
become a Primary Key and so is an alternate option.

ALTERNATE Keys in SQL are defined using the SQL constraint UNIQUE.

UNIQUE(col_name(s))

col_name(s): The name of the column(s) in the table which need to be


unique.

BASIC SQL QUERY :

1. Creating a Database

CREATE DATABASE database_name

2. Creating a Table

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

3. Inserting into a Table

INSERT INTO Table_name

VALUES(val_1, val_2, val_3, ..........)

val: Values in particular column

4. View The Table

SELECT * FROM Table_name

Output :
Pro
duct Table

Customer Table

A pictorial view of all the keys present in the table is shown below :
KEYS

Key Differences Between Primary Key and Alternate Key

Feature Primary Key Alternate Key

Uniqueness Must be unique Must be unique

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

Conclusion
Alternate Keys are an essential feature in SQL that helps maintain data
uniqueness and integrity. While the Primary Key is the most important key
used to uniquely identify rows in a table, Alternate Keys provide additional
options for uniqueness constraints and can be used to enforce data integrity
across multiple columns. Understanding how to use and define alternate
keys can significantly improve database design, particularly in systems
where multiple attributes could serve as a unique identifier for records.

SQL | CHECK Constraint

The CHECK constraint in SQL enforces rules on column values by limiting the
data that can be inserted or updated. It ensures that values meet specified
conditions. If a value violates the condition, the operation is
rejected. CHECK can be added during table creation or modification.

Syntax of the CHECK Constraint

The CHECK constraint can be defined when creating a table or added later
using the ALTER statement.

1. Using CHECK with CREATE TABLE:

CREATE TABLE table_name (


column1 datatype,
column2 datatype CHECK (condition),
...
);

2. Using CHECK with ALTER TABLE (to add a condition after table
creation):

ALTER TABLE table_name


ADD CONSTRAINT constraint_name 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.

Examples of Using the CHECK Constraint

Let’s look at some practical examples to better understand how the CHECK
constraint works in SQL.

Example 1: Applying CHECK on a Single Column

In this example, we create a Customers table with a Age column that must
contain values between 18 and 120. The CHECK constraint ensures that no
invalid age is inserted into the table.

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

The Age column has a CHECK constraint that ensures the value must be
between 18 and 120. If you attempt to insert an age outside this range, the
database will throw an error.

Example 2: CHECK Constraint with Multiple Columns

We can also use the CHECK constraint across multiple columns. For instance,
let's say we have an Employee table, and we want to ensure that the
Salary is positive and the Age is greater than or equal to 18.
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

The CHECK constraint ensures that both conditions are satisfied. the
employee must be at least 18 years old, and the salary must be greater than
0. This kind of constraint is useful when multiple columns are involved in the
rule.

Example 3: Adding a CHECK Constraint with ALTER TABLE

We can add a CHECK constraint to an existing table using the ALTER


TABLE statement.

Query:

ALTER TABLE Employee


ADD CONSTRAINT chk_salary CHECK (Salary >= 30000);

This adds a CHECK constraint named chk_salary to the Employee table,


ensuring that the Salary column has a minimum value of 30,000. If you
attempt to insert or update a record with a salary lower than 30,000, the
operation will fail.

SQL | DEFAULT Constraint

In SQL, 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.

Features of SQL DEFAULT Constraint

 Automatic Value: Inserts a predefined value if none is provided.

 Simplifies Data Entry: Useful for commonly repeated values.

 Optional: Not required for every column.

 Any Data Type: Can be applied to numbers, dates, strings, etc.

 Cannot Default to NULL: NULL must be specified explicitly.

Syntax :

CREATE TABLE table_name (

column1 datatype DEFAULT default_value,

column2 datatype DEFAULT default_value,

...

);

In the above syntax:

 CREATE VIEW view_name: Defines a new view.

 AS : Indicates the SELECT query that defines the view.


 SELECT … : Specifies columns or expressions to include.

 FROM table_name: Selects the source table(s).

 WHERE … : Optional filter to include specific rows

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

Output:
I Nam Ag Locati
D e e on

4 Mira 23 Delhi

Hem
27 Noida
5 a

6 Neha 25 Delhi

Khus
26 Noida
7 hi

In this query:

 Table Creation: Geeks table has columns ID (NOT NULL), Name, Age,
and Location with a default value 'Noida'.

 Inserts with Explicit Values: Rows for Mira and Neha provide all
column values explicitly.

 Inserts Using DEFAULT: Rows for Hema and Khushi use the default
'Noida' for Location when no value or DEFAULT keyword is used.

Dropping the DEFAULT Constraint

If you no longer want a column to use a default value, you can drop the
DEFAULT constraint. This will only apply to new rows and will not affect
existing data in the table.

Syntax:

ALTER TABLE tablename

ALTER COLUMN columnname

DROP DEFAULT;

Query:
ALTER TABLE Geeks

ALTER COLUMN Location

DROP DEFAULT;

Let us add 2 new rows in the Geeks table :

Query:

INSERT INTO Geeks VALUES (8, 'Komal', 24, 'Delhi');

INSERT INTO Geeks VALUES (9, 'Payal', 26,NULL);

Note - Dropping the default constraint will not affect the current data in the
table, it will only apply to new rows.

Select * from Geeks;

Output:

I Nam Ag Locati
D e e on

4 Mira 23 Delhi

Hem
27 Noida
5 a

6 Neha 25 Delhi

Khus
26 Noida
7 hi

Koma
24 Delhi
8 l

9 Payal 26 NULL
Chapter IX
SQL Joins

SQL joins serve as the weaver's tool, allowing you to seamlessly merge data
from multiple tables based on common threads. So explore this section to
learn how to use JOIN command.

 JOIN

 Outer Join

 Left Join

 Right Join

 Full Join

 Cross Join

 Self Join

 UPDATE with JOIN

 DELETE JOIN

 Recursive Join

SQL Joins (Inner, Left, Right and Full Join)

SQL joins are fundamental tools for combining data from multiple tables in
relational databases.

 For example, consider two tables where one table (say Student) has
student information with id as a key and other table (say Marks) has
information about marks of every student id. Now to display the marks
of every student with name, we need to join the two tables.

 Please remember, we store data into multiple tables as part


of database normalization to avoid anomalies and redundancies.

Types of SQL Joins

Let us visualize how each join type operates:

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.

Example of INNER JOIN

Consider the two tables, Student and StudentCourse, which share a common
column ROLL_NO. Using SQL JOINS, we can combine data from these tables
based on their relationship, allowing us to retrieve meaningful information
like student details along with their enrolled courses.
Student Table:

StudentCourse Table:
Let's look at the example of INNER JOIN clause, and understand it's
working. This query will show the names and age of students
enrolled in different courses.

Query:

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

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

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;

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

Output

COURSE_
NAME ID

HARSH 1

PRATIK 2

RIYANK
2
A

DEEP 3

SAPTAR
1
HI

DHANR
NULL
AJ

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5
COURSE_
NAME ID

NULL 4

5. SQL Natural Join

A Natural Join is a type of INNER JOIN that automatically joins two


tables based on columns with the same name and data type. It
returns only the rows where the values in the common columns
match.

 It returns rows where the values in these common columns are


the same in both tables.

 Common columns appear only once in the result, even if they


exist in both tables.

 Unlike a CROSS JOIN, which creates all possible combinations


of rows, a Natural Join only includes rows with matching values

Example:

Look at the two tables below: Employee and Department

Employee

Emp_i Emp_na Dept_


d me id

1 Ram 10

2 Jon 30

3 Bob 50
Employee

Department

Dept_ Dept_na
id me

10 IT

30 HR

40 TIS

Find all Employees and their respective departments.

(Employee) ? (Department)

Output:

Emp_i Emp_na Dept_ Dept_ Dept_na


d me id id me

1 Ram 10 10 IT

2 Jon 30 30 HR
SQL Outer Join

Last Updated : 27 Aug, 2025

Outer Joins allow retrieval of rows from two or more tables based on
a related column. Unlike Inner Joins, Outer Joins also include rows
that do not have a corresponding match in one or both of the tables.
This makes them especially useful when dealing with incomplete
data, ensuring that no records are missed during reporting or
analysis.

Types of Outer Joins

There are three main types of Outer Joins in SQL:

 LEFT OUTER JOIN (or LEFT JOIN)

 RIGHT OUTER JOIN (or RIGHT JOIN)

 FULL OUTER JOIN

Each of these join types handles unmatched rows differently and


understanding how they work will help you use them effectively in
your SQL queries.

Let's Consider the two tables, Employees and Departments for


understanding all types of Outer Joins with examples.

1. Employees Table

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
DepartmentID INT );

INSERT INTO Employees (EmployeeID, Name, DepartmentID) VALUES


(1, 'John', 101),
(2, 'Sarah', 102),
(3, 'Michael', NULL),
(4, 'Emma', 103);

Employee Departmen
ID Name tID

1 John 101

2 Sarah 102

Micha
3 NULL
el

4 Emma 103

2. Departments Table

CREATE TABLE Departments (


DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50));

INSERT INTO Departments (DepartmentID, DepartmentName)


VALUES
(101, 'HR'),
(102, 'IT'),
(103, 'Marketing')
(104, 'Finance');

Departmen DepartmentN
tID ame

101 HR

102 IT
Departmen DepartmentN
tID ame

103 Marketing

104 Finance

Now we’ll use these tables in our join queries.

1. LEFT OUTER JOIN (or LEFT JOIN)

LEFT OUTER JOIN (referred to as LEFT JOIN) returns all rows from the left
table and the matching rows from the right table. If there is no match, the
result will include NULL values for columns from the right table.

LEFT OUTER JOIN (or LEFT JOIN)

Syntax:

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Example: To retrieve all employees along with their respective departments,


even if they don't belong to any department (i.e., the department is NULL),
we can use the LEFT OUTER JOIN
Query:

SELECT Employees.Name, Employees.DepartmentID,


Departments.DepartmentName
FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

Output

Departmen DepartmentN
Name tID ame

John 101 HR

Sarah 102 IT

Micha
NULL NULL
el

Emma 103 Marketing

LEFT JOIN ensures Michael still appears in the result even though he has no
department. The DepartmentName is shown as NULL to indicate no match.

2. RIGHT OUTER JOIN (RIGHT JOIN)

RIGHT OUTER JOIN (often called RIGHT JOIN) returns all rows from the right
table and the matching rows from the left table. If there is no match, the
result will include NULL values for columns from the left table.
RIGHT
OUTER JOIN (RIGHT JOIN)

Syntax:

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Example: Let’s now look at a RIGHT OUTER JOIN on the Employees and
Departments tables. Suppose we want to retrieve all departments, even if no
employees belong to a specific department.

Query:

SELECT Employees.Name, Employees.DepartmentID,


Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

Output
Departmen DepartmentN
Name tID ame

John 101 HR

Sara
102 IT
h

Emm
103 Marketing
a

NULL NULL Finance

The Finance department (104) has no employees, so the employee fields


appear as NULL.

3. FULL OUTER JOIN

FULL OUTER JOIN returns all rows when there is a match in either the left or
right table. If there is no match, the result will include NULL for the missing
side of the table. Essentially, it combines the results of both LEFT JOIN and
RIGHT JOIN.
FULL OUTER JOIN

Syntax:

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Example: Let’s now use a FULL OUTER JOIN to get all employees and all
departments, regardless of whether an employee belongs to a department or
a department has employees.

Query:

SELECT Employees.Name, Employees.DepartmentID,


Departments.DepartmentName
FROM Employees
FULL JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;
Output

Departmen DepartmentN
Name tID ame

John 101 HR

Sarah 102 IT

Micha
NULL NULL
el

Emma 103 Marketing

NULL NULL Finance

Michael has no department (so DepartmentName is NULL) and Finance has


no employees (so Name and DepartmentID are NULL).

When to Use SQL Outer Joins?

Outer Joins are particularly useful when:

 One need to include all records from one or both tables, even if no
match exists.

 Handling incomplete or missing relationships, ensuring no important


records are lost.

 Creating comprehensive reports that must show all employees,


departments or entities.

 Merging datasets from different sources where some records may not
align perfectly.
Difference Between INNER JOIN and OUTER JOIN

INNER JOIN OUTER JOIN

Returns only records with Returns records even if there is no


matching values in both tables. match in one or both tables.

Includes non-matching rows (NULLs fill


Excludes non-matching rows.
missing values).

Produces a smaller, filtered Produces a larger, more


result set. comprehensive result set.

Three types: LEFT, RIGHT, FULL OUTER


Only one type: INNER JOIN.
JOIN.

Used when focusing strictly on Used when dealing with incomplete


relationships between tables. data or ensuring no records are lost.

Common in transactional Common in reporting, analytics and


queries. data integration tasks.
SQL LEFT JOIN

In SQL, the LEFT JOIN (also called LEFT OUTER JOIN) retrieves all records from
the left table and only the matching records from the right table. If no match
is found in the right table, the query will return NULL values for its columns.

 Returns all rows from the left table.

 Includes only matching rows from the right table.

 Non-matching rows in the right table are represented as NULL

SQL LEFT JOIN Venn Diagram

This VENN diagram shows how a LEFT JOIN works in SQL.

LEFT JOIN

Syntax:

SELECT column_name(s)

FROM tableA

LEFT JOIN tableB ON tableA.column_name = tableB.column_name;

Examples of SQL LEFT JOIN

Let's look at an example of LEFT JOIN in SQL to understand it better. Consider


two tables: Emp (employees) and department (departments). The Emp table
contains employee details, while the department table holds department
details.

Employee Table
CREATE TABLE Emp (

EmpID INT PRIMARY KEY,

Name VARCHAR(50),

Country VARCHAR(50),

Age INT,

Salary INT,

department_id INT

);

INSERT INTO Emp (EmpID, Name, Country, Age, Salary, department_id)

VALUES (1, 'Shubham', 'India', 23, 30000, 101),

(2, 'Aman', 'Australia', 21, 45000, 102),

(3, 'Naveen', 'Sri Lanka', 24, 40000, 103),

(4, 'Aditya', 'Austria', 21, 35000, 104),

(5, 'Nishant', 'Spain', 22, 25000, 101);

Output:

Employee Table

Department Table

CREATE TABLE department (

department_id INT PRIMARY KEY,

department_name VARCHAR(50),

department_head VARCHAR(50),
location VARCHAR(50)

);

INSERT INTO department (department_id, department_name,


department_head, location)

VALUES (101, 'Sales', 'Sarah', 'New York'),

(102, 'Marketing', 'Jay', 'London'),

(103, 'Finance', 'Lavish', 'San Francisco'),

(104, 'Engineering', 'Kabir', 'Bangalore');

SELECT * FROM department;

Output:

Department Table

Example 1: Performing a LEFT JOIN

To perform left-join on Employee and Department Tables we will use the


following SQL query:

Query:

SELECT Emp.EmpID, Emp.Name, department.

department_name, department.department_head,

department.location

FROM Emp

LEFT JOIN department ON Emp.department_id = department.department_id;


Output:

LEFT JOIN in SQL Example Output

Explanation:

 All employees (left table) are included.

 Since each employee is assigned a department, we see matching


details from the right table.

 If an employee had no department assigned, the department columns


would show NULL.

Example 2: SQL LEFT JOIN with WHERE Clause

In this example, we will add a WHERE clause that specifies to only return
results where the "location" column in the department table equals
'Bangalore'. This will filter the results to only show employees who belong to
a department located in Bangalore, and departments that have no
employees will not be returned in the results.

Query:

SELECT e.EmpID, e.Name, d.department_name, d.department_head,


d.location

FROM Emp e

LEFT JOIN department d ON e.department_id = d.department_id

WHERE d.location = 'Bangalore';

Output:

SQL LEFT JOIN with WHERE Clause Example


Explanation:

 Only employees working in departments located in Bangalore are


included.

 If no department matched Bangalore, the result would be empty.

Example 3: SQL LEFT JOIN as Aliases

In this query, we'll use aliases "e" for the Emp table and "d" for the
department table. The SELECT statement references these aliases for each
column, making the query easier to read and type. Aliases simplify code and
improve readability, especially with long or complex table names.

Query:

SELECT e.EmpID, e.Name, d.department_name,

d.department_head, d.location

FROM Emp e

LEFT JOIN department d ON

e.department_id = d.department_id;

Output:

SQL LEFT JOIN as Aliases Example Output

Explanation:

 e is used as an alias for Emp, and d is used for department.

 This improves query readability and makes referencing columns


simpler.
SQL RIGHT JOIN

In SQL, the RIGHT JOIN (also called RIGHT OUTER JOIN) is used to combine
rows from two tables based on a related column. It returns all records from
the right table and only the matching records from the left table. If there is
no match in the left table, the result will show NULL values for the left table’s
columns.

 Returns all rows from the right table.

 Includes only matching rows from the left table.

 Non-matching rows from the left table appear as NULL

RIGHT JOIN

Syntax:

SELECT column_name(s)

FROM tableA

RIGHT JOIN tableB

ON tableA.column_name = tableB.column_name;

Examples of SQL RIGHT JOIN


In this example, we will consider two tables employee table containing
details of the employees working in the particular department the and
department table containing the details of the department

Employee Table:

emp_ dept_
no emp_name no

E1 Varun Singhal D1

Amrita
E2 D2
Aggarwal

E3 Ravi Anand D3

Department Table:

dept_ d_nam
no e location

D1 IT Delhi

Hyderab
D2 HR
ad

D3 Finance Pune

D4 Testing Noida

Marketi
D5 Mathura
ng

Query:
SELECT emp_no , emp_name ,d_name, location

FROM employee

RIGHT JOIN dept

ON employee.dept_no = department.dept_no;

Output:

emp_n d_nam
o emp_name e location

E1 Varun Singhal IT Delhi

Amrita Hyderab
E2 HR
Aggarwal ad

E3 Ravi Anand Finance Pune

[NUL
[NULL] Testing Noida
L]

[NUL Marketi
[NULL] Mathura
L] ng

Explanation:

 The RIGHT JOIN ensures that all departments are listed.

 Since D4 (Testing) and D5 (Marketing) have no employees,


the emp_no and emp_name columns show NULL.

 Departments with employees show proper matches.

Applications of SQL RIGHT JOIN

 Merging Data: Combines related data from different tables.


 Ensuring Completeness: Guarantees all records from the right table are
included.

 Handling Missing Values: Identifies records without matches in the left


table.

 Analyzing Relationships: Helps detect data gaps and dependencies


across tables.

When Should You Use RIGHT JOIN?

1. Data Completeness: When you need to show all records from the right
table (e.g., all departments).

2. Analyzing Missing Data: To detect records in the right table without


matches in the left.

3. Reporting & Data Integrity: Ensures no records from the right table are
skipped.

4. Handling Optional Data: When some left-side records may not exist but
right-side ones must be shown.
SQL FULL JOIN

The FULL JOIN (or FULL OUTER JOIN) in SQL returns all rows from both tables,
combining matched rows and filling unmatched rows with NULL values. It is
basically the combination of LEFT JOIN and RIGHT JOIN

 Retrieves all rows from both tables.

 Matches rows where conditions meet.

 Fills NULLs where no match exists.

 Combines results of LEFT JOIN + RIGHT JOIN.

 Can be used sequentially for multiple tables.


Syntax:

SELECT columns

FROM table1

FULL JOIN table2

ON table1.column = table2.column;

Parameters:

 SELECT columns: Specifies the columns to retrieve.

 FROM table1: The first table to be joined.

 FULL JOIN table2: Specifies the second table to join with the first
table using a FULL JOIN.

 ON table1.column = table2.column: Defines the condition to match


rows between the two tables.

This query retrieves all records from both table1 and table2, returning NULL
where there are no matches.

Examples of SQL FULL JOIN


Let's look at some examples of the FULL JOIN in SQL and understand it's
working. First, let's create a demo database and two tables on which we will
perform the JOIN.

1. Books Table

This table Represents the list of books in the system

BOOK_I ISSUED_ DUE_DA


D BOOK_NAME ON TE

2023-01- 2023-01-
1 RD SHARMA
01 08

2023-02- 2023-02-
2 GATE CRACKER
02 09

2023-03- 2023-03-
3 MORRIS MANO
03 10

NK 2023-04- 2023-04-
4
PUBLICATIONS 04 11

BIG BANG 2023-05- 2023-05-


5
THEORY 05 12

2. Authors Table

This table represents the authors who have written the books.
AUTHOR_ AUTHOR_NA
ID ME

1 Ram Kumar

Shyam
2
Sunder

3 Sita Singh

4 Mohan Gupta

5 Raj Kapoor

3. Publishers Table

This table represents the authors who have published the books.

PUBLISHER PUBLISHER_NA
_ID ME

1 Pearson

2 Wiley

3 McGraw-Hill

4 Springer

5 Elsevier
PUBLISHER PUBLISHER_NA
_ID ME

Example 1: FULL JOIN on Multiple Tables

In this example, we perform a FULL JOIN across the Books, Authors,


and Publishers tables to combine all related records into a single result set.

Query:

SELECT

b.BOOK_ID,

b.BOOK_NAME,

a.AUTHOR_NAME,

p.PUBLISHER_NAME

FROM Books b

FULL JOIN Authors a ON b.BOOK_ID = a.AUTHOR_ID

FULL JOIN Publishers p ON b.BOOK_ID = p.PUBLISHER_ID;

Output:

BOOK_I AUTHOR_NA PUBLISHER_NA


D BOOK_NAME ME ME

1 RD SHARMA Ram Kumar Pearson

Shyam
2 GATE CRACKER Wiley
Sunder

3 MORRIS MANO Sita Singh McGraw-Hill


BOOK_I AUTHOR_NA PUBLISHER_NA
D BOOK_NAME ME ME

NK
4 Mohan Gupta Springer
PUBLICATIONS

BIG BANG
5 Raj Kapoor Elsevier
THEORY

Explanation:

 Books uses BOOK_ID.

 Authors uses AUTHOR_ID, which matches BOOK_ID.

 Publishers uses PUBLISHER_ID, also matching BOOK_ID.

 FULL JOIN ensures that all rows are included even if a match is missing.

Example 2: FULL JOIN with WHERE Clause

Now, we want to filter the results from the above join based on a specific
condition. We will select only books that have "Sharma" in the book name.

Query:

SELECT

b.BOOK_ID,

b.BOOK_NAME,

a.AUTHOR_NAME,

p.PUBLISHER_NAME

FROM Books b

FULL JOIN Authors a ON b.BOOK_ID = a.AUTHOR_ID

FULL JOIN Publishers p ON b.BOOK_ID = p.PUBLISHER_ID

WHERE b.BOOK_NAME LIKE '%Sharma%';


Output:

BOOK_I BOOK_NA AUTHOR_NA PUBLISHER_NA


D ME ME ME

RD
1 Ram Kumar Pearson
SHARMA

Explanation:

In this example, the WHERE clause filters out all books that do not contain
the word "Sharma" in their name. After applying the filter, only the record for
"RD SHARMA" remains.

SQL CROSS JOIN

Last Updated : 27 Aug, 2025

CROSS JOIN in SQL generates the Cartesian product of two tables, meaning
each row from the first table is paired with every row from the second. This is
useful when you want all possible combinations of records. Since result
grows as rows_in_table1 × rows_in_table2, it can get very large, so it’s best
used with smaller tables or alongside a WHERE clause to filter results into
meaningful pairs.
CROSS JOIN

Syntax:

SELECT * FROM table1


CROSS JOIN table2;

Examples of SQL CROSS JOIN

Before diving into queries, let’s create two sample tables: Customer and
Orders. These tables will help us understand how CROSS JOIN combines data
into multiple combinations.

Table 1- Customer

CREATE TABLE Customer (


ID INT,
NAME VARCHAR(50),
AGE INT,
PHONE VARCHAR(10) );

INSERT INTO Customer (ID, NAME, AGE, PHONE) VALUES


(1, 'AMIT JAIN', 21, 98474),
(2, 'JATIN VERMA', 47, 63996);
AG PHON
ID NAME E E

1 AMIT JAIN 21 98474

JATIN
2 47 63996
VERMA

Table 2- Orders

CREATE TABLE Orders (


ORDER_ID INT,
AMOUNT INT,
PLACED_ON DATE );

INSERT INTO Orders (ORDER_ID, AMOUNT, PLACED_ON) VALUES


(101, 999, '2023-04-19'),
(102, 4999, '2023-04-20');

ORDER_ AMOU PLACED_


ID NT ON

2023-04-
101 999
19

2023-04-
102 4999
20

Now, let’s perform a CROSS JOIN to see how every Customer pairs with every
Order In the below example, we will use the CROSS JOIN command to match
the data of the Customer and Orders table.

In general, if table A has m rows and table B has n rows, CROSS JOIN result
will have m × n rows.

Query:
SELECT *
FROM Customer
CROSS JOIN Orders;

Output:

AG PHON ORDER_ AMOU PLACED_


ID NAME E E ID NT ON

2023-04-
1 AMIT JAIN 21 98474 101 999
19

2023-04-
1 AMIT JAIN 21 98474 102 4999
20

JATIN 2023-04-
2 47 63996 101 999
VERMA 19

JATIN 2023-04-
2 47 63996 102 4999
VERMA 20

Explanation: CROSS JOIN combines every row from the Customer table with
every row from Orders table. Since there are 2 customers and 2 orders,
result contains 2 × 2 = 4 rows.
SQL Self Join

A Self Join is a regular join where a table is joined with itself. It is particularly
useful when comparing rows within the same table, such as retrieving
employee-manager relationships from an employee table.

Note: A self join is not a new join type. It simply means joining the same
table twice with aliases.

Self Join

Syntax:

SELECT columns
FROM table AS alias1
JOIN table AS alias2
ON alias1.column = alias2.related_column;

 columns: Columns to retrieve in the result.


 alias1: First reference (alias) of the table.

 alias2: Second reference (alias) of the same table.

 related_column: condition that links rows within same table (e.g.,


Employee.ManagerID = Manager.EmployeeID).

Syntax:

SELECT columns
FROM table AS alias1
JOIN table AS alias2
ON alias1.column = alias2.related_column;

 columns: Columns to retrieve in the result.

 alias1: First reference (alias) of the table.

 alias2: Second reference (alias) of the same table.

 related_column: condition that links rows within same table (e.g.,


Employee.ManagerID = Manager.EmployeeID).

Example: Employees and Their Managers

We have a table GFGemployees with employee_id, employee_name and


manager_id. Each employee is linked to their manager using manager_id.
Our goal is to extract employees along with their respective managers’
names.

Here is the query to create the table and insert sample data:

CREATE TABLE GFGemployees (


employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
manager_id INT );

INSERT INTO GFGemployees (employee_id, employee_name, manager_id)


VALUES (1, 'Zaid', 3),
(2, 'Rahul', 3),
(3, 'Raman', 4),
(4, 'Kamran', NULL),
(5, 'Farhan', 4);
Output

employee_id employee_name manager_id

1 Zaid 3

2 Rahul 3

3 Raman 4

4 Kamran NULL

5 Farhan 4

To retrieve the list of employees with their corresponding managers, we


perform a self join on the GFGemployees table. We use two aliases: e for
employees and m for managers.

By joining manager_id from the employee side with employee_id from the
manager side, we establish the relationship between employees and their
managers.

Query:

SELECT e.employee_name AS employee, m.employee_name AS manager


FROM GFGemployees AS e
JOIN GFGemployees AS m ON e.manager_id = m.employee_id;

Output

employee manager

Zaid Raman
employee manager

Rahul Raman

Raman Kamran

Farhan Kamran

Employees with a valid manager_id are shown. Kamran (who has no


manager, NULL) is not listed as an employee, but appears as a manager.

Applications of SQL Self Join

SQL Self Join is widely used in different scenarios, such as:

 Hierarchical Data: Representing organizational structures like


employee–manager, category–subcategory or parent–child
relationships.

 Finding Relationships: Identifying relationships within the same


table, for example linking friends in a social network or mapping task
dependencies.

 Data Comparison: Comparing rows within same table, such as


salaries of employees in same department.

 Detecting Duplicates: Finding duplicate records in a table by joining


it with itself on duplicate criteria.

 Sequential Data Analysis: Comparing current rows with previous or


next rows, useful for analyzing trends in sales or time-series data.
SQL | UPDATE with JOIN

In SQL, the UPDATE with JOIN statement is a powerful tool that


allows updating one table using data from another table based on a
specific JOIN condition. This technique is particularly useful when we need
to synchronize data, merge records, or update specific columns in one table
by referencing related records from another table.

In this article, we will explore how to use the SQL UPDATE JOIN statement
effectively with detailed examples, outputs, and best practices to optimize
performance.

What is SQL UPDATE with JOIN?

The UPDATE with JOIN statement enables us to modify records in a table


using a JOIN operation. It combines data from two or more tables based
on a matching condition (e.g., INNER JOIN, LEFT JOIN) and updates the
specified columns in one table. SQL UPDATE JOIN could be used to update
one table using another table and join condition.

Syntax

UPDATE target_table
SET target_table.column_name = source_table.column_name,
target_table.column_name2 = source_table.column_name2
FROM target_table
INNER JOIN source_table
ON target_table.column_name = source_table.column_name
WHERE condition;

Key Terms

 target_table: The table whose records you want to update.

 source_table: The table containing the data you want to use for the
update.

 SET: Specifies the columns in the target table that will be updated.

 INNER JOIN: Ensures only matching rows from both tables are
considered.

 ON: The condition that specifies how the tables are related.
 WHERE: An optional clause to filter which rows to update.

Example: SQL UPDATE with JOIN Using Two Tables

Let us assume we have two tables Geeks1 and Geeks2, each containing
data about different attributes. In this example, we will update Geeks1 by
joining it with Geeks2 based on a common column col1.

Table Geeks1

Table Geeks1

Table Geeks2

We have table Geeks2 which has two rows where Col 1 is 21 & 31 and We
want to update col2 and col3 in table Geeks1 using values from
table Geeks2 where col1 matches in both tables. Specifically, we will update
the rows where col1 is 21 and 31

Query:

UPDATE Geeks1
SET col2 = Geeks2.col2,
col3 = Geeks2.col3
FROM Geeks1
INNER JOIN Geeks2 ON Geeks1.col1 = Geeks2.col1
WHERE Geeks1.col1 IN (21, 31);

Output

Table Geeks1 After Update

Explanation:

 We are updating col2 and col3 in table Geeks1.

 We use an INNER JOIN to match rows


from Geeks1 and Geeks2 where col1 is the same.

 The WHERE clause filters the rows for col1 = 21 and col1 = 31.

SQL UPDATE with JOIN Using LEFT JOIN

Sometimes you may need to update records in the target table even if there
is no match in the source table. In such cases, we can use LEFT JOIN.

Syntax

UPDATE target_table
SET target_table.column_name = source_table.column_name
FROM target_table
LEFT JOIN source_table
ON target_table.column_name = source_table.column_name;

Example

Let’s say we want to update the Geeks1 table but only change col2 where a
match exists; otherwise, set it to a default value.

UPDATE Geeks1
SET col2 = ISNULL(Geeks2.col2, 0)
FROM Geeks1
LEFT JOIN Geeks2
ON Geeks1.col1 = Geeks2.col1;
Output

Table Geeks1 After Update using Left Join

Explanation:

 Rows with no match in Geeks2 have col2 set to 0 (default value).

 Rows with matches are updated with values from Geeks2.

Conclusion

The SQL UPDATE with JOIN statement is a powerful technique


for updating data in one table using values from another table based
on specific conditions. By using INNER JOIN or LEFT JOIN, we can
perform targeted updates while maintaining data integrity. This article
covered practical examples, syntax, and key performance tips to help us
efficiently use UPDATE JOIN in SQL. Whether we're synchronizing tables,
merging data, or cleaning up records, mastering this approach is essential
for database administrators and developers.
SQL DELETE JOIN

The SQL DELETE JOIN statement is a powerful feature that allows us


to delete rows from one table based on conditions involving another
table. This is particularly useful when managing relationships between
tables in a database. For example, we may want to delete rows in a
"Library Books" table where certain "Student IDs" exist in a related
"Students" table.

SQL DELETE JOIN

The DELETE JOIN operation in SQL delete rows from a table while
considering conditions that involve another table. By
combining DELETE with JOIN, we can efficiently manage related data across
tables. This method allows us to join two or more tables and delete rows
from the primary table that meet specific criteria, ensuring that
the integrity of related data is maintained while removing
unnecessary or outdated information.

While we can join multiple tables in the FROM clause, we can only specify
one table in the DELETE clause. This means that although multiple tables
can be used to define conditions for deletion, the rows can only be deleted
from a single, explicitly stated table.

Key Features of DELETE JOIN

 Deletes rows from one primary table based on conditions set by joining
additional tables.

 Only one table is listed explicitly in the DELETE clause.

 Ensures efficient data management and integrity across relational


tables.

 Uses INNER JOIN, LEFT JOIN, or USING clauses to match data


between tables.

 Can target specific rows using the WHERE clause.

Syntax:

DELETE table1
FROM table1 JOIN table2
ON table1.attribute_name = table2.attribute_name
WHERE condition

Key Terms:

 table1: The primary table from which rows will be deleted.

 table2: The table used for comparison or condition.

 ON: Specifies the condition for the JOIN.

 WHERE: Optional; filters which rows to delete.

Demo SQL Database

For this DELETE JOIN tutorial, we will use two example


tables: students and library_books. These tables contain related data,
where each student has an associated library book entry. This example
demonstrates how to delete records from the library_books table based on
matching student IDs from the students table.

1. Student Table

student student_na student_bra


_id me nch

1001 PRADEEP E.C.E

1002 KIRAN E.C.E

1003 PRANAV E.C.E

2001 PADMA C.S.E

2002 SRUTHI C.S.E


student student_na student_bra
_id me nch

2003 HARSITHA C.S.E

3001 SAI I.T

3002 HARSH I.T

3003 HARSHINI I.T

2. Library Books Table

lib_i book_tak
d en

100
2
1

100
3
2

100
4
3

200
2
1

300 3
lib_i book_tak
d en

Step-by-Step Example: Deleting Rows with DELETE JOIN

This section demonstrates how to use the DELETE JOINsyntax to remove


rows from one table based on conditions involving another table. This
example will walk you through the process of setting up the
necessary tables, inserting data, and executing the DELETE JOIN query
to delete specific rows efficiently.

Step 1: Create Tables

CREATE DATABASE GeeksforGeeks;


USE GeeksforGeeks

CREATE TABLE student (


student_id VARCHAR(8),
student_name VARCHAR(20),
student_branch VARCHAR(20)
)

CREATE TABLE library_books(


lib_id VARCHAR(20),
book_taken INT
)

Step 2: Insert Sample Data

INSERT INTO students


VALUES( '1001','PRADEEP','E.C.E'),
( '1002','KIRAN','E.C.E'),
( '1003','PRANAV','E.C.E'),
( '2001','PADMA','C.S.E'),
( '2002','SRUTHI','C.S.E'),
( '2003','HARSITHA','C.S.E'),
( '3001','SAI','I.T'),
( '3002','HARSH','I.T'),
( '3003','HARSHINI','I.T')
INSERT INTO library_books
VALUES( '1001',2),
( '1002',3),
( '1003',4),
( '2001',2),
( '3001',3)

Step 3: Delete a Row Using DELETE JOIN

Suppose we want to delete a row from the library_books table where


the lib_id matches student_id 1001 in the students table for a specific
student ID

DELETE library_books
FROM library_books JOIN students ON
students.student_id =library_books.lib_id
WHERE lib_id= 1001
SELECT * FROM library_books

Output
Explanation

 Here, deletion occurs only in the library_books table.

 The join with the students table helps identify exactly which rows to
remove.

Important Points about DELETE JOIN

 DELETE JOIN allows to delete rows from a table based on condition


involving another table.

 We cannot delete from multiple tables in a single DELETE JOIN query.

 We can only specify one table in the DELETE clause, even if multiple
tables are joined in the FROM clause.

 If a record is deleted from a table, related records in other table will be


deleted too
Conclusion

The SQL DELETE JOIN operation is a strong way to manage and clean
up data across multiple tables efficiently. By using the proper syntax and
understanding how JOIN works, we can maintain a well-organized and
optimized database. Always test our DELETE queries and ensure data
integrity before applying them to production systems.

Recursive Join in SQL

In SQL, a recursive join is a powerful technique used to


handle hierarchical data relationships, such as managing employee-
manager relationships, family trees, or any data with a self-referential
structure. This type of join enables us to combine data from the same table
repeatedly, accumulating records until no further changes are made to the
result set.

In this article, we will explore recursive joins in SQL, understand the


concept of recursive common table expressions (CTEs), and work through
detailed examples to illustrate how to use recursive joins effectively.

What is a Recursive Join in SQL?

Recursive joins are implemented using recursive common table


expressions (CTEs). CTEs are temporary result sets that can be referred to
within the execution scope of a SELECT, INSERT, UPDATE, or DELETE
statement. In a recursive CTE, a query is repeatedly executed to gather
related data, making it possible to handle hierarchical relationships like
parent-child data.

Syntax:

WITH RECURSIVE cte_name AS (


-- Anchor Query: Select the root or starting point
SELECT columns
FROM table
WHERE condition
UNION ALL

-- Recursive Query: Join the CTE with the table to fetch related data
SELECT t.columns
FROM table t
INNER JOIN cte_name cte ON t.column = cte.column
)

Example of Recursive Join in SQL

Let’s walk through an example where we create an employee-manager


hierarchy using a recursive join in SQL. Assume we have a table of
employees where each employee has a manager_id pointing to their
manager’s employee_id. The goal is to retrieve a list of employees along with
their managers, all the way up the chain.

employee employee_na manager ag


_id me _id e

1 Ankit NULL 32

2 Ayush 1 31

3 Piyush 1 42

4 Ramesh 2 31

5 Rohan 3 29

6 Harry 3 28

7 Rohit 4 32

8 Gogi 4 32
employee employee_na manager ag
_id me _id e

9 Tapu 5 33

10 Sonu 5 40

Now, we will use a recursive join to get a list of all employees and their
managers, starting with Ankit (employee with employee_id = 1).

Query:

WITH RECURSIVE employee_hierarchy AS (


-- Anchor query: Start with Ankit (employee_id = 1)
SELECT employee_id, employee_name, manager_id, age
FROM employees
WHERE employee_id = 1

UNION ALL

-- Recursive query: Join the employees table with itself to get the
employees reporting to each manager
SELECT e.employee_id, e.employee_name, e.manager_id, e.age
FROM employees e
INNER JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM employee_hierarchy;

Output:
Explanation:

 The anchor part selects Ankit as the starting point.

 The recursive part joins the employees table with the


employee_hierarchy CTE to find all employees who report to the
previous level of employees.

 The process repeats until all employees who report to Ankit (and
indirectly to others) are listed.

Applications of Recursive Joins

 Hierarchical Data Representation: Recursive joins are commonly


used to represent and query hierarchical structures, such as employee-
manager relationships, organizational charts, and bill of materials.

 Parent-Child Relationships: Recursive queries help retrieve data


that represents parent-child relationships, such as categories and
subcategories in a product catalog.

 Graph Traversal: Recursive joins are also used for traversing graphs
or networks, such as social networks or transportation networks.
Conclusion

Recursive joins in SQL, implemented through recursive CTEs, are a vital tool
for querying hierarchical data efficiently. Whether it's navigating
organizational structures, analyzing product categories, or working with
parent-child relationships, recursive joins simplify the process of building and
querying hierarchies. By using the WITH RECURSIVE clause and combining it
with an INNER JOIN, SQL provides a powerful way to traverse and retrieve
nested data.
Chapter IX
SQL Functions

SQL functions offer an efficient and versatile approach to data analysis.


Enhance your queries with built-in functions that manipulate data types and
perform calculations.

 Date Functions

 String Functions

 Numeric Functions

 Statistical Functions

 JSON Functions

 Conversion Functions

 Datatype Functions

 LTRIM Function

 UPPER Function

 RTRIM Function

SQL | Date Functions

Last Updated : 20 Aug, 2025

SQL Date Functions are built-in tools used to manage and manipulate date
and time values in a database. They are essential for performing operations
like retrieving current dates, calculating differences and formatting results

 Calculate date and time differences (e.g., days between orders).


 Retrieve the current system date and time.

 Extract specific parts of a date (year, month, day).

 Format dates for user-friendly display.

 Track trends, deadlines, or schedules in business processes.

Let's use the salestable as the base for demonstrating each of the SQL Date
Functions mentioned. Here’s the structure of the sales table:

Sale
s Table

1. NOW()

The NOW() function returns the current date and time based on the server’s
time zone. It is commonly used when we need to capture the exact moment
an event occurs, such as a transaction timestamp. This function is useful for
logging timestamps or comparing current time with database records.

Query:

SELECT NOW() AS current_datetime;

Output

current_datetim
e

2024-08-12
14:35:27

2. CURDATE()
The CURDATE() function returns the current date in the YYYY-MM-DD format.
It is useful when we need to retrieve only the current date without the time.
This function is often used in reporting or filtering records by date.

Query:

SELECT CURDATE() AS current_date;

Output

current_d
ate

2024-08-
12

3. CURTIME()

The CURTIME() function returns the current time in the HH:MM:SS format. It is
useful for time-specific operations, such as scheduling tasks. By isolating the
time, this function helps in scenarios requiring precise time comparisons.

Query:

SELECT CURTIME() AS current_time;

Output

current_ti
me

14:35:27

4. DATE()

The DATE() function extracts the date portion from a date or


datetime expression. This function is useful when we want to ignore the time
component and focus only on the date. This function is commonly employed
in date-only comparisons or aggregations.

Query:

SELECT sale_id, product_name,


DATE(sale_date) AS sale_date_only

FROM sales;

Output

Date Function

5. EXTRACT()

The EXTRACT() function allows us to retrieve a specific part (like year, month,
or day) from a date. It is particularly useful when we need to group or filter
data based on specific time components. This function is especially useful in
reports that require year-over-year analysis.

Query:

SELECT sale_id, product_name,

EXTRACT(YEAR FROM sale_date)

AS sale_year FROM sales;

Output

Extract Function
6. DATE_ADD()

The DATE_ADD() function adds a specified time interval (like days, months,
or years) to a date. It's often used in scenarios where we need to calculate a
future date. This function simplifies future date calculations for planning
purposes.

Query:

SELECT sale_id, product_name, DATE_ADD(sale_date, INTERVAL 7 DAY) AS


sale_date_plus_7_days FROM sales;

Output

sale_i product_na sale_date_plus_7_


d me days

1 Widget A 2024-08-08

2 Widget B 2024-08-12

3 Widget C 2024-08-14

4 Widget A 2024-08-17

5 Widget B 2024-08-22

6 Widget C 2024-08-27

7. DATE_SUB()

The DATE_SUB()function subtracts a specified time interval from a date. It is


handy when we need to determine a past date by subtracting days, months,
or years. This is often used for retrospective data analysis.

Query:

SELECT sale_id, product_name,


DATE_SUB(sale_date, INTERVAL 3 DAY)

AS sale_date_minus_3_days

FROM sales;

Output

sale_i product_na sale_date_minus_3_


d me days

1 Widget A 2024-07-29

2 Widget B 2024-08-02

3 Widget C 2024-08-04

4 Widget A 2024-08-07

5 Widget B 2024-08-12

6 Widget C 2024-08-17

8. DATEDIFF()

The DATEDIFF() function returns the difference in days between two dates. It
is commonly used to calculate the duration between two events or dates.
This function is ideal for deadline tracking or overdue calculations. Here we
will find out how many days are left from each sale till August 15, 2024.

Query:

SELECT sale_id, product_name, sale_date,

DATEDIFF('2024-08-15', sale_date) AS days_until_aug15

FROM sales;

Output
sale_i product_na sale_dat days_until_au
d me e g15

2024-08-
1 Widget A 14
01

2024-08-
2 Widget B 10
05

2024-08-
3 Widget C 8
07

2024-08-
4 Widget A 5
10

2024-08-
5 Widget B 0
15

2024-08-
6 Widget C -5
20

9. DATE_FORMAT()

The DATE_FORMAT() function formats a date according to a specified format,


allowing for customized date output (e.g. displaying the full day name,
month name etc). This function is excellent for improving report readability.

Query:

SELECT sale_id, product_name,

DATE_FORMAT(sale_date, '%W, %M %d, %Y')

AS formatted_sale_date FROM sales;

Output
sale_i product_na
d me formatted_sale_date

Thursday, August 01,


1 Widget A
2024

Monday, August 05,


2 Widget B
2024

Wednesday, August 07,


3 Widget C
2024

Saturday, August 10,


4 Widget A
2024

Thursday, August 15,


5 Widget B
2024

Tuesday, August 20,


6 Widget C
2024

10. ADDDATE()

The ADDDATE() function adds a specified time interval to a date. It is useful


for calculating future or past dates based on a given date.

Query:

SELECT sale_id, product_name,

ADDDATE(sale_date, INTERVAL 10 DAY)

AS sale_date_plus_10_days

FROM sales;

Output
sale_i product_na sale_date_plus_10_
d me days

1 Widget A 2024-08-11

2 Widget B 2024-08-15

3 Widget C 2024-08-17

4 Widget A 2024-08-20

5 Widget B 2024-08-25

6 Widget C 2024-08-30

11. ADDTIME()

The ADDTIME() function adds a specified time interval to a time or datetime


value. It is useful for adjusting times by adding hours, minutes or seconds.

Query:

SELECT sale_id, product_name, ADDTIME('10:30:00', '02:30:00') AS


sale_time_plus_2hrs_30min FROM sales;

Output

sale_i product_na sale_time_plus_2hrs_3


d me 0min

1 Widget A 13:00:00

2 Widget B 13:00:00
sale_i product_na sale_time_plus_2hrs_3
d me 0min

3 Widget C 13:00:00

4 Widget A 13:00:00

5 Widget B 13:00:00

6 Widget C 13:00:00

SQL | String functions

Last Updated : 20 Aug, 2025

SQL String Functions are powerful tools that allow us to manipulate, format,
and extract specific parts of text data in our database. These functions are
essential for tasks like cleaning up data, comparing strings, and combining
text fields. Whether we are working with names, addresses, or any form of
textual data, mastering SQL string functions is crucial for efficient data
handling and analysis.

Common SQL String Functions

String functions are used to perform an operation on input string and return
an output string. Below are some of the most commonly used SQL string
functions:

1. CONCAT(): Concatenate Strings


The CONCAT() function is used to concatenate (combine) two or more strings
into one string. It is useful when we want to merge fields like first and last
names into a full name.

Query:

SELECT CONCAT('John', ' ', 'Doe') AS FullName;

Output:

John Doe

2. CHAR_LENGTH() / CHARACTER_LENGTH(): Find String Length

The CHAR_LENGTH() or LENGTH() function returns the length of a string in


characters. It’s essential for validating or manipulating text data, especially
when you need to know how many characters a string contains.

Query:

SELECT CHAR_LENGTH('Hello') AS StringLength;

Output:

3. UPPER() and LOWER(): Convert Text Case

These functions convert the text to uppercase or lowercase, respectively.


They are useful for normalizing the case of text in a database.

Query:

SELECT UPPER('hello') AS UpperCase;


SELECT LOWER('HELLO') AS LowerCase;

Output:

HELLO
hello

4. LENGTH(): Length of String in Bytes

LENGTH() returns the length of a string in bytes. This can be useful for
working with multi-byte character sets.

Query:

SELECT LENGTH('Hello') AS LengthInBytes;


Output:

5. REPLACE(): Replace Substring in String

The REPLACE() function replaces occurrences of a substring within a string


with another substring. This is useful for cleaning up data, such as replacing
invalid characters or formatting errors.

Query:

SELECT REPLACE('Hello World', 'World', 'SQL') AS UpdatedString;

Output:

Hello SQL

6. SUBSTRING() / SUBSTR(): Extract Part of a String

The SUBSTRING() (or SUBSTR()) function is used to extract a substring from a


string, starting from a specified position. It is especially useful when we need
to extract a specific part of a string, like extracting the domain from an email
address.

Query:

SELECT SUBSTRING('Hello World', 1, 5) AS SubStringExample;

Output:

Hello

7. LEFT() and RIGHT(): Extract Substring from Left or Right

The LEFT() and RIGHT() functions allow you to extract a specified number of
characters from the left or right side of a string, respectively. It is used for
truncating strings for display.

Query:

SELECT LEFT('Hello World', 5) AS LeftString;


SELECT RIGHT('Hello World', 5) AS RightString;

Output:

Hello
World

8. INSTR(): Find Position of Substring


The INSTR() function is used to find the position of the first occurrence of a
substring within a string. It returns the position (1-based index) of the
substring. If the substring is not found, it returns 0. This function is
particularly useful for locating specific characters or substrings in text data.

Query:

SELECT INSTR('Hello World', 'World') AS SubstringPosition;

Output:

9. TRIM(): Remove Leading and Trailing Spaces

The TRIM() function removes leading and trailing spaces (or other specified
characters) from a string. By default, it trims spaces but can also remove
specific characters using TRIM(character FROM string). This is helpful for
cleaning text data, such as user inputs or database records.

Query:

SELECT TRIM(' ' FROM ' Hello World ') AS TrimmedString;

Output:

Hello World

10. REVERSE(): Reverse the String

The REVERSE() function reverses the characters in a string. It’s useful in


situations where we need to process data backward, such as for password
validation or certain pattern matching.

Query:

SELECT REVERSE('Hello') AS ReversedString;

Output:

olleH

Other String Functions

In SQL, beyond the basic string functions, there are several advanced string
functions that can help you manipulate and process string data more
effectively. These are the some additional SQL Functions.

11. ASCII(): Get the ASCII Value of a Character


The ASCII() function returns the ASCII value of a single character. This is
helpful when we need to find the numeric code corresponding to a character,
often used in encoding and decoding text.

Syntax:

SELECT ascii('t');

Output:

116

12. CONCAT_WS(): Concatenate Strings with a Separator

CONCAT_WS() stands for "Concatenate With Separator." It allows us to join


multiple strings with a specific separator between them. This is ideal when
we need to merge columns like first name and last name with a custom
separator.

Syntax:

SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks');

Output:

geeks_for_geeks

13. FIND_IN_SET(): Find Position of a Value in a Comma-Separated


List

The FIND_IN_SET() function returns the position of a value within a comma-


separated list. This is especially useful for finding out where an element
exists in a string of values (e.g., tags, categories).

Syntax:

SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');

Output:

14. FORMAT(): Format Numbers for Readable Output

The FORMAT() function is used to format a number as a string in a specific


way, often with commas for thousands or with a specific number of decimal
places. It is handy when you need to display numbers in a user-friendly
format.
Syntax:

SELECT FORMAT(0.981 * 100, 'N2') + '%' AS PercentageOutput;

Output:

‘98.10%’

15. INSTR(): Find the Position of a Substring

The INSTR() function returns the position of the first occurrence of a


substring within a string. If the substring is not found, it returns 0. It is useful
for finding where specific text appears in a larger string.

Syntax:

SELECT INSTR('geeks for geeks', 'e');

Output:

16. LCASE(): Convert String to Lowercase

The LCASE() function converts all characters in a string to lowercase. It helps


standardize text data, especially when comparing strings in a case-
insensitive way.

Syntax:

SELECT LCASE ("GeeksFor Geeks To Learn");

Output:

geeksforgeeks to learn

17. LOCATE(): Find the nth Position of a Substring

LOCATE() allows you to find the nth occurrence of a substring in a string. This
is especially useful when you need to locate a specific substring based on its
position.

Syntax:

SELECT LOCATE('for', 'geeksforgeeks', 1);

Output:

18. LPAD(): Pad the Left Side of a String


LPAD() is used to pad a string to a certain length by adding characters to the
left side of the original string. It is useful when you need to format data to a
fixed length.

Syntax:

SELECT LPAD('geeks', 8, '0');

Output:

000geeks

19. MID(): Extract a Substring from the Middle

MID() extracts a substring starting from a given position in a string and for a
specified length. It is useful when you want to extract a specific portion of a
string.

Syntax:

SELECT Mid ("geeksforgeeks", 6, 2);

Output:

for

20. POSITION(): Find the Position of a Character in a String

The POSITION() function finds the position of the first occurrence of a


specified character in a string.

Syntax:

SELECT POSITION('e' IN 'geeksforgeeks');

Output:

21. REPEAT(): Repeat a String Multiple Times

The REPEAT() function repeats a string a specified number of times. It's


useful when you need to duplicate a string or pattern for certain operations.

Syntax:

SELECT REPEAT('geeks', 2);

Output:

geeksgeeks
22. REPLACE(): Replace a Substring in a String

REPLACE() is used to replace all occurrences of a substring with another


substring. It's useful for replacing or cleaning up certain text in your data.

Syntax:

REPLACE('123geeks123', '123');

Output:

geeks

23. RPAD(): Pad the Right Side of a String

RPAD() pads the right side of a string with specified characters to a fixed
length. This is often used to format text or numbers to a desired size.

Syntax:

RPAD('geeks', 8, '0');

Output:

‘geeks000’

24. RTRIM(): Remove Trailing Characters

RTRIM() removes trailing characters from the right side of a string. By


default, it removes spaces, but you can specify other characters as well.

Syntax:

RTRIM('geeksxyxzyyy', 'xyz');

Output:

‘geeks’

25. SPACE(): Generate a String of Spaces

The SPACE() function generates a string consisting of a specified number of


spaces. This is useful when you need to format output or create padding in
your queries.

Syntax:

SELECT SPACE(7);

Output:
‘ ‘

26. STRCMP(): Compare Two Strings

STRCMP() compares two strings and returns an integer value based on their
lexicographical comparison. This is useful for sorting or checking equality
between two strings. STRCMP(string1, string2) returns:

 0 if both strings are equal.

 A negative value if string1 is less than string2.

 A positive value if string1 is greater than string2.

Syntax

SELECT STRCMP('google.com', 'geeksforgeeks.com');

Output:

Summary of String Functions

Below is a table summarizing these functions, their purposes, and examples.

Function Description Example Query Output

Find ASCII value of


ASCII() SELECT ASCII('A'); 65
a character.

CONCAT_W Concatenate with a SELECT CONCAT_WS('_',


A_B
S() delimiter. 'A', 'B');

FIND_IN_SE Find position in a SELECT


2
T() set. FIND_IN_SET('b', 'a,b,c');

Find nth SELECT LOCATE('e',


LOCATE() 2
occurrence. 'geeksforgeeks', 1);

LPAD() Pad string from the SELECT LPAD('geeks', 8, 000geeks


Function Description Example Query Output

left. '0');

Find character SELECT POSITION('e' IN


POSITION() 2
position. 'geeks');

SELECT REPEAT('SQL', SQLSQLSQ


REPEAT() Repeat a string.
3); L

Remove trailing SELECT


RTRIM() SQL
characters. RTRIM('SQLXYZ', 'XYZ');

SQL | Numeric Functions


SQL Numeric Functions are built-in tools that allow you to perform
mathematical and arithmetic operations on numeric data. They are widely
used in financial, statistical, and reporting tasks to simplify calculations.

 Operate on numeric data types like INT, FLOAT, DECIMAL, DOUBLE.

 Perform basic arithmetic operations (addition, subtraction,


multiplication, division).

 Round numbers to desired precision.

 Format numeric values for better readability.

 Aggregate and analyze numeric data efficiently.

Commonly Used SQL Numeric Functions

Following are the numeric functions defined in SQL

1. ABS() – Absolute Value


The ABS() function returns the absolute value of a number, which is the
number without its sign (i.e., it converts negative numbers to positive).

Syntax:

SELECT ABS(number);

Example:

SELECT ABS(-25);

Output:

25

2. CEIL() or CEILING() – Round Number Up

The CEIL() (or CEILING()) function rounds a number up to the nearest


integer, regardless of whether the decimal part is greater than or less than
0.5.

Syntax:

SELECT CEIL(number);

Example:

SELECT CEIL(12.34);

Output:

13

3. FLOOR() – Round Number Down

The FLOOR() function rounds a number down to the nearest integer, ignoring
the decimal part.

Syntax:

SELECT FLOOR(number);

Example:

SELECT FLOOR(12.98);

Output:

12

4. ROUND() – Round a Number to a Specified Decimal Place


The ROUND() function rounds a number to a specified number of decimal
places. It is very useful for financial calculations or whenever precise
rounding is necessary.

Syntax:

SELECT ROUND(number, decimal_places);

Example:

SELECT ROUND(15.6789, 2);

Output:

15.68

5. TRUNCATE() – Remove Decimal Places

The TRUNCATE() function is used to remove the decimal portion of a number


without rounding. It truncates the number to the specified number of decimal
places.

Syntax:

SELECT TRUNCATE(number, decimal_places);

Example:

SELECT TRUNCATE(12.98765, 2);

Output:

12.98

6. MOD() – Modulo or Remainder

The MOD() function returns the remainder of a division operation (i.e., it


computes the modulus). This function is useful for tasks like determining
even/odd numbers or finding remainders in mathematical operations.

Syntax:

SELECT MOD(dividend, divisor);

Example:
SELECT MOD(10, 3);

Output:

7. POWER() – Raise a Number to the Power of Another

The POWER() function is used to raise a number to the power of another


number. It is often used in mathematical calculations like compound interest
or growth rate.

Syntax:

SELECT POWER(base, exponent);

Example:

SELECT POWER(2, 3);

Output:

8. SQRT() – Square Root

The SQRT() function returns the square root of a number. This is useful for
mathematical calculations involving geometry or statistical analysis.

Syntax:

SELECT SQRT(number);

Example:

SELECT SQRT(16);

Output:

9. EXP() – Exponential Function


The EXP() function returns the value of e raised to the power of a specified
number, where e is the base of the natural logarithm (approximately
2.71828).

Syntax:

SELECT EXP(number);

Example:

SELECT EXP(1);

Output:

2.718281828459045

10. LOG() – Logarithm

The LOG() function returns the natural logarithm (base e) of a number. You
can also use LOG(base, number) to calculate the logarithm of a number with
a custom base.

Syntax:

SELECT LOG(number);

SELECT LOG(base, number);

Example:

SELECT LOG(100);

Output:

4.605170186

11. RAND() – Random Number

The RAND() function generates a random floating-point number between 0


and 1. This function is commonly used for simulations, lotteries, or
generating random samples.

Syntax:

SELECT RAND();

Example:

SELECT RAND();

Output:
0.287372

SQL - Statistical Functions


SQL statistical functions are essential tools for extracting meaningful
insights from databases. These functions, enable users to perform statistical
calculations on numeric data. Whether determining averages, sums,
counts, or measures of variability, these functions empower efficient data
analysis within the SQL environment.

In this article, we’ll explore the most commonly used SQL statistical functions
such as AVG(), SUM(), COUNT(), MIN(), MAX(), STDDEV(), VAR(), and more.
We will also provide practical examples to demonstrate their usage.

What is SQL Statistical Functions?

Statistics is a branch of mathematics that deals with data collection,


analysis, interpretation, presentation, and organization. It involves the use of
mathematical techniques to extract meaningful information from data.
Statistics is widely used in various fields such as business, economics, social
science, medicine, and engineering

A Statistical function is a mathematical function that helps us to process


and analyze data to provide meaningful information about the dataset. For
example mean, sum, min, max, standard deviation, etc.

Statistical Functions in SQL

Here are Some Common Statistical Functions in SQL:


Function Output

Calculates the average value of a


AVG() numeric column.

Calculates the sum of values in a


SUM() numeric column.

Counts the number of rows in a


result set or the number of non-null
COUNT() values in a column.

Returns the minimum value in a


MIN() column.

Returns the maximum value in a


MAX() column.

Calculates the population variance


VAR() / VARIANCE() of a numeric column.

Calculates the population standard


STDDEV() / STDDEV_POP() deviation of a numeric column.

Calculates the correlation


coefficient between two numeric
CORR() columns.

Calculates the population


covariance between two numeric
COVAR_POP() columns.
Function Output

Calculates a specified percentile


PERCENTILE_CONT() value for a numeric column

Statistical Functions With Exmaple

We have four tables in our database: 'studentDetails,' 'employees,'


'sales_data,' and 'financial_data.' (The pictures are displayed below.)

Table :
StudentDetails

employees Table:
Table:Employees

sales_data:

Table:Sales_data

financial_data:

Table: financial_data

1. AVG() Function

Calculate the average or arithmetic mean for a group of numbers or a


numeric column.
Syntax:

SELECT AVG(column_name) FROM table_name;

Example Query:

SELECT AVG(marks) AS average_marks FROM studentDetails;

Output:

AVG_MARKS

2. SUM() Function

The total of all numeric values in a group i.e. Calculates the total sum of
values in a numeric column.

Syntax:

SELECT SUM(column_name) FROM table_name;

Example Query:

SELECT SUM(marks) AS total_marks FROM studentDetails;

Output:

Sum of marks

3. Count() Function

The number of cell locations in a range that contain a numeric character i.e
Counts the number of rows in a result set or the number of non-null values in
a column.

Syntax:

SELECT COUNT(*) FROM table_name;

SELECT COUNT(column_name) FROM table_name;

Example Query:

SELECT COUNT(studentID) AS total_students FROM studentDetails;


Output:

Count of Student

Example Query:

select count(*) from studentdetails;

Output:

Return the count of rows that meet a specified condition .

count all rows

4. Max() Function

Returns the highest numeric value in a group of numbers.

Syntax:

SELECT MAX(column_name) FROM table_name;

Example Query:

SELECT MAX(marks) AS highest_marks FROM studentDetails;

Output:

Maximum marks

5. MIN() Function

Returns the lowest numeric value in a group of numbers.

Syntax:

SELECT MIN(column_name) FROM table_name;


Example Query:

SELECT MIN(marks) AS lowest_marks FROM studentDetails;

Output:

Minimum marks

6. VAR() / VARIANCE() Function

Calculates the population variance of a numeric column

Syntax:

SELECT VAR(column_name) FROM table_name;

Example Query:

SELECT VARIANCE(marks) AS variance_marks FROM studentDetails;

Output:

Variance marks

7. STDDEV() / STDDEV_POP() Function

The standard deviation for a group of numbers based on a sample

Syntax:

SELECT STDDEV(column_name) FROM table_name;

Example Query:

SELECT STDDEV(marks) AS stddev_marks FROM studentDetails;

Output:

Standrad deviation for marks

8. PERCENTILE_CONT() Function
Calculates a specified percentile value for a numeric column.

Syntax:

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column_name)


FROM table_name;

Example Query:

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS


median_salary

FROM employees;

Output:

Median salary of employee's

9. CORR() Function

Calculates the correlation coefficient between two numeric columns.

Syntax:

SELECT CORR(column1, column2) FROM table_name;

Example Query:

SELECT CORR(sales, profit) AS correlation_coefficient

FROM sales_data;

Output:
correlation coefficient between 'sales'
and 'profit'

10 .COVAR_POP() Function

Calculates the population covariance between two numeric columns.

Syntax:

SELECT COVAR_POP(column1, column2) FROM table_name;

Example Query:

SELECT COVAR_POP(revenue, expenses) AS population_covariance

FROM financial_data;

Output:

Population Covariance between revenue


and expenses

Conclusion

In SQL, statistical functions help to analyze and summarise data in the


database. These functions assist in extracting meaningful information from
the given datasets. For determining the number of occurrences, calculating
totals, finding averages or calculating the variance in the dataset statistical
functions plays a vital role. Overall, the integration of Statistical Functions
elevates SQL's capabilities, making it an invaluable asset for businesses and
analysts seeking actionable intelligence from their relational databases.
Working With JSON in SQL

JSON stands for Javascript Object Notation. It is mainly used in storing


and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB,
etc., use JSON format data. Whenever your data from one server has to be
transferred to a web page, JSON format is the preferred format for front-end
applications like Android, iOS, React, Angular, etc.

In this article, we will learn how to store, retrieve, and manipulate JSON data
in SQL Server using various SQL functions. We will learn how JSON fits into
SQL, demonstrate how to store JSON data in SQL tables and cover the most
common JSON functions like ISJSON(), JSON_VALUE(), JSON_MODIFY(), and
more.

What is JSON in SQL Server?

JSON is a lightweight data-interchange format that is easy for humans to


read and write. SQL Server introduced native support for JSON
handling starting from SQL Server 2016. This allows you to store JSON data
in NVARCHAR columns and use SQL functions to parse, query, and modify
JSON data.

Storing JSON in SQL Server


In SQL Server, you can store JSON data as a string in
an NVARCHAR column. SQL Server treats JSON data as a string, allowing
you to parse it when necessary.

Creating Tables with Data

Now let us create a table named "Authors" and let us insert some data into
it as shown below:

CREATE TABLE Authors (


ID INT IDENTITY NOT NULL PRIMARY KEY,
AuthorName NVARCHAR(MAX),
Age INT,
Skillsets NVARCHAR(MAX),
NumberOfPosts INT
);
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES
('Geek',25,'Java,Python,.Net',5);
GO

INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES


('Geek2',22,'Android,Python,.Net',15);
GO
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES
('Geek3',23,'IOS,GO,R',10);
GO
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES
('Geek4',24,'Java,Python,GO',5);
GO

JSON is a beautiful option for bridging NoSQL and relational worlds. Hence,
in case if you have the data got exported from MongoDB and need to import
them in SQL Server, we can follow below approaches

JSON documents can be stored as-is in NVARCHAR columns either in LOB


storage format or Relational storage format. Raw JSON documents have to be
parsed, and they may contain Non-English text. By using nvarchar(max)
data type, we can store JSON documents with a max capacity of 2 GB in size.
If the JSON data is not huge, we can go for NVARCHAR(4000), or else we can
go for NVARCHAR(max) for performance reasons.

Cross feature compatibility:


The main reason for keeping the JSON document in NVARCHAR format is for
Cross feature compatibility. NVARCHAR works with X feature i.e. all the SQL
server components such as Hekaton(OLTP), temporal, or column store tables,
etc. As JSON behavior is also in that way, it is represented as NVARCHAR
datatype.

Migration:

Before SQL Server 2016, JSON was stored in the database as text. Hence,
there was a need to change the database schema and migration occurred as
JSON type in NVarchar format

Client-side support:

JSON is just treated as an Object in JavaScript and hence called as Javascript


Object Notation. There is no specific standardized JSON object type on client-
side available similar to XmlDom object.

Let us see the important functionalities available in SQL Server which can be
used with JSON data.

Example JSON Data :

{
"Information":
{"SchoolDetails":
[{"Name": "VidhyaMandhir"}, {"Name": "Chettinad"},
{"Name":"PSSenior"}]
}
}

Example 1: ISJSON (JSON string):

This function is used to check whether the given input json string is in
JSON format or not. If it is in JSON format, it returns 1 as output or else 0.
i.e. it returns either 1 or 0 in INT format.

SELECT ISJSON(@JSONData) AS VALIDJSON


Example 2: JSON_VALUE (JSON string, path):

The output will be a scalar value from the given JSON string. Parsing of JSON
string is done and there are some specific formats are there for providing the
path. For example

 '$' - reference entire JSON object

 '$.Example1' - reference Example1in JSON object

 '$[4]' - reference 4th element in JSON array

 '$.Example1.Example2[2].Example3' - reference nested property in


JSON object

Example :

SELECT JSON_VALUE(@JSONData,'$.Information.SchoolDetails[0].Name') as
SchoolName
Example 3: JSON_QUERY(JSON string, path)

Used to extract an array of data or objects from the JSON string.

SELECT JSON_QUERY(@JSONData,'$.Information.SchoolDetails')
AS LISTOFSCHOOLS

LIST OF SCHOOLS BY MEANS OF JSON_QUERY

Example 4: JSON_MODIFY
There is an option called "JSON_MODIFY" in (Transact-SQL) function is
available to update the value of a property in a JSON string and return the
updated JSON string. Whenever there is a requirement to change JSON text,
we can do that

SET @JSONData= JSON_MODIFY(@JSONData,


'$.Information.SchoolDetails[2].Name', 'Adhyapana');
SELECT modifiedJson = @JSONData;

Example 5: FOR JSON

This function is used for Exporting SQL Server data as JSON format. This is a
useful function to export SQL data into JSON format. There are two options
available with FOR JSON

 AUTO: As it is nested JSON sub-array is created based on the table


hierarchy.

 PATH: By using this we can define the structure of JSON in a


customized way.
Authors table output

SELECT * FROM Authors FOR JSON AUTO;


SELECT * FROM Authors FOR JSON AUTO, ROOT ('AuthorInfo')
Example 6: OPENJSON

This function is used for importing JSON as String data. We can import JSON
as a text file by using OPENROWSET function and in that the BULK option
should be enabled. It returns a single string field with BulkColumn as its
column name.

Example :

DECLARE @JSON VARCHAR(MAX)


--Syntax to get json data using OPENROWSET
SELECT @JSON = BulkColumn FROM OPENROWSET
(BULK '<pathname\jsonfilename with .json extension>', SINGLE_CLOB) AS j
--To check json valid or not, we are using this ISJSON
SELECT ISJSON(@JSON)
--If ISJSON is true, then display the json data
If (ISJSON(@JSON)=1)
SELECT @JSON AS 'JSON Text'

Note: Even large data also can be placed. As a sample, we showed only a
single row.

SINGLE_BLOB, which reads a file as varbinary(max). SINGLE_NCLOB, which


reads a file as nvarchar(max) -- If the contents are in Non-English text like
Japanese or Chinese etc., data, we need to go in this pattern. We used
SINGLE_CLOB, which reads a file as varchar(max).

It will generate a relational table with its contents from the JSON string. Each
row is created which can be got by iterating through JSON object elements,
OPENJSON can be used to parse the JSON as a text. Let us have a JSON
placed in an external file and its contents are
Select * FROM OPENJSON (@JSON)

SELECT @JSON = BulkColumn


FROM OPENROWSET
(BULK '<location of json file>', SINGLE_CLOB)
AS j
--If the retrieved JSON is a valid one
If (ISJSON(@JSON)=1)
Select * FROM OPENJSON (@JSON)
We can see that for "Strings" key like "authorname" and "skills" got type as 1
and "int" key like "id" and "age" got type as 2. Similarly, for boolean, the
type is 3. For arrays, it is 4 and for object, it is 5. OPENJSON parses only the
root level of the JSON.

In case if the JSON is nested, we need to use Path variables

Select * FROM OPENJSON (@JSON, '$.skills')

We can even make the skillsets as columns of data as

SELECT * FROM OPENJSON (@JSON, '$.skills')


WITH ( skill1 VARCHAR(25), skill2 VARCHAR(25), skill3 VARCHAR(25) )
Saving the rowset into Table: Here the number of columns should match
the count that is present inside with:

SELECT <col1>,<col2>,.... INTO <tablename> FROM OPENJSON (@JSON,


'$.skills')
WITH (skill1 VARCHAR(25),
skill2 VARCHAR(25),
skill3 VARCHAR(25)
)
Example 7:Changing JSON values

There is an option called "JSON_MODIFY" in (Transact-SQL) function is


available to update the value of a property in a JSON string and return the
updated JSON string. Whenever there is a requirement to change JSON text,
we can do that

DECLARE @json NVARCHAR(MAX);


SET @json = '{"Information": {"SchoolDetails": [{"Name": "VidhyaMandhir"},
{"Name": "Chettinad"}, {"Name":"PSSenior"}]}}';
SET @json = JSON_MODIFY(@json, '$.Information.SchoolDetails[2].Name',
'Adhyapana');
SELECT modifiedJson = @json;
Working with JSON in Azure SQL Database

Azure SQL Database has powerful support for handling JSON data, allowing
users to store, query, and manipulate JSON data directly in the database.
While earlier versions of SQL Server and Azure SQL required workarounds like
storing JSON as plain text, Azure SQL now supports native JSON
functionality. This makes working with JSON much more efficient and allows
developers to leverage SQL functions designed specifically for JSON
manipulation.

Native JSON Support in Azure SQL

Azure SQL Database now has native JSON support, which allows you to
directly store JSON data in columns without relying on text-based fields. This
makes working with JSON much easier and more efficient, as you can use
built-in SQL functions to manipulate and query JSON data.

You can use SQL functions like JSON_VALUE(), JSON_QUERY(),


and JSON_MODIFY() to extract, query, and modify JSON data stored in
columns, enabling more robust and performant queries.

For example, you can store a JSON document in a column, and use SQL
queries to extract individual elements or modify values within that JSON
document without needing to parse the data manually.

Working with JSON Functions in Azure SQL

Azure SQL provides several functions to work with JSON data, making it
simple to query, extract, and modify JSON stored in columns.

1. JSON_VALUE(): Extracts a scalar value from a JSON string.


SELECT JSON_VALUE(data, '$.name') AS name
FROM Users;

2. JSON_QUERY(): Extracts a JSON object or array from a JSON string.

SELECT JSON_QUERY(data, '$.address') AS address


FROM Users;

3. JSON_MODIFY(): Modifies the value of a property in a JSON string.

UPDATE Users
SET data = JSON_MODIFY(data, '$.address.city', 'New York')
WHERE UserID = 1;

4. OPENJSON(): Parses a JSON string and returns a result set.

SELECT *
FROM OPENJSON('{"name": "John", "age": 30}')
WITH (name VARCHAR(100), age INT);

These functions allow you to interact with JSON data in SQL just like any
other data type, making it easier to work with JSON-based applications in
Azure SQL Database.

Why Use Native JSON in Azure SQL?

1. Simplified Data Handling: Storing JSON as a native data type


eliminates the need for storing data as text or using external tools for
parsing.

2. Advanced Querying: The native JSON functions allow you to extract,


query, and update specific parts of the JSON document directly in your
SQL queries.

3. Performance: Using native support for JSON ensures better


performance than using string manipulation for JSON data, making
operations faster and more efficient.

4. Seamless Integration: Native JSON support allows seamless


integration between relational and semi-structured data, enabling
flexible, real-time data access without the need for complex schema
transformations.
Conclusion

Handling JSON in SQL Server enables seamless interaction with modern web
applications and NoSQL databases. The ability to store, query, and
manipulate JSON data directly in SQL Server enhances the flexibility and
efficiency of your data management system. SQL Server’s native JSON
functions—such as ISJSON(), JSON_VALUE(), JSON_QUERY(), and
JSON_MODIFY()—make it easier to integrate and work with JSON data without
needing a separate NoSQL system.

Conversion Function in SQL

Data type conversion in SQL ensures accurate query results by allowing


different formats (numbers, text, dates, etc.) to be correctly interpreted and
manipulated. Conversion functions such as TO_CHAR, TO_NUMBER, and
TO_DATE are commonly used for this purpose.

Types of Data Type Conversion

There are two main types of data type conversion in SQL.

 Implicit Data Type Conversion: Automatic conversion of one data


type to another by SQL during query execution.
 Explicit Data Type Conversion: Done by the user when SQL can’t
convert automatically or when precise control is needed.

Implicit Data-Type Conversion

Implicit data type conversion, also known as automatic type casting,


occurs when SQL automatically converts one data type to another without
requiring any intervention from the user.

The DBMS does this whenever it detects a need for the conversion, based on
the context of the operation.

From To

VARCHAR2 or
NUMBER
CHAR

VARCHAR2 or
DATE
CHAR

VARCHAR
DATE
2

VARCHAR
NUMBER
2

Example of Implicit Data Type Conversion


Consider the following example where we retrieve employees whose salary is
greater than 15,000.

create table employees(


employee_id INT PRIMARY KEY ,
first_name VARCHAR(50) ,
salary INT);
INSERT INTO employees(employee_id,first_name,salary)
VALUES
(100,'Steven',24000),
(101,'Neena',17000),
(102,'Lex',17000),
(103,'John',11000),
(104,'Robert',12000),
(105,'Leo',10000);

Query 1: Using a Numeric Value

Here, we want to retrieve the employee_id, first_name, and salary from the
employees table whose salary is greater than 15000 then the query is:

SELECT employee_id,first_name,salary
FROM employees
WHERE salary > 15000;

Output:

In this query

 Columns Selected: It retrieves employee_id, first_name, and salary


from the employees table.

 Filter Condition: It only includes employees whose salary is greater


than 15,000.

Query 2: Using a String Value


In this query, we provide the value '15000' as a string, and SQL automatically
converts it to an integer to match the column data type.

SELECT employee_id,first_name,salary
FROM employees
WHERE salary > '15000';

Output:

In this query:

 Retrieves employee_id, first_name, and salary from the employees


table.

 Filters to include only employees with salary greater than 15,000.

 The string '15000' is automatically converted to a number for


comparison.

Explicit Data-Type Conversion

Explicit data type conversion, or type casting, occurs when a value is


explicitly converted from one data type to another. This is necessary when
SQL cannot automatically determine the correct conversion, or when it is
important to ensure the data is processed in a specific way.
SQL provides several functions for explicit type conversion, including:

 TO_CHAR(): Converts numbers or dates to a string.

 TO_NUMBER(): Converts a string to a numeric type.

 TO_DATE(): Converts a string to a date.

Example of Explicit Data Type Conversion

These conversion functions (TO_CHAR, TO_NUMBER, TO_DATE) ensure


data is stored in one format but can be displayed, compared, or processed in
another as per the requirement.

1. TO_CHAR Function

TO_CHAR function is used to typecast a numeric or date input to a character


type with a format model (optional).

TO_CHAR(expression, 'format_model')

Using the TO_CHAR Function with Dates

TO_CHAR(date, ’format_model’)

The format model:

 Must be enclosed in single quotation marks and is case sensitive

 Can include any valid date format element in the query


 Has an fm element to remove padded blanks or suppress leading zeros

 Is separated from the date value by a comma

Example:

SELECT employee_id, TO_CHAR(hire_date, 'MM/YY') Month_Hired


FROM employees
WHERE last_name = ’Higgins’;

Output :

EMPLOYEE MONTH_HIR
_ID ED

205 06/94

Elements of the Date Format Model

YYYY Full-year in Numbers

YEAR Year spelled out

YY Two-digit value of year

MM Two-digit value for the month

MONT
Full name of the month
H

MON Three Letter abbreviation of the month

D Number of Days in a Week

DY Three-letter abbreviation of the day of


YYYY Full-year in Numbers

the week

DAY Full Name of the Day

DD Numeric day of the month

Date Format Elements - Time Formats


Use the formats listed in the following tables to display time information and
literals and to change numerals to spelled numbers.

ELEMENT DESCRIPTION

AM or PM Meridian indicator

A.M. or P.M. Meridian indicator with periods

HH or HH12 or Hour of day, or hour (1-12), or


HH24 hour (0-23)

MI Minute 0-59

SS Second 0-59

SSSSS Second past Mid Night 0-86399

Other Formats
ELEME
NT DESCRIPTION

Punctuation is reproduced in the


/.,
result

"of The quoted string is reproduced in


the" the result

Specifying Suffixes to Influence Number Display

ELEMENT DESCRIPTION

TH Ordinal Number (for example DDTH for 4TH

SP Spelled outnumber (for example DDSP for FOUR

SPTH or spelled out ordinal numbers (for example DDSPTH


THSP for FOURTH

Example :

SELECT last_name,
TO_CHAR(hire_date, ’fmDD Month YYYY’)
AS HIREDATE
FROM employees;

Output :

LASTNA
ME HIREDATE

25 January
Austin
2005
LASTNA
ME HIREDATE

Shubha
20 June 2004
m

15 January
Nishant
1999

Ankit 15 July 1995

Vanshik 5 August
a 2004

Kusum 10 June 1994

11 March
Faviet
2005

King 9 April 1996

2. Using the TO_CHAR Function with Numbers

TO_CHAR(number, ’format_model’)

These are some of the format elements you can use with the TO_CHAR
function to display a number value as a character :

9 Represent a number

0 Forces a zero to be displayed


9 Represent a number

$ places a floating dollar sign

It uses the floating local currency


L
symbol

. Print a decimal point

, Prints a Thousand indicator

Example :

SELECT TO_CHAR(salary, ’$99,999.00’) SALARY


FROM employees
WHERE last_name = ’Ernst’;

Output :

SALA
RY

$500
0

Using the TO_NUMBER and TO_DATE Functions :

Convert a character string to a number format using


the TO_NUMBER function :

TO_NUMBER(char[, ’format_model’])

Convert a character string to a date format using the TO_DATE function:

TO_DATE(char[, ’format_model’])

These functions have an fx modifier. This modifier specifies the exact


matching for the character argument and date format model of
a TO_DATE function.

Example :

SELECT last_name, hire_date


FROM employees
WHERE hire_date = TO_DATE(’May 24, 1999’, ’fxMonth DD, YYYY’);

Output :

LASTNA
ME HIREDATE

24-MAY-
Kumar
1999

SQL Data Types

Last Updated : 08 Aug, 2025

In SQL, each column must be assigned a data type that defines the kind of
data it can store, such as integers, dates, text, or binary values. Choosing the
correct data type is crucial for data integrity, query performance and efficient
indexing.

Benefits of using the right data type:

 Memory-efficient storage

 Accurate operations (e.g., calculations, sorting)

 Consistency in stored values


 Validation of input data

SQL data types are broadly categorized into several groups:

1. Numeric Data Types

Numeric data types are fundamental to database design and are used to
store numbers, whether they are integers, decimals or floating-point
numbers. These data types allow for mathematical operations like addition,
subtraction, multiplication and division, which makes them essential for
managing financial, scientific and analytical data.

Exact Numeric Datatype

Exact numeric types are used when precise numeric values are needed, such
as for financial data, quantities, and counts. Some common exact numeric
types include:

Data Type Description Range

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


Data Type Description Range

9,223,372,036,854,775,807

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

SMALLINT Small integers -32,768 to 32,767

TINYINT Very small integers 0 to 255

Exact fixed-point
DECIMAL numbers (e.g., for -10^38 + 1 to 10^38 - 1
financial values)

Similar to DECIMAL,
NUMERIC -10^38 + 1 to 10^38 - 1
used for precision data

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


MONEY
values 922,337,203,685,477.5807

SMALLMON Smaller monetary


-214,748.3648 to 214,748.3647
EY values

Approximate Numeric Datatype

These types are used to store approximate values, such as scientific


measurements or large ranges of data that don't need exact precision.
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

2. Character and String Data Types

Character data types are used to store text or character-based data. The
choice between fixed-length and variable-length data types depends on the
nature of your data.

Data Type Description

The maximum length of 8000 characters. (Fixed-Length


Char
non-Unicode Characters)

The maximum length of 8000 characters. (Variable-Length


Varchar
non-Unicode Characters)

Varchar(m The maximum length of 2^31 - 1 characters(SQL Server


ax) 2005 only). (Variable Length non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable


Text
Length non-Unicode data)

Unicode Character String Data Types

Unicode data types are used to store characters from any language,
supporting a wider variety of characters. These are given in below table.
Data Type Description

The maximum length of 4000 characters(Fixed-Length


Nchar
Unicode Characters)

The maximum length of 4000 characters.(Variable-Length


Nvarchar
Unicode Characters)

Nvarchar(m The maximum length of 2^31 - 1 characters(SQL Server


ax) 2005 only). (Variable Length Unicode data)

3. Date and Time Data Type

SQL provides several data types for storing date and time information. They
are essential for managing timestamps, events and time-based queries.
These are given in the below table.

Data Storage
Type Description Size

DATE stores the data of date (year, month, day) 3 Bytes

TIME stores the data of time (hour, minute,second) 3 Bytes

DATETI store both the data and time (year, month, day,
8 Bytes
ME hour, minute, second)

4. Binary Data Types in SQL

Binary data types are used to store binary data such as images, videos or
other file types. These include:
Data
Type Description Max Length

Binary Fixed-length binary data. 8000 bytes

VarBina Variable-length binary


8000 bytes
ry data.

Stores binary data as 2,147,483,647


Image
images. bytes

5. Boolean Data Type in SQL

The BOOLEAN data types are used to store logical values, typically TRUE or
FALSE. It is commonly used for flag fields or binary conditions.

6. Special Data Types

SQL also supports some specialized data types for advanced use cases:

 XML Data Type: Used to store XML data and manipulate XML
structures in the database

 Spatial Data Type (Geometry): stores planar spatial data, such as


points, lines, and polygons, in a database table.
SQL LTRIM() Function

The SQL LTRIM() function is an essential tool used in data cleaning and
manipulation tasks. This function helps remove unwanted leading spaces
or specific characters from the left side of a string or string expression. It's
commonly used to tidy up data by eliminating unnecessary spaces or
characters that may have been inadvertently added during data entry.

In this guide, we’ll provide an in-depth look at the SQL LTRIM() function, its
syntax, how it works, and examples of common use cases.

LTRIM() Function in SQL

The LTRIM() function in SQL is an inbuilt string function that is used to


remove the leading empty spaces from the left side of our data. The LTRIM
function can also be used to remove a specific character or substring from
the left side of the string.

The LTRIM function is primarily used for data cleaning purposes where the
data administrator uses this function to remove unnecessary characters from
the database in one go.
Syntax:

SQL LTRIM function syntax is:

LTRIM(Input_String, [Trim_Characters])

Parameters

 Input_String: String from which you want to remove leading spaces.

 Trim_Characters: [optional] specified characters you want to remove.

Note: If we don't specify any characters to remove, the LTRIM function


removes the white spaces for data cleaning and manipulation in SQL.

SQL LTRIM function Working

The following diagram shows how the SQL LTRIM function affects strings in
the table.

Workflow of LTRIM function

The function LTRIM in SQL analyzes the input string from the left side and
removes any empty spaces or the mentioned character found on that string.
The function does not alter the original string, it returns a new string where
the leading whitespaces are removed.

This function doesn't deal with whitespaces present between the strings. For
example if the string ' JOHN' was written as ' JO HN' then only the leading
white spaces on the left side will be removed by this function and the spaces
in between will remain as they were earlier.

SQL LTRIM Function Examples

Now let us see some examples of LTRIM function in different use cases to
understand it's working better:

Example 1: Remove Leading White Spaces Using LTRIM function

In this example, we will remove the leading white spaces from a string using
SQL LTRIM function.
Query:

Select LTRIM(' GeeksforGeeks.') AS trimmedString;

Output:

Output

Example 2: Remove Specific Characters Using LTRIM Function

In this example, we will remove specific characters using LTRIM function.

Query:

SELECT LTRIM('----GeeksforGeeks', '-') AS TrimmedString;

Output:

Out
put

Example 3: Remove a Substring from a String Using LTRIM Function

In this example, we will remove a substring from a string using the LTRIM
function.

Query:
SELECT LTRIM('GeeksforGeeks', 'Geeks') AS TrimmedString;

Output:

O
utput

Example 4: Use LTRIM on a Table Column

Let us consider the following table where the names of the users are stored
with whitespaces. If we want to remove these whitespaces then we can use
the LTRIM in SQL to remove them in one go.

Input Table

To create this table, write the following SQL query:

CREATE TABLE Names (

Name VARCHAR(45)

);

INSERT INTO Names (Name) VALUES


(' Alice'), (' Bob'), (' Charlie'), (' David'), (' Eve');

Now to remove whitespace from this column, we can use the SQL query:

SELECT LTRIM(name) FROM users AS TrimmedNames;

Output:

Output Table

After executing the LTRIM function on the column of the above table, you can
observe that the leading whitespaces are removed in one go from all the
records of the table.

Important Points About SQL LTRIM Function

 SQL LTRIM is useful inbuilt function which can be used to remove the
whitespaces on left our data in the databases.

 Not only whitespaces it can also remove a specific character or a


subtring from the data.

 LTRIM function in SQL can be used on entire column/field of table to


remove whitespace.

 LTRIM function only works for the left side of data, and will not affect
the middle or right side of data.

Conclusion

The SQL LTRIM() function is an invaluable tool for data cleaning and string
manipulation. It helps remove unwanted leading spaces or characters,
ensuring that your data remains clean and consistent. Whether you’re
working with user input, cleaning up data from external sources, or preparing
data for analysis, the LTRIM() function can make your tasks easier and more
efficient.
SQL UPPER() Function
In SQL, the UPPER() function is one of the most commonly used string
functions. It is used to convert all characters in a given string to uppercase.
Whether we are dealing with textual data that requires uniform formatting or
need to compare strings without case sensitivity, the UPPER() function comes
in handy.

In this article, we will cover the SQL UPPER() function, including its syntax,
examples, and best practices for use.

UPPER() Function in SQL

The UPPER function in SQL is an in-built function that changes lowercase


characters or strings to capital cases. Certain characters like integers (0-9)
or special characters like ("@", "-" "/", "&" etc.) remain unchanged in the
result.

It is used to display the output in CAPITAL CASE and is supported by all


major SQL-based DBMSs.

Note: UPPER and UCASE functions perform the same operation on strings.
In older versions of SQL, some databases (like Db2 DBMS)used the UCASE
function, while others used the UPPER function. Now both the functions are
supported by all major databases.
The UPPER function is supported in SQL Server (starting with 2008), Azure
SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse, MySQL
4.0, Oracle, DB2, and all other major Database systems.

Syntax:

SQL UPPER function syntax is:

UPPER(input_text);

OR

UPPER(column_name);

Examples of SQL UPPER() Function

Let's look at the examples of UPPER() function in SQL. Check the SQL
UPPER function with examples to understand it better.

First, let's create a demo database and table on which we will use the UPPER
function.

We will be using the following table in the examples:

ID NAME

12@tEsla Elon

X Musk

Microsoft Bill

Example 1: Convert Character Literal to Uppercase Using SQL Upper


Function

In this example, we are printing the x value as it is in first column, and in the
second column we are printing the ID value after applying the UPPER
function, and the UPPER function converted "x" into "X".

Query:

SELECT "x" as "BEFORE UPPER() Function" , UPPER("x") as "AFTER


UPPER() Function";
Output:

Converting Character Literal to Capital Case Using UPPER() function.

Example 2: Convert string to Uppercase using SQL UPPER Function

IIn this example, in the first column, we are printing the "Microsoft" word as
it is, and in the second column we are printing the "Microsoft" value after
applying the UPPER() function, and the UPPER function converted "Microsoft"
into "MICROSOFT".

Query:

SELECT "Microsoft" as "BEFORE UPPER() Function" , UPPER("Microsoft")


as "AFTER UPPER() Function";

Output:

Converting Character Literal to Capital Case Using UPPER() function.


Example 3: Using UPPER Function on String Consisting of Special
Characters, Integers, and Alphabets

In this example, in the first column, we are printing the ID value as it is, and
in the second column we are printing the ID value after applying the UPPER
function, and "12@tEsla" is converted to "12@TESLA". The special
characters and Numerical characters remained the same, only the alphabets
are converted into capital case.

SELECT "12@tEsla" as "BEFORE UPPER() Function" , UPPER("12@tEsla")


as "AFTER UPPER() Function" ;

Output:

Converting a String with Numerical characters and Special Characters into


Capital Case using UPPER() function.

Example 4: Using SQL UPPER function on a Column

In this example, we passed a column name ID as an argument to the UPPER()


function. It converts all the values present in the ID column and outputs. In
the first column, we can see the ID values before using the UPPER() function.
In the second column, We can see all the alphabetic characters get
converted into Capital Cases. Integer and special characters remain as it is.
As we can see, "x", "Microsoft", and "12@tEsla" are converted into "X",
"MICROSOFT", and "12@TESLA" respectively.

Query:

SELECT ID as "BEFORE UPPER() Function" , UPPER(ID) as "AFTER


UPPER() Function" FROM GFG_UPPER_DEMO;

Output:
Passing a column name to the UPPER() function and Converting it to Capital
Case.

Important Points About SQL UPPER() Function

 UPPER()function in SQL allows us to convert the string text into


uppercase.

 It takes only one parameter and converts the entire string into upper
case.

 It is similar to theUCASE() function.

 Special Characters like "@", "%", "+" etc. and numerical characters
remain unchanged, only the lowercase alphabetical letters get
transformed into uppercase.

Conclusion

The SQL UPPER() function is a versatile tool for converting string data into
uppercase. It is primarily used to ensure uniformity in data presentation and
to perform case-insensitive comparisons. By using UPPER() in your queries,
we can clean up inconsistent case usage in our database, standardize
outputs, and simplify comparisons.

From simple string manipulations to case-insensitive searches, the UPPER()


function provides an efficient way to handle text data in SQL. By following
best practices and understanding how to use this function effectively, you
can make your database operations more consistent and reliable.
SQL RTRIM() Function

SQL RTRIM function is a string function that removes spaces from the
right side of a character or string. RTRIM or Right Trim function is used in
data cleaning and manipulation in SQL.

In this example, we will learn the basics of the RTRIM function, and learn how
it works with examples of different use cases.

RTRIM() Function in SQL

SQL RTRIM() function allows us to remove the trailing empty spaces from the
string. Trailing white spaces are the redundant white spaces present at
the right end of the string. For example, In "GFG ", there are 5 empty white
spaces at the right end of the string.

If there are redundant white spaces at the beginning of the string. For
example: " GFG", there are 5 whitespaces at the beginning of the string",
these are called leading whitespace.

RTRIM function works in: MySQL 4.0, SQL Server (starting with 2008), Azure
SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse, Oracle,
and all other major database systems.

Syntax:

RTRIM( input_text);

OR

RTRIM(column_name) AS trimmed_name
FROM table_name;

Examples of SQL RTRIM Function

Let's see some examples of RTRIM function in SQL, and understand it's
working with examples of different use cases.

Example 1: Using RTRIM Function to Remove Trailing Spaces from a


String
The RTRIM function in SQL is used to remove trailing spaces from a string.
Here are a few examples to illustrate its usage:

SELECT (' Geeks for Geeks ') as "Before RTRIM()",

RTRIM(' Geeks for Geeks ') as "After RTRIM()";

Output:

As we can see, the whitespaces in the right end of the string are removed,
and the left side spaces remain as it is.

RTRIM() function

Example 2: Using RTRIM Function on Table Column

Suppose we have a table named Students with id and name. RTRIM()


function will trim the trailing spaces in the given column.

First, we create a table GFG, with following commands.

CREATE TABLE GFG(

id integer,

name varchar(40));

INSERT INTO GFG VALUES

(1,"kiran "),

(2," navya ");

Output:
Output of
GFG TABLE.

Now we will use RTRIM function on column name.

SELECT name as "Before RTRIM()", RTRIM(name) as "AFTER RTRIM()" from


gfg;

Output:

The above query results in two columns, the first column represents the
name column before using the RTRIM() function and the second column
represents the values of name column after applying the RTRIM() function.
As we can see, the trailing spaces are removed and width of the second
column "AFTER TRIM()" is shortened.

Output after applying RTRIM() function.


Example 3: Using RTRIM Function With a Variable

DELIMITER //

CREATE PROCEDURE RTRIM_Example()

BEGIN

-- Declare a variable

DECLARE input_string VARCHAR(15);

-- Assign a value to the variable

SET input_string = 'Hello ';

-- Use the variable in a query

SELECT CONCAT(RTRIM(input_string), ' World') AS result;

END //

DELIMITER ;

-- Call the stored procedure

CALL RTRIM_Example();

Output:

We declare a variable in stored procedure and assign it a value. We


changed delimiter to "//" to consider procedure as one statement. Then we
use CONCAT function to concatenate declared variable and "World".We have
also use RTRIM function on declare variable in CONCAT function and As we
can see in results, RTRIM method removed whitespace s from the declared
variable.
Key Takeaways About SQL RTRIM Function

 RTRIM() function removes the trailing spaces in the given string or


removes trailing spaces for all the values present in a specific column
in the table.

 It allows only one parameter i.e. either a string or a column having


values of string type.

 It is supported in all major database systems.

 When used in SELECT statements, the function improves the


readability of results by eliminating unnecessary white spaces.

Conclusion

The SQL RTRIM() function is a valuable tool for removing trailing spaces in
strings, making it essential for data cleaning and preparation tasks. By
improving the readability and consistency of your data, it enhances both
data integrity and query performance.

With the practical examples provided, you now understand how to use the
RTRIM() function in various scenarios, whether it's cleaning up text data from
a column, using it in stored procedures, or combining it with other string
functions. When applied thoughtfully, the RTRIM() function can help you
maintain a clean, consistent database that’s easier to work with and analyze.
Chapter – X
SQL Views
Views simplify complex queries and improve security by controlling data
access. Views also act like a helpful security guard, keeping the most
sensitive information in the back room, while still allowing access to what's
needed.

 CREATE VIEW

 UPDATE VIEW

 RENAME VIEW

 DROP VIEW

SQL CREATE VIEW Statement


The SQL CREATE VIEW statement is the central idea used to create a virtual
table that does not store data itself but rather provides a dynamic
representation of data obtained from one or more underlying tables. This
arrangement lets users simplify intricate queries, improve security, and
make abstracted data structures easy to access and manipulate.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

In the above Syntax:

 CREATE VIEW view_name: This part of the statement specifies that a


new view with the given name (view_name) will be created.

 AS: This keyword is used to indicate that the following SELECT


statement will define the structure and data for the view.
 SELECT column1, column2, ...: Here, you specify the columns that
you want the view to include. These can be columns from one or more
tables or even expressions derived from those columns.

 FROM table_name: This part of the statement specifies the table or


tables whose data will populate your view.

 WHERE condition: Optionally you may add a WHERE clause so as to


give conditions under which data retrieved by this view should be
filtered by. This is very helpful when creating views with subsets of
data.

Examples of SQL CREATE VIEW Statement

The CREATE VIEW statement in SQL is used to create a virtual table based on
the result of a query. Views help simplify complex queries and enhance
security by restricting access to specific columns or rows.

Example 1: Creating a Simple View

Consider the table products having three columns product_id, product_name,


and price. Suppose we have to create a view that contains only products
whose prices are greater than $50.

Query:

CREATE VIEW expensive_products AS


SELECT product_id, product_name, price
FROM products
WHERE price > 100;

products Table:

product_ product_na pric


id me e

1 Laptop 800

2 smartphone 600

3 Tablet 120
product_ product_na pric
id me e

4 Headphone 80

5 Monitor 200

expensive_products View:

product_ product_na pric


id me e

1 Laptop 800

2 Smartphone 600

3 Tablet 120

5 Monitor 200

Explanation:

 We develop a view called expensive_products.

 The view obtains columns product_id, product_name, and price from


table products.

 We filter it so that it only includes rows with prices bigger than $100.

Example 2: Creating a Joined View

Assume that we have two tables employees and departments. We need to


build a view combining information about both tables in order to show each
employee’s name along with their department name:

Query:
CREATE VIEW employee_department_info AS
SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;

Employees table:

employee first_na last_na department


_id me me _id

1 John Doe 101

2 Jane Smith 102

3 David Lee 101

Departments table:

department department_n
_id ame

101 Sales

102 Marketting

employee_department_info view:

employee first_na last_na department_n


_id me me ame

1 John Doe Sales

2 Jane Smith Marketing


employee first_na last_na department_n
_id me me ame

3 David Lee Sales

Explanation:

 A view named employee_department_info is created by us.

 Columns employee_id, first_name, last_name from employees table


along with department_name from departments table are selected by
this view.

 An inner join between employees and departments on department_id


is performed to get department name for each employee.

Now when querying the employee_department_info view we shall have a list


of employees together with their corresponding department names.
SQL UPDATE VIEW

SQL Views are virtual tables that represent the result of a SELECT query.
They simplify complex queries and present data in a more understandable
format. While views don't store data themselves, they provide a convenient
way to access and manipulate data without modifying the underlying tables

How to Create a View in SQL

Creating a view in SQL is straightforward. The CREATE VIEW command is


used to define a view. The view can be based on a simple or complex query.
This SQL command defines a view by selecting specific columns from a table
or joining multiple tables based on certain conditions.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

How to Update a View in SQL

Updating a view in SQL means modifying the data it shows. However, not all
views can be updated instantly. Views with complex queries, like those
with joins, subqueries, or aggregate functions, may not be directly
updatable.

There are two ways to update a view: using the UPDATE keyword or using
the CREATE OR REPLACE keyword
 The UPDATE keyword is used to update the view without changing the
schema of the table. Update keyword will be used to update the values
of the attributes.

 CREATE OR REPLACE keyword is used to update the view where the


schema of the the view can also be changed. As the name suggests, if
the view is not present it will get created. If view is present then view
will get Replaced.

Examples of Updating a View

To understand How to Create and Update Views we need a table on which we


will perform various operations and queries. Here we will consider a table
called Student which contains Roll_No , name, Marks , and Subject as
Columns.

Roll_n Nam Mar Subje


o e ks ct

1 Kartik 70 math

scienc
Yash 80
2 e

3 Pratik 45 math

Adity scienc
75
4 a e

Prana
48 math
5 v

1. Updating View Using IN Operator

This method allows updating the values in the view using


the UPDATE keyword. We will set specific conditions to update data in the
view. The query for updating the view is as below.
Query:

UPDATE view1
SET Marks=50
where Roll_no in (3,5);

Output:

Roll_n Mar Subje


o ks ct

1 70 Math

Scienc
80
2 e

3 50 Math

Scienc
75
4 e

5 50 Math

Explanation:

This query updates the view1 where the Marks will be set to 50 for the
students with Roll_No 3 and 5.

2. Updating View Using Arithmetic Operation

We can update the view using arithmetic operations also. Arithmetic


operations are used to change the values of attributes present in the view.
Here we are updating the view. Marks will be updated using the Marks*0.95
formula. So query for the given condition will be as below.

Query:

UPDATE view1 SET Marks = Marks*0.95;

Output:
Roll_n Mar Subje
o ks ct

1 67 Math

Scienc
76
2 e

3 48 Math

Scienc
71
4 e

5 48 Math

Explanation:

In this query, the Marks for all students in view1 will be updated to 95% of
their current values, effectively applying a scaling factor.

3. Updating View Using Aggregate Function

We can also update the view using the aggregate function. As we are using
the aggregate function, we need to change the schema/ structure of the
view. So we will CREATE OR REPLACE VIEW to update the view. The query for
updating the view using the aggregate function is as below.

Query:

CREATE OR REPLACE VIEW view1 AS


SELECT Subject, SUM(Marks) AS TotalMarks
FROM Student
GROUP BY Subject;

Output:
Subje TotalMar
ct ks

math 170

scienc
155
e

Explanation:

This query creates or replaces view1 with a new definition that calculates
the total marks (SUM(Marks)) for each subject. The view will now display
total marks grouped by subject.

4. Updating View Using Subqueries

The view can be updated using nestes or subqueries. When there is a need
for more than a query for updating the view, we can update the view. Here
we are using the CREATE OR REPLACE keyword as we need to change the
structure of view. The query for updating the view which is using subqueries
is as below.

Query:

CREATE OR REPLACE VIEW view1 AS


SELECT Name,
(SELECT SUM(Marks) FROM Student s WHERE s.Subject =
Student.Subject) AS TotalMarks
FROM Student;

Output:
Nam TotalMar
e ks

Karti
170
k

Yash 155

Prati
170
k

Adity
155
a

Pran
170
av

Explanation:

Here we created the new attribute TotalMarks which will have a sum of marks
of the respective subject and the marks will get assigned to the respective
student of that subject. for example, Kartik has the subject math so he will
get assigned the sum of scores of all student who has math subject i.e. 170.

SQL - Rename View

Last Updated : 23 Jul, 2025

In relational databases, views are essential tools used to simplify complex


queries, enhance data security, and improve overall database management.
However, as our database evolves, the need to rename existing views may
arise. This renaming process helps maintain consistency, improves clarity,
and ensures that our database schema remains organized and aligned with
business requirements.

Why Rename a View in SQL?

 Reflecting Updated Business Requirements: As business logic or


data structures change, renaming views to match the updated
terminology ensures clarity and relevance.

 Improving Database Schema Organization: Renaming views can


help maintain consistency and improve the organization of
the database schema, which is critical for efficient data retrieval and
management.

 Preserving Dependencies: Renaming a view preserves all its


dependencies (like permissions, related views, and stored procedures),
making it a safer option than dropping and recreating the view.

How to Rename a View in SQL

In SQL, there is no direct RENAME VIEW command. However, we can rename


a view by following these two common methods:

1. Using sp_rename in SQL Server.

2. Using the CREATE OR REPLACE VIEW command to create a new


view with the desired name and drop the old one in databases
like MySQL, PostgreSQL, and others.

Renaming a View in SQL Server

The SQL RENAME VIEW command is used to change the name of existing
view in a database. This command ensures that the view can be renamed
without affecting the view structure, dependent objects, or data such as
other views, user permissions, and stored procedures.

Syntax

EXEC sp_rename 'old_view_name', 'new_view_name';

Key Terms

 sp_rename system stored procedure is used to rename a view in SQL.

 old_view_name denotes the current name of the view which is you


want to rename the view in SQL.
 new_view_name denotes the new name of the view.

Example 1: Renaming a View in SQL Server

Let us use the sample Sales table given below, which contains two
columns: product_id and quantity to create a view and then rename it.
The product_id represents different products, and the quantity represents
the number of units sold for each product.

Sales Table

1. Create the sales_report View

The view sales_report aggregates the total quantity of each product from
the Sales table.

CREATE VIEW sales_report AS


SELECT product_id, SUM(quantity) AS total_quantity
FROM Sales
GROUP BY product_id;

Explanation:

This view calculates the total quantity for each product (product_id) by
summing the quantity values. It simplifies querying the aggregated data.

2. Rename the sales_report View

We rename the sales_report view to monthly_sales_report using


the sp_rename stored procedure in SQL Server.

EXEC sp_rename 'sales_report', 'monthly_sales_report';

Explanation:
In this step, we renamed the view
from sales_report to monthly_sales_report. The operation does not affect
the underlying data in the Sales table or any other dependent objects like
stored procedures.

3. Verification

To verify that the view was successfully renamed, we query the newly named
view.

select * from monthly_sales_report;

Output

product_ total_quan
id tity

1 100

2 150

3 100

Explanation:

The output shows the total quantity of products, as calculated by


the monthly_sales_report view. The view has been successfully renamed
and continues to function as expected, displaying aggregated data from
the Sales table.

Renaming a View in MySQL and Other Databases

In MySQL, and many other database systems, there is no direct command


for renaming a view. Instead, the recommended approach varies across
different database systems. Below are the methods for renaming views in
MySQL and PostgreSQL:

1. Renaming a View in MySQL

In MySQL, the RENAME TABLE command is used to rename a view. This


command renames the view directly without having to recreate it or drop the
old one. You can use the following query:
RENAME TABLE old_view_name TO new_view_name;

2. Renaming a View in PostgreSQL

In PostgreSQL, you can use the ALTER VIEW command to rename a view. This
is the preferred method in PostgreSQL for renaming views directly.

ALTER VIEW old_view_name RENAME TO new_view_name;

Example 2: Renaming a View in MySQL

Let us use the employees table, which contains columns id, name,
and department_id. This data will be used to create and manipulate
views based on employees belonging to specific departments.

department
id name _id

1 John Doe 1

2 Jane Smith 2

Mike
3 1
Johnson

Emily
4 3
Davis

1. Create the it_employees View

We will create a view named it_employees to list all employees who belong
to department 1 (IT department).

CREATE VIEW it_employees AS


SELECT name
FROM employees
WHERE department_id = 1;

Explanation:
This query creates the it_employees view, which retrieves the name of
employees in the IT department (where department_id is 1).

2. Rename the it_employees View

In MySQL, renaming a view is done using the RENAME TABLE command:

RENAME TABLE it_employees to employee;

3. Drop the Old it_employees View

Since we now have the employee view with the new name, we can safely
drop the old view if desired.

DROP VIEW it_employees;

4. Verification

To confirm the renaming was successful, we query the newly renamed view
employee.

select * from employee;

Output

name

John Doe

Mike
Johnson

Explanation:

The output shows the employees from department 1 (IT department)


according to the employees table, and confirms that the renaming
operation was successful. The view now displays the correct data under the
new name employee.

Purpose and Significance

Renaming views is essential for maintaining a well-


organized and understandable database schema. Here are some key
benefits:
1. Adaptability: Allow for the renaming of the views to better reflect the
current purpose or data content without the need to drop and
recreate them.

2. Consistency: It helps in aligning the view names with the updated


naming conventions or business terminologies.

3. Clarity: Enhance the readability and understanding of database


schema by providing more descriptive and meaningful names.

4. Preservation of Dependencies: Make sure that all dependencies like


other views, stored procedures, and user permissions, remain
intact, thus avoiding disruptions in database functionalities.

5. Efficiency: It will save time and effort compared


to dropping and recreating the view which requires the additional
steps to reassign permissions and recreate the dependencies.

Conclusion

In Conclusion, renaming views in SQL is a straightforward operation that can


greatly enhance the clarity and maintainability of the database schema.
Whether we are aligning view names with the naming conventions and
updating the views to reflect changes in the business requirements or simply
improving the organization of database objects understanding how to
rename views is essential for effective database management.

SQL - DROP View


SQL Views provide a powerful way to simplify complex queries and
present data in a more understandable format. However, there may be times
when we need to remove a view from our database schema. In SQL,
deleting a view is straightforward using the DROP VIEW command.

In this article, we will explain the process of deleting views in SQL, why
and when to remove a view, and provide examples and outputs to
demonstrate how to effectively manage views in our database.

SQL DROP VIEW Command

In SQL, there is no direct DELETE VIEW command. To remove a view from


a database, you must use the DROP VIEW command. This command deletes
the view definition from the database. However, DROP VIEW does not affect
any underlying data in the base tables that the view was created from. It
only removes the virtual table (view) from the database schema.

Syntax:

DROP VIEW view_name;

Creating Views

Consider the following EMPLOYEES table that stores data about employees.
This table contains important information such as employee
names, positions, salaries, and departments. We can create views to
simplify the querying process and present data in a more structured way,
focusing on specific subsets of the data.

Employees Table

1. View for High Salary Employees


The HighSalaryEmployees view filters the EMPLOYEES table to include
only those employees with a salary greater than 50,000. The query retrieves
columns such as ID, Name, Position, Salary, and Department, and returns
records for employees who meet the salary condition.

Query:

CREATE VIEW HighSalaryEmployees AS


SELECT * FROM EMPLOYEES WHERE Salary > 50000;

Output

Nam Sala Departm


ID e Position ry ent

Roha 5700
1 Manager HR
n 0

Senior 6000
3 Arpit IT
Developer 0

2. View for Developers

The Developers view filters the EMPLOYEES table to retrieve employees


whose Position contains the word "Developer". The view returns
the Name, Position, and Department of employees who have roles related
to development within the IT department.

Query:

CREATE VIEW Developers AS


SELECT Name, Position, Department FROM EMPLOYEES WHERE Position LIKE
'%Developer%';

Output
Nam Departm
e Position ent

Arya
Developer IT
n

Senior
Arpit IT
Developer

Tara Developer IT

3. View for Employees in IT Department

The ITEmployees view filters the EMPLOYEES table to include only those
employees who belong to the IT department. It retrieves all columns
(ID, Name, Position, Salary, and Department) for employees working in the IT
department, making it easier to query and manage IT-related employee
data.

Query:

CREATE VIEW ITEmployees AS


SELECT * FROM EMPLOYEES WHERE Department = 'IT';

Output

Nam Sala Departm


ID e Position ry ent

Arya 4500
2 Developer IT
n 0

Senior 6000
3 Arpit IT
Developer 0

5 Tara Developer 5500 IT


Nam Sala Departm
ID e Position ry ent

To check the Created Views

SELECT TABLE_SCHEMA,
EMPLOYEES FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA='GFG';

To confirm that our views are created we can use the query mentioned above
it will show us so our the views that we have created in form of table
something like this:

TABLE_SCHE
MA EMPLOYEES

HighSalaryEmploy
GFG
ees

GFG GOOD_EMPLOYEE

GFG TOP_EMPLOYEE

Deleting a View

Once we no longer need a view, we can delete it using the DROP


VIEW command. For example, let’s delete
the HighSalaryEmployees and ITEmployees views.

DROP VIEW HighSalaryEmployees;


DROP VIEW TOP_EMPLOYEE;

After executing this, these views will no longer exist in the database schema.
We can confirm by querying the INFORMATION_SCHEMA.VIEWS table to see
the remaining views:
SELECT TABLE_SCHEMA, EMPLOYEES
FROM
INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA='GFG';

Output:

TABLE_SCHE
MA EMPLOYEES

GOOD_EMPLOY
GFG
EE

Explanation:

This query retrieves information about views from the


INFORMATION_SCHEMA.VIEWS table for a specific TABLE_SCHEMA ('GFG'). It
selects the TABLE_SCHEMA and EMPLOYEES columns from the VIEWS table,
filtering the results to only include views from the 'GFG' schema.

Verifying the Deletion

To confirm the views have been successfully deleted, we can run the
following query again. The HighSalaryEmployees and ITEmployees views
should no longer appear in the result.

Query:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA = 'your_schema_name';

Explanation:

The above query retrieves all the views in the specified schema. After
deleting the views, only the Developers view will remain.

Why and When Should You Use DROP VIEW?

1. Outdated Views: If a view is no longer relevant because the


underlying data structure has changed or the view is based on
obsolete requirements, it’s a good idea to drop it to keep the database
clean.
2. Performance Optimization: Removing unnecessary views can help
optimize query performance and maintain database health.

3. Security: Views may sometimes expose sensitive data or provide too


much access. Dropping a view when it's no longer needed helps
maintain the principle of least privilege.

4. Database Maintenance: As our database grows, managing views


becomes critical. Keeping only the necessary views can improve
overall maintainability.

Conclusion

The DROP VIEW command in SQL is a simple and effective way to remove
views that are no longer needed in the database schema. It is essential for
maintaining a clean and efficient database by
eliminating outdated or unused views. Understanding when to use DROP
VIEW helps optimize database performance, reduce clutter, and
enhance security. By mastering the DROP VIEW command, we ensure that
our database remains organized and easy to manage, ensuring only relevant
views are present and that we comply with data access control best
practices.

Chapter- XI

Ajay

SQL Indexes

Improve query performance by creating indexes that speed up data retrieval.

 Indexes

 Create Index

 Drop Index

 Show Indexes
 Unique Index

 Clustered Index vs Non-Clustered Index

SQL Indexes

Last Updated : 28 Aug, 2025

Indexes in SQL are special data structures that improve speed of data
retrieval operations. They work like a quick lookup table for the database
instead of scanning the entire table row by row, database can use the index
to directly locate the required rows.

They play a crucial role in improving performance and efficiency in databases


as it:

 Speed up queries (SELECT, JOIN, WHERE, ORDER BY).

 Reduce disk I/O and improve efficiency in large tables.

 Ensure data integrity with unique indexes.

 Must be used wisely as too many indexes can slow down INSERT,
UPDATE and DELETE.

Note: Primary Key and Unique constraints automatically create indexes.

1. Creating an Index

There are 3 main ways to create an index in SQL. Let’s look at them one by
one.

1.1. Single Column Indexes

A single-column index is created on just one column. It’s the most basic type
of index and helps speed up queries when you frequently search, filter or sort
by that column.

Syntax:

CREATE INDEX index ON TABLE column;

Let’s create a simple Sales table to understand Indexes:


CREATE TABLE Sales (
sale_id INT PRIMARY KEY,
product_id INT,
quantity INT,
customer_id INT );

INSERT INTO Sales (sale_id, product_id, quantity, customer_id) VALUES


(1, 101, 5, 201),
(2, 102, 2, 202),
(3, 101, 3, 203),
(4, 103, 1, 204),
(5, 104, 7, 205);

sale_i product_ quanti customer


d id ty _id

1 101 5 201

2 102 2 202

3 101 3 203

4 103 1 204

5 104 7 205

Example:

CREATE INDEX idx_product_id ON Sales (product_id);

Explanation: This creates an index named idx_product_id on the product_id


column. Output is usually a confirmation message.

1.2. Multi Column Indexes

A multi-column index is created on two or more columns. It improves


performance when queries filter or join based on multiple columns together.
Syntax:

CREATE INDEX index ON TABLE (column1, column2,.....);

Example:

CREATE INDEX idx_product_quantity ON Sales (product_id, quantity);

Explanation: This index allows database to quickly filter or join data based
on both product_id and quantity columns with a confirming message.

1.3. Unique Indexes

A unique index ensures that all values in a column (or combination of


columns) are unique preventing duplicates and maintaining data integrity.

Syntax:

CREATE UNIQUE INDEX index_name ON table_name (column_name);

Example:

CREATE UNIQUE INDEX idx_unique_employee_id ON Sales (customer_id);

Explanation: This ensures no two rows in the Sales table can have same
customer_id.

If we try inserting a duplicate:

INSERT INTO Sales (sale_id, product_id, quantity, customer_id)


VALUES (6, 105, 4, 201);

It will throw an error because customer_id = 201 already exists.

2. Removing an Index

Indexes take up storage and add overhead on write operations (INSERT,


UPDATE, DELETE). If an index is no longer needed, it can be removed.

Syntax:

DROP INDEX index_name;

Example:

DROP INDEX idx_product_quantity;

Explanation: Deletes the idx_product_quantity index but keeps the


underlying table data intact.

3. Altering an Index
If an index requires adjustments, such as reorganizing or rebuilding, it can be
altered without affecting the data. This is useful for optimizing index
performance as tables grow larger.

Syntax:

ALTER INDEX IndexName ON TableName REBUILD;

Example:

ALTER INDEX idx_product_id ON Sales REBUILD;

Explanation: Rebuilds the idx_product_id index to optimize its structure.

4. Confirming and Viewing Indexes

We can view all the indexes in a database to understand which ones are in
use and confirm their structure. In SQL, the following query helps us see the
indexes for a given table:

Syntax:

SHOW INDEXES FROM table_name;

Example:

SHOW INDEXES FROM Sales;

Output

Non_uniq Column_na
Table ue Key_name me

Sale idx_product_quant
1 product_id
s ity

Sale idx_product_quant
1 quantity
s ity

Sale idx_unique_custo
0 customer_id
s mer

Explanation: Displays all indexes defined on the Sales table.


5. Renaming an Index

In some cases, renaming an index might be necessary for clarity or


consistency. While SQL does not directly support renaming indexes, we can
use a combination of commands to achieve this.

Syntax:

EXEC sp_rename 'old_index_name', 'new_index_name', 'INDEX';

Example:

EXEC sp_rename 'idx_product_quantity', 'idx_prod_qty', 'INDEX';

Explanation: This command allows us to rename an existing index, which


helps maintain clarity in our database schema.
SQL CREATE INDEX Statement

Last Updated : 23 Jul, 2025

In SQL, indexes are important for optimizing query performance by


speeding up data retrieval operations. The CREATE INDEX statement is
used to create indexes in tables, enabling quicker searches and improving
database efficiency.

In this article, we will explain how to use the SQL CREATE INDEX
Statement, when to create indexes, and why they are important for
enhancing query performance.

What is the CREATE INDEX Statement?

The CREATE INDEX Statement in SQL is used to create indexes in tables


and retrieve data from the database faster than usual. Indexes are invisible
structures that work behind the scenes to speed up data retrieval operations
in databases. They are essential for optimizing query performance and
improving overall system efficiency. While they are not visible to users,
indexes improve query performance significantly, making them an essential
part of database optimization.

The CREATE INDEX command enables us to create an index on a table,


improving query performance by providing a faster way to retrieve rows.

Syntax:

CREATE INDEX index_name


ON table (column1, column2.....);

Key Terms

 index_name: The name of the index.

 table_name: The name of the table on which the index is created.

 column1, column2, ...: The columns that the index will be applied to.

Creating a Unique Index:


A unique index ensures that all values in the indexed columns are unique
preventing duplicate values.

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

When Should Indexes Be Created?

Indexes should be created under the following conditions:

 Frequent Search Columns: When a column is frequently used


in WHERE clauses or as part of joins.

 Wide Range of Values: When a column has a large variety of distinct


values (e.g., product IDs, customer IDs).

 Low Null Values: Indexes work best on columns that contain a low
number of NULL values.

Example of SQL CREATE INDEX Statement

Let’s look at an example where we use the CREATE INDEX command on


a STUDENTS table given below

student ag birthdat
_id name address e e

91 ABC 1991-08-
1 DEV SHARMA 25
STREET 19

1999-09-
2 ARYA RAJPUT 77 XYZ STREET 21
29

GAURAV 101 YEMEN 2000-01-


3 29
VERMA ROAD 01

Step 1: Create an Index

In this example, we will create an index on the name column of


the STUDENTS table to speed up queries that search by name.

Query:
CREATE INDEX idx
ON STUDENTS(NAME);

Explanation:

This creates an index named idx_name on the name column of


the STUDENTS table. The index will improve performance for queries that
search for students by name.

Step 2: Retrieve Data Using the Index

After creating the index, queries that use the name column in
their WHERE clause will benefit from the faster data retrieval provided by the
index. The USE INDEX hint directs the query to use the idx_name index to
speed up data retrieval.

Query:

SELECT * FROM STUDENTS USE INDEX(idx);

Output

Create Index Statement Example

DROP INDEX Statement in SQL

The DROP INDEX statement in SQL is used to delete an index from a table.
Removing unnecessary or redundant indexes can improve write performance
by reducing the overhead involved in maintaining them
during INSERT, UPDATE, or DELETE operations.

The syntax for the DROP INDEX statement varies slightly depending on
the database management system (DBMS) being used.

1. DROP INDEX in MS Access

DROP INDEX index_name ON table_name;

Key Terms

 index_name: The name of the index to be deleted.


 table_name: The name of the table from which the index is being
removed.

2. DROP INDEX in SQL Server

DROP INDEX table_name.index_name;

Key Terms

 table_name: The name of the table that contains the index.

 index_name: The name of the index to be deleted.

3. DROP INDEX in DB2/Oracle

DROP INDEX index_name;

4. DROP INDEX in MySQL

ALTER TABLE table_name DROP INDEX index_name;

Key Terms

 table_name: The name of the table.

 index_name: The name of the index to be dropped.

Important Points About SQL CREATE INDEX Statement

 Improves Data Retrieval: The CREATE INDEX statement is used to


create indexes on columns, speeding up query execution and enabling
faster data retrieval, especially on large tables.

 Enhances Query Efficiency: Indexes help with efficiently searching


for data, sorting results in a specified order, and optimizing joins
between tables.

 Over-Indexing Risks: While indexes speed up SELECT queries, too


many indexes can degrade overall system performance. They require
additional storage and can slow down data modification operations
(INSERT, UPDATE, DELETE). Indexes should be created on columns
frequently queried or used in joins.

 Unique Indexes: The CREATE UNIQUE INDEX statement ensures


that the indexed column contains only unique values, helping maintain
data integrity by preventing duplicates.
 Removing Unused Indexes: The DROP INDEX statement allows for
removing indexes that are no longer needed, helping improve
database performance by eliminating unnecessary overhead.

Conclusion

Indexes are essential for improving database performance, particularly for


frequently searched columns or those used in WHERE clauses of SELECT
queries. While they speed up data retrieval, it's important to use them
judiciously. Over-indexing can lead to slower database updates and overall
system performance degradation. The CREATE INDEX statement allows for
both simple and unique indexes, offering flexibility in how data is indexed
and queried.
SQL DROP INDEX Statement

Last Updated : 23 Jul, 2025

In SQL, indexes play an essential role in optimizing query performance by


speeding up data retrieval operations. However, indexes can also slow
down data modification operations such as INSERT, UPDATE,
and DELETE due to the overhead of maintaining them. When an index is no
longer required or becomes redundant, it's important to remove it using
the DROP INDEX statement

In this article, we will explain the purpose of the SQL DROP


INDEX command, how to use it, and explore different examples and
scenarios for removing indexes in SQL databases.

What is SQL DROP INDEX?

The SQL DROP INDEX Command is used to remove an existing index from a
table. Indexes are created to speed up query performance, but they can
also consume storage space and add overhead to write operations. By
removing unnecessary indexes, we can free up space and improve the
performance of INSERT, UPDATE, and DELETE operations.

Indexes created by PRIMARY KEY or UNIQUE constraint can not be


deleted with just a DROP INDEX statement. To delete such indexes, we
need to first drop the constraints using the ALTER TABLE statement, and
then drop the index.

Syntax for DROP INDEX Statement


The syntax for dropping an index varies slightly depending on the database
system we are using. Here are the syntaxes for different database
management systems (DBMS):

MySQL

ALTER TABLE table_name DROP INDEX index_name;

MS Access

DROP INDEX index_name ON table_name;

SQL Server

DROP INDEX table_name.index_name;

DB2/Oracle

DROP INDEX index_name;

PostgreSQL

DROP INDEX index_name;

Example of SQL DROP INDEX

Let’s go through an example where we create a table and add an index using
the CREATE INDEX statement, and then drop it using the DROP
INDEX statement.

Step 1: Create the EMPLOYEE Table

CREATE TABLE EMPLOYEE(


EMP_ID INT,
EMP_NAME VARCHAR(20),
AGE INT,
DOB DATE,
SALARY DECIMAL(7,2));

Step 2: Create an Index on the EMPLOYEE Table

CREATE INDEX EMP


ON EMPLOYEE(EMP_ID, EMP_NAME);

This creates an index named EMP on the EMP_ID and EMP_NAME columns of
the EMPLOYEE table, improving query performance for queries involving
these columns.

Dropping an Index
Now let's look at some examples of DROP INDEX statement and
understand its workings in SQL. We will learn different use cases of the SQL
DROP INDEX statement with examples. We can drop the index using two
ways either with IF EXISTS or with ALTER TABLE so we will first drop the
index using if exists.

Example 1: SQL DROP INDEX with IF EXISTS

Using the IF EXISTS clause ensures that the index is dropped only if it already
exists in the table. This prevents errors from being thrown if the index is not
present.

Query:

DROP INDEX IF EXISTS EMP ON EMPLOYEE;

Output

Commands Executed Successfully;

Explanation:

This query drops the EMP index from the EMPLOYEE table only if the index
exists, ensuring no error occurs if the index is absent. Since the EMP index
exists, it is successfully removed. If the index didn’t exist, no error would be
thrown

Example 2: SQL DROP INDEX with ALTER TABLE

In MySQL, PostgreSQL, and some other databases, the ALTER


TABLE statement is used to drop an index. This query drops the EMP index
on the EMPLOYEE table using the ALTER TABLE statement.

Query:

ALTER TABLE EMPLOYEE


DROP INDEX EMP;

Output
Dropping the
index

Verifying the DROP INDEX

To verify if the DROP INDEX statement has successfully removed the index
from the table, we can check the indexes on the table. If the index is not
present in the list, we know it has been deleted. This can be done
using database-specific commands.

MySQL Verification:

SHOW INDEXES FROM EMPLOYEE;

SQL Server Verification:

SELECT * FROM sys.indexes WHERE object_id = (SELECT object_id FROM


sys.objects WHERE name = 'EMPLOYEE');

PostgreSQL Verification:

SELECT * FROM USER_INDEXES WHERE table_name = 'EMPLOYEE';

Explanation:

These queries retrieve information about the indexes associated with


the EMPLOYEE table. If the index was successfully removed, it will not
appear in the results.

Important Points About SQL DROP INDEX Statement

 The SQL DROP INDEX statement is used to remove an existing index


from a database table.

 It optimizes database performance by reducing index maintenance


overhead.

 It improves the speed of improve INSERT, UPDATE, and DELETE


operations on the table.
 Indexes created by PRIMARY KEY or UNIQUE constraints cannot be
dropped using just the DROP INDEX statement.

 The IF EXISTS clause can be used to conditionally drop the index only if
it exists.

 To verify if the DROP INDEX statement has successfully removed the


index from the table, we can check the indexes on the table.

Conclusion

The SQL DROP INDEX statement is an important tool


for database optimization. By removing unnecessary indexes, we can free
up space, improve write performance, and enhance overall system
efficiency. However, we should always evaluate the impact of dropping an
index on query performance before proceeding, especially for frequently
accessed columns. Indexes should be used strategically, and removing
them should only be done when they are no longer required, ensuring a
balanced and efficient database environment.

SQL Show Indexes

Last Updated : 23 Jul, 2025

In relational databases, indexes are essential for optimizing query


performance and speeding up data retrieval operations. By creating an
efficient access path for specific columns, indexes help reduce the time it
takes to fetch results from large datasets. Understanding how to manage,
view, and optimize indexes is crucial for any database administrator.
In this article, we will explain how to use the SQL SHOW
INDEXES statement, its role in database optimization, and how to list and
view indexes effectively across various database systems.

SHOW INDEXES: How to View Indexes in SQL

The SHOW INDEXES statement is used to display detailed


information about the indexes present in a specific table. This information
includes the index name, columns involved, whether the index
allows duplicates, and other important details. It helps database
administrators analyze the existing indexes and determine if any
indexes need optimization or removal.

The syntax for the SHOW INDEXES statement varies across different
database management systems. Here are some common examples:

MySQL:

SHOW INDEXES FROM table_name;

Explanation:

This command displays all the indexes created for a particular table,
providing details such as index name, column names, and more.

PostgreSQL:

SELECT * FROM pg_indexes WHERE tablename = 'table_name';

Explanation:

PostgreSQL uses the pg_indexes system catalog to store index details. This
query lists all indexes associated with a specific table.

SQL Server:

SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('table_name');

Explanation:

In SQL Server, this query retrieves information about indexes for a given
table by querying the sys.indexes catalog view.

Output of SHOW INDEXES

The SHOW INDEXES command provides valuable information about the


indexes in a table. Below are the key columns in the output and their
meanings:
Columns in the SHOW INDEXES Output:

1. table: The name of the table that has infomation about indexes being
shown.

2. non_unique: It tells whether the index allows similar values. A value


of 1 means repetition is allowed, but with a zero the index makes sure
it don't repeat.

3. key_name: It tells us the name of the index. The name for primary
key indexes is written as 'PRIMARY'.

4. seq_in_index: It shows the sequence number of a column in an index.


For complex indexes (indexes made up of more than one column), this
part shows where the column is in the index.

5. column_name: The title of the section that belongs to the index.

6. collation: Sets out the way that column is sorted inside the index. 'A'
means ascending, 'B' means descending and NULL shows that the
column is not sorted.

7. cardinality: An estimate of how many unique values are there in the


index. Usually, a higher cardinality means better use of indexes for
search queries.

8. sub_part: Shows how long the part of columns that are just partly
indexed is. If NOTHING, the whole column is indexed.

9. index_type: Tells what kind of index is used, like BTREE, HASH,about


or FULLTEXT.

10. visible: Shows if the list is seen by the query optimizer (say 'Yes'
if it can be, and not say anything for no).

Example Of SQL Show Indexes

Let’s create a table and add indexes to it, and then use the SHOW
INDEXES statement to view index details in MySQL. Additionally, we will
demonstrate how different types of indexes such as primary, unique,
and composite indexes impact the table's performance and indexing
strategy.

Step 1: Create the orders Table

CREATE TABLE orders (


order_id INT AUTO_INCREMENT,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2),
PRIMARY KEY(order_id),
INDEX idx_customer_id (customer_id), -- Regular index on customer_id
UNIQUE INDEX unique_order_date (order_date), -- Unique index on
order_date
INDEX invisible_index (total_amount) INVISIBLE, -- Invisible index on
total_amount
INDEX composite_index (customer_id, order_date) COMMENT 'By customer
and order date' -- Composite index on multiple columns
);

Explanation:

This creates the orders table with several indexes: a primary index
on order_id, a regular index on customer_id, a unique index
on order_date, an invisible index on total_amount, and a composite index
on customer_id and order_date.

Step 2: Show Indexes on the orders Table

SHOW INDEXES FROM orders;

Output

Show Indexes example


Show Indexes example

Explanation:

The output shows all the indexes associated with the orders table, along
with details like index name, column names, uniqueness, cardinality, and
index type. It helps you understand how each index is structured and
whether it's used for specific queries.

Key Features of Indexes:

1. Faster Data Retrieval: Indexes allow the database to access specific


rows quickly without scanning the entire table.

2. Efficiency in Querying: By organizing data in a structured way,


indexes make SELECT queries faster, which improves the overall
performance of database operations.

3. Impact on Data Modifications: While indexes optimize SELECT


queries, they can slow down INSERT, UPDATE,
and DELETE operations, as these actions require the index to be
updated as well.

Conclusion

The SHOW INDEXES statement is an essential tool


for managing and optimizing indexes in SQL databases. By providing
detailed information about the indexes in a table, it allows database
administrators to monitor and adjust the indexing strategy based on query
performance. Whether we're using MySQL, PostgreSQL, or SQL Server,
understanding how to use SHOW INDEXES can help us fine-tune our
indexing strategy, improve query performance, and ensure that
our database remains efficient as it scales.
SQL Unique Index

Last Updated : 23 Jul, 2025

A SQL Unique Index is a constraint that ensures no two rows in the indexed
columns of a table have the same values, thereby preventing duplicate
entries. Unique indexes are crucial for maintaining data integrity, particularly
when you need specific columns or combinations of columns to hold only
unique values.

In this article, we will explore the concept of SQL Unique Indexes, their
syntax, use cases, and practical examples with detailed explanations. By the
end, you’ll have a clear understanding of how and when to use unique
indexes to improve your database design and ensure data consistency.

What is a SQL Unique Index?

A SQL Unique Index is a database constraint that ensures the values in


the indexed column(s) are unique across all rows in a table. It can be
applied to one or more columns, ensuring data integrity by preventing
duplicate values. Unique indexes can be created for both single
columns and combinations of multiple columns. Additionally, they
automatically exclude NULL values if multiple rows contain NULL in
the indexed columns, further maintaining data consistency.

Key Characteristics of SQL Unique Index

 If a unique index is created on a single column, all rows in that


column must be unique.

 If the unique index is created on multiple columns, the combination


of values in these columns must be unique.

 A unique index cannot be created on a column if duplicate


values already exist.
 Unique indexes improve query performance by optimizing data
retrieval.

Syntax:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ..., columnN);

Key Terms:

 index_name: The name of the unique index.

 table_name: The name of the table where the index will be created.

 column1, column2, ..., columnN: The columns on which the unique


index is being applied.

Examples of SQL Unique Index

Let’s create a sample CUSTOMERS table containing customer details such


as ID, NAME, AGE, ADDRESS, and SALARY. This table serves as the basis
for demonstrating the creation and use of unique indexes. Each row
represents a unique customer, and we will apply unique constraints to
specific columns to illustrate their functionality.

Query:

CREATE TABLE CUSTOMERS (


ID INT NOT NULL,
NAME VARCHAR(15) NOT NULL,
AGE INT NOT NULL,
ADDRESS VARCHAR(25),
SALARY DECIMAL(10, 4),
PRIMARY KEY(ID)
);

INSERT INTO CUSTOMERS VALUES


(1, 'Ramesh', 32, 'Ahmedabad', 2000),
(2, 'Khilan', 25, 'Delhi', 1500),
(3, 'Kaushik', 23, 'Kota', 2000),
(4, 'Chaitali', 26, 'Mumbai', 6500),
(5, 'Hardik', 27, 'Bhopal', 8500),
(6, 'Komal', 22, 'Hyderabad', 9000),
(7, 'Muffy', 24, 'Indore', 5500);
Example 1: Creating a Unique Index on a Single Column

This example creates a unique index on the NAME column to prevent


duplicate names in the CUSTOMERS table. It ensures that every entry in
the NAME column is distinct, enforcing data integrity.

Query:

CREATE UNIQUE INDEX UNIQUE_NAME ON CUSTOMERS(NAME);

Output:

Query OK, 0 rows


affected

Explanation:

The output confirms the successful creation of the unique index on


the NAME column. No rows are affected since the index is applied to existing
data, and any future attempts to insert duplicate values will result in
an error.

Example 2: Creating a Unique Index on Multiple Columns

This example demonstrates how to enforce uniqueness across a


combination of two columns by creating a unique index on NAME and AGE.

Query:

CREATE UNIQUE INDEX MUL_UNIQUE_INDEX ON CUSTOMERS(NAME, AGE);

Output:

Query OK, 0 rows affected

Explanation:

The unique index MUL_UNIQUE_INDEX ensures that the combination


of NAME and AGE values is unique for every row in the CUSTOMERS table. If
you attempt to insert or update a row with the same combination
of NAME and AGE values as an existing row, the database engine will throw
an error, ensuring no duplicate combinations are allowed.

Example 3: Attempting to Create a Unique Index on a Column with


Duplicate Values
This example illustrates the behavior of the database when trying to create
a unique index on a column that already contains duplicate values.

Query:

CREATE UNIQUE INDEX UNIQUE_SALARY ON CUSTOMERS(SALARY);

Output:

| ERROR 1062 (23000): Duplicate entry '2000.00' for key


'customers.UNIQUE_SALARY' |

Explanation:

The database engine prevents creating a unique index on


the SALARY column because it contains duplicate entries (2000.00 appears
twice). To resolve this issue, we would need to remove or update duplicate
values.

Example 4: Verifying Indexes in a Table

This example demonstrates how to verify the unique indexes created on


the CUSTOMERS table using the SHOW INDEX command.

Query:

SHOW INDEX FROM CUSTOMERS;

Output:

Non_uniq Seq_in_in Column_na


Table ue Key_name dex me

CUSTOME
0 PRIMARY 1 ID
RS

CUSTOME
0 UNIQUE_NAME 1 NAME
RS

CUSTOME MUL_UNIQUE_IND
0 1 NAME
RS EX
Non_uniq Seq_in_in Column_na
Table ue Key_name dex me

CUSTOME MUL_UNIQUE_IND
0 2 AGE
RS EX

Explanation:

The SHOW INDEX command lists all indexes created on the table. It displays
the index names, the associated columns, and their properties. This
information helps verify the existence and structure of indexes applied to
the table, ensuring their proper implementation.

Example 5: Handling Duplicate Entries in Indexed Columns

This example demonstrates what happens when


an UPDATE operation attempts to assign a duplicate value to a column
with a unique index.

Query:

UPDATE CUSTOMERS SET ADDRESS = 'Mumbai' WHERE ADDRESS = 'Delhi';

Output:

| ERROR 1062 (23000): Duplicate entry 'Mumbai' for key


'customers.ADD_UNIQUE_INDEX' |

Explanation:

The UPDATE query tries to change the value of ADDRESS from 'Delhi' to
'Mumbai', but the column ADDRESS has a unique index
(ADD_UNIQUE_INDEX). Since 'Mumbai' is already present in another row, the
database engine prevents this operation to maintain the uniqueness
constraint on the ADDRESS column.

Benefits of SQL Unique Index

 Data Integrity: A unique index ensures that no duplicate values exist


in the indexed column(s), maintaining the accuracy and reliability of
your data.

 Improved Query Performance: Unique indexes optimize data


retrieval for queries involving unique values, making searches faster
and more efficient.
 Flexibility: Unique indexes can be applied to single columns or a
combination of multiple columns, offering versatility in enforcing
constraints across different data structures.

 Error Prevention: Unique indexes help prevent unintentional


duplicates during INSERT or UPDATE operations, safeguarding your
database from inconsistent or invalid data

Conclusion

The SQL Unique Index is a powerful tool for maintaining data


integrity and optimizing query performance. By enforcing uniqueness in
one or more columns, it ensures that our database remains consistent and
reliable. Use the CREATE UNIQUE INDEX statement strategically
to prevent duplicate entries and improve data retrieval efficiency. With
examples and detailed explanations, this guide provides everything we
need to understand and implement unique indexes effectively.

Clustered and Non-Clustered Indexing

Last Updated : 29 Aug, 2025

Indexing is a performance optimization technique in SQL Server that


significantly improves the speed of data retrieval operations. There are
mainly two types of indexing: Clustered and Non-Clustered. Understanding
the difference between them is essential for database developers and
administrators to write faster and more efficient queries.

Clustered Index

A Clustered Index defines the physical order of rows in a table. When you
create a clustered index on a column, SQL Server rearranges the actual data
rows to match the index order. This is why a table can have only one
clustered index.

A clustered index is created only when both the following conditions are
satisfied:

 The data can be stored in a sequential or sorted manner.

 The column used as the key must contain unique values.


Example of Clustered Index:

Consider a table called Student where the Roll_No column is the primary
key. This automatically becomes a clustered index.

Here, SQL Server automatically creates a clustered index on


the Roll_No column. The rows are physically stored in ascending
order based on the Roll_No.

Roll_N Gend
o Name er Mob_No

femal 98765432
ankita
4 e 10

femal 96754328
anita
3 e 90

5 mahim femal 89764532


Roll_N Gend
o Name er Mob_No

a e 01

Explaination:

 A table can have only one clustered index.

 A clustered index can be created on multiple columns → called a


composite index.

 In this case, Roll_No is the primary key, so it automatically becomes


the clustered index.

 Query results are displayed in ascending order of Roll_No.

Non-Clustered Index

A Non-Clustered Index does not change the physical order of data. Instead, it
creates a separate structure that stores the indexed column(s) along with
pointers (row locators) to the actual rows in the table.

This separation allows you to have multiple non-clustered indexes on a single


table, making them useful for columns frequently used in search conditions
or joins.

Key Characteristics:

 Stores index data separately from the table.

 Multiple non-clustered indexes can exist on a table.

 Contains a copy of the indexed column(s) and a pointer to the actual


data row.
Example of Non-Clustered Index:

In the Student table, we could create a non-clustered index on


the Name column. Here, roll no is a primary key, hence there is
automatically a clustered index. If we want to apply a non-clustered index in
the NAME column (in ascending order), then a new table will be created for
that column. In this example, a non-clustered index is created on
the Name column. SQL Server will create a separate
structure containing Nameand pointers to the rows where the
corresponding data resides.

Query:

CREATE NONCLUSTERED INDEX NIX_FTE_Name

ON Student (Name ASC);

Output:
Roll_N Nam Gend
o e er Mob_No

98765432
afzal male
4 10

sudhi 96754328
male
3 r 90

femal 89764532
zoyz
5 e 01

Explanation:

Creates Index: Makes a non-clustered index named NIX_FTE_Name.

 Table: The index is created on the Student table.

 Column: Applied to the Name column.

 Order: Data in the index is stored in ascending order.

 Purpose: Speeds up searches/queries on the Name column without


changing the table’s actual data order.

Differences Between Clustered and Non-Clustered Index

This table organizes the primary differences between clustered and non-
clustered indexes, making it easier to understand when to use each index
type based on performance requirements and database structure.

Clustered Index Non-Clustered Index

Faster for range-based queries Slower for range-based queries but faster
and sorting. for specific lookups.

Requires less memory for Requires more memory due to additional


operations. index structure.
Clustered Index Non-Clustered Index

The clustered index stores The non-clustered index stores data


data in the table itself. separately from the table.

A table can have only one A table can have multiple non-clustered
clustered index. indexes.

The non-clustered index stores the index


The clustered index can store
structure (B-tree) on disk with pointers to
data on the disk.
the data pages.

Stores both the indexed value and a


Stores pointers to the data
pointer to the actual row in a separate
blocks, not the data itself.
data page.

Leaf nodes contain the actual Leaf nodes contain indexed columns and
data itself. pointers to data.

Defines the physical order of Defines the logical order of data in the
the rows in the table. index, not the table.

The data is physically The logical order does not match the
reordered to match the index. physical order of rows.

Primary keys are by default Composite keys used with unique


clustered indexes. constraints are non-clustered.

Typically larger, especially for


Smaller than clustered indexes,
large primary clustered
especially when composite.
indexes.
Clustered Index Non-Clustered Index

Ideal for range queries and Suitable for optimizing lookups and
sorting. queries on non-primary columns.

A clustered index directly


A non-clustered index does not affect the
impacts the table's physical
physical storage order of the table.
storage order.

SQL Subquery
Perform queries within queries to solve complex data retrieval problems.
They help in filtering data or performing operations on data that would
otherwise require multiple queries.

 Subquery

 Correlated Subqueries

 Nested Queries

SQL Subquery

Last Updated : 28 Aug, 2025

A subquery in SQL is a query nested inside another SQL query. It allows


complex filtering, aggregation and data manipulation by using the result of
one query inside another. They are an essential tool when we need to
perform operations like:

 Filtering: selecting rows based on conditions from another query.

 Aggregating: applying functions like SUM, COUNT, AVG with dynamic


conditions.

 Updating: modifying data using values from other tables.

 Deleting: removing rows based on criteria from another query.

While there is no universal syntax for subqueries, they are commonly used in
SELECT statements as follows.

Syntax:

SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);

Common SQL Clauses for Subqueries

Clauses that can be used with subqueries are:


 WHERE: filter rows based on subquery results.

 FROM: treat subquery as a temporary (derived) table.

 HAVING: filter aggregated results after grouping.

Types of Subqueries

1. Single-Row Subquery

 Returns exactly one row as the result.

 Commonly used with comparison operators such as =, >, <

Example:

SELECT * FROM Employees


WHERE Salary = (SELECT MAX(Salary) FROM Employees);

Output: Returns the employee(s) with the highest salary.

2. Multi-Row Subquery

 Returns multiple rows as the result.

 Requires operators that can handle multiple values, such as IN, ANY or
ALL

Example:

SELECT * FROM Employees


WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE
Location = 'New York');

Output: Fetches employees working in all New York departments.

3. Correlated Subquery

 A dependent subquery: it references columns from the outer query.

 Executed once for each row of the outer query, making it slower for
large datasets.

Example:

SELECT e.Name, e.Salary


FROM Employees e
WHERE e.Salary > (SELECT AVG(Salary)
FROM Employees
WHERE DepartmentID = e.DepartmentID);
Output: Returns employees earning more than the average salary of their
own department.

Examples of Using SQL Subqueries

These examples showcase how subqueries can be used for various


operations like selecting, updating, deleting or inserting data, providing
insights into their syntax and functionality. Through these examples, we will
understand flexibility and importance of subqueries in simplifying complex
database tasks.

Consider the following two tables:

Student Table

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ram 101 Chennai 9988775566

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

New_Student Table

ROLL_N SECTIO
NAME O N

Ravi 104 A
ROLL_N SECTIO
NAME O N

Sumat
105 B
hi

Raj 102 A

Example 1: Fetching Data Using Subquery in WHERE Clause

This example demonstrates how to use a subquery inside the WHERE clause.
The inner query retrieves roll numbers of students who belong to section 'A'
and the outer query fetches their corresponding details (name, location and
phone number) from the Student table.

Query:

SELECT NAME, LOCATION, PHONE_NUMBER


FROM Student
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM New_Student WHERE SECTION = 'A'
);

Output

NAM LOCATIO PHONE_NUMB


E N ER

Rav
Salem 8989898989
i

Coimbato
Raj 8877665544
re

Explanation:

 The subquery SELECT ROLL_NO FROM New_Student WHERE SECTION =


'A' finds roll numbers of students in section A.
 The outer query then uses these roll numbers to fetch details from the
Student table.

 Thus, only Ravi and Raj are returned, since they are in section A.

Example 2: Using Subquery with INSERT

Here we demonstrate how a subquery can be used with INSERT. Instead of


manually entering data, we copy data from another table (Temp_Students)
into the main Student table.

Temp_Students

ROLL_N LOCATI PHONE_NUMB


NAME O ON ER

Ajay 201 Mumbai 9090901234

Meen
202 Delhi 8080805678
a

Query:

INSERT INTO Student


SELECT * FROM Temp_Students;

Output

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ram 101 Chennai 9988775566

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344


ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Ajay 201 Mumbai 9090901234

Meena 202 Delhi 8080805678

Explanation:

 The subquery SELECT * FROM Temp_Students selects all rows from the
helper table.

 The INSERT INTO Student adds these rows into the main Student table.

 Thus, Ajay and Meena are successfully added.

Example 3: Using Subquery with DELETE

In this example, we use a subquery with DELETE to remove certain rows from
the Student table. Instead of hardcoding roll numbers, the subquery finds
them based on conditions.

Query:

DELETE FROM Student


WHERE ROLL_NO IN (
SELECT ROLL_NO FROM Student WHERE ROLL_NO <= 101 OR ROLL_NO =
201
);

Output
ROLL_N PHONE_NUMB
NAME O LOCATION ER

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Meena 202 Delhi 8080805678

Explanation:

 The subquery selects roll numbers 101 and 201.

 The outer query deletes students having those roll numbers.

 As a result, Ram (101) and Ajay (201) are removed.

Example 4: Using Subquery with UPDATE

Subqueries can also be used with UPDATE. In this example, we update


student names to "Geeks" if their location matches the result of a subquery.

Query:

UPDATE Student
SET NAME = 'Geeks'
WHERE LOCATION IN (
SELECT LOCATION FROM Student WHERE LOCATION IN ('Salem', 'Delhi')
);

Output
ROLL_N PHONE_NUMB
NAME O LOCATION ER

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Geeks 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Geeks 202 Delhi 8080805678

Explanation:

 The subquery selects locations 'Salem' and 'Delhi'.

 The outer query updates the NAME field for students whose location
matches those values.

 Thus, Ravi and Meena are renamed to "Geeks".

Example 5: Simple Subquery in the FROM Clause

This example demonstrates using a subquery inside the FROM clause, where
the subquery acts as a temporary (derived) table.

Query:

SELECT NAME, PHONE_NUMBER


FROM (
SELECT NAME, PHONE_NUMBER, LOCATION
FROM Student
WHERE LOCATION LIKE 'C%'
) AS subquery_table;

Output
NAM PHONE_NUMB
E ER

Ra
9988775566
m

Raj 8877665544

Explanation:

 The subquery (SELECT NAME, PHONE_NUMBER, LOCATION FROM


Student WHERE LOCATION LIKE 'C%') fetches students whose location
starts with "C" (Coimbatore, Chennai, etc.).

 The outer query then selects only NAME and PHONE_NUMBER from this
derived table.

 Only Raj qualifies because his location is Coimbatore.

Example 6: Subquery with JOIN

We can also use subqueries along with JOIN to connect data across tables.

Query:

SELECT s.NAME, s.LOCATION, ns.SECTION


FROM Student s
INNER JOIN (
SELECT ROLL_NO, SECTION
FROM New_Student WHERE SECTION = 'A'
) ns
ON s.ROLL_NO = ns.ROLL_NO;

Output

NAM LOCATIO SECTIO


E N N

Rav
Salem A
i
NAM LOCATIO SECTIO
E N N

Coimbato
Raj A
re

Explanation: The subquery extracts roll numbers of students in section A.


Joining this with the Student table on ROLL_NO returns Ravi and Raj along
with their locations and section.

SQL Correlated Subqueries

Last Updated : 19 Aug, 2025

A correlated subquery is a subquery that depends on values from the outer


query. Unlike a regular (non-correlated) subquery, it is evaluated once for
every row in the outer query. This makes correlated subqueries dynamic and
highly useful for solving complex database problems like row-by-row
comparisons, filtering, and conditional updates.

 Row-by-Row Evaluation: Executes once for each row of the outer


query.

 Dynamic & Dependent: Subquery uses values from the outer query.

 Complex Filtering: Ideal for ranking, row-specific calculations, and


conditional logic

Syntax:

SELECT column1, column2, ...

FROM table1 outer

WHERE column1 operator

(SELECT column

FROM table2

WHERE expr1 = outer.expr2);


Correlated Subquery Examples

Correlated subqueries are best understood through practical use cases.


Below are some common scenarios where they are used to filter, update, or
compare data row by row.

1. Fetching Data Based on Row-Specific Conditions

Correlated subqueries are often used when you need to filter data based on a
condition that involves comparing values from the outer query.

Example: Fetch Employees Who Earn More Than Their Department's


Average Salary

SELECT last_name, salary, department_id

FROM employees outer

WHERE salary >

(SELECT AVG(salary)
FROM employees

WHERE department_id =

outer.department_id group by department_id);

Explanation:

In this example, the subquery calculates the average salary for each
department, and for each employee, the outer query checks if their salary is
greater than the average for their department.

2. Using Correlated Subqueries with UPDATE

Correlated subqueries can also be used with UPDATE statements to modify


data based on related information from another table.

Example: Update Employee Salary Based on Department Average

UPDATE employees e

SET salary = (SELECT AVG(salary)

FROM employees

WHERE department_id = e.department_id)

WHERE department_id = 101;

Explanation:

This query updates the salaries of employees in department 101 based on


the average salary for that department. The subquery is evaluated for each
row in the employees table.

3. Using Correlated Subqueries with DELETE

We can use a correlated subquery within a DELETE statement to remove


rows from one table based on conditions in another table.

Example: Delete Employees Who Do Not Belong to Department 101

DELETE FROM table1 alias1

WHERE column1 operator

(SELECT expression

FROM table2 alias2

WHERE alias1.column = alias2.column);


Explanation:

This query deletes employees who do not belong to the 'HR' department by
using a correlated subquery in the NOT EXISTS clause.

4. Using EXISTS with Correlated Subqueries

The EXISTS operator is often used in correlated subqueries to test if a


subquery returns any rows. It returns TRUE if the subquery has at least one
row.

Example: Find Employees Who Have at Least One Person Reporting


to Them

SELECT employee_id, last_name, job_id, department_id

FROM employees outer

WHERE EXISTS ( SELECT ’X’

FROM employees

WHERE manager_id =

outer.employee_id);

Output

5. Using NOT EXISTS with Correlated Subqueries

The NOT EXISTS operator is used to check if a subquery does not return any
rows. This is useful for finding records that do not match specific criteria.
Example: Find Departments Without Any Employees

SELECT department_id, department_name

FROM departments d

WHERE NOT EXISTS (SELECT ’X’

FROM employees

WHERE department_id

= d.department_id);

Output

Explanation:

This query retrieves departments that do not have any employees assigned
to them. The NOT EXISTS clause ensures that only those departments
without employees are selected.

Nested vs. Correlated Subqueries

Nested (Non-Correlated)
Subquery Correlated Subquery

Executes once before the


Executes for each row of the outer query.
outer query.
Nested (Non-Correlated)
Subquery Correlated Subquery

Independent of the outer


Dependent on values from the outer query.
query.

Usually more efficient for


Can be slower as it runs multiple times.
large datasets.

Example: WHERE col IN Example: WHERE col > (SELECT AVG(col)


(SELECT col FROM table2) FROM table2 WHERE table2.id = outer.id)

Performance Considerations

 Can be slow on large datasets due to repeated execution.

 Use JOINs when possible for better performance.

 Ensure proper indexes on columns used in filtering.


SQL Nested Queries

Last Updated : 28 Aug, 2025

A nested query (or subquery) is an SQL query placed inside another query to
make the overall operation more structured and readable. The inner query
executes first and its result is then used by the outer query. Subqueries can
appear in the SELECT, FROM or WHERE clauses, making them useful for
tasks such as filtering, aggregation and retrieving data based on the results
of another query. They are helpful for breaking down complex SQL operations
into smaller, structured steps that are easier to read and maintain.

Types of Nested Queries in SQL

There are two primary types of nested queries in SQL, Independent Nested
Queries and Correlated Nested Queries. Each type has its own use case and
benefits depending on the complexity of the task at hand.

We will use the following sample tables to demonstrate nested queries:

1. STUDENT Table

The STUDENT table stores information about students, including their unique
ID, name, address, phone number and age.

S_I S_NA S_ADDRE S_AG


D ME SS S_PHONE E

94551234
RAM DELHI 18
S1 51

RAMES 96524315
GURGAON 18
S2 H 43
S_I S_NA S_ADDRE S_AG
D ME SS S_PHONE E

91562531
SUJIT ROHTAK 20
S3 31

SURES 91567689
DELHI 18
S4 H 71

2. COURSE Table

The COURSE table stores course details, including a unique course ID and
course name.

C_I
D C_NAME

C1 DSA

Programmi
C2
ng

C3 DBMS

3. STUDENT_COURSE Table

This table maps students to the courses they have enrolled in, with columns
for student ID (S_ID) and course ID (C_ID):

S_I C_I
D D

S1 C1
S_I C_I
D D

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

1. Independent Nested Queries

In an independent nested query, the execution of the inner query is


independent of the outer query. The inner query runs first and its result is
used directly by the outer query. Operators like IN, NOT IN, ANY and ALL are
commonly used with independent nested query.

Example 1: Using IN

In this Example we will find the S_IDs of students who are enrolled in the
courses ‘DSA’ or ‘DBMS’. We can break the query into two parts:

Step 1: Find the C_IDs of the courses:

This query retrieves the IDs of the courses named 'DSA' or 'DBMS' from the
COURSE table.

SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS');

Output

C_I
D

C1
C_I
D

C3

Step 2: Use the result of Step 1 to find the corresponding S_IDs:

The inner query finds the course IDs and the outer query retrieves the
student IDs associated with those courses from the STUDENT_COURSE table

SELECT S_ID FROM STUDENT_COURSE


WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
);

Output

S_I
D

S1

S2

S4

Explanation: The inner query finds the course IDs of DSA and DBMS. The
outer query then retrieves the student IDs enrolled in those courses.

2. Correlated Nested Queries

In correlated nested queries, the inner query depends on the outer query for
its execution. For each row processed by the outer query, the inner query is
executed. This means the inner query references columns from the outer
query. The EXISTS keyword is often used with correlated queries.
Example 2: Using EXISTS

In this Example, we will find the names of students who are enrolled in the
course with C_ID = 'C1':

SELECT S_NAME FROM STUDENT S


WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);

Output

S_NAME

RAM

RAMES
H

Explanation: For each student, the inner query checks if they are enrolled
in C1. If yes, that student’s name is returned.

Common SQL Operators for Nested Queries

SQL provides several operators that can be used with nested queries to filter,
compare and perform conditional checks.

1. IN Operator

The IN operator is used to check whether a column value matches any value
in a list of values returned by a subquery. This operator simplifies queries by
avoiding the need for multiple OR conditions.

Example: Retrieve student names who enrolled in ‘DSA’ or ‘DBMS’:

SELECT S_NAME FROM STUDENT


WHERE S_ID IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
Output

S_NAME

RAM

RAMES
H

SURES
H

Explanation:

 The innermost query fetches course IDs of ‘DSA’ and ‘DBMS’.

 The middle query finds student IDs enrolled in those courses.

 The outer query retrieves names of those students.

2. NOT IN Operator

The NOT IN operator excludes rows based on a set of values from a subquery.
It is particularly useful for filtering out unwanted results. This operator helps
identify records that do not match the conditions defined in the subquery.

Example: Retrieve student IDs not enrolled in ‘DSA’ or ‘DBMS’:

SELECT S_ID FROM STUDENT


WHERE S_ID NOT IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);

Output
S_I
D

S3

Explanation:

 The inner queries first collect IDs of students enrolled in DSA or DBMS.

 The outer query returns only those student IDs that are not in that list.

3. ANY Operator

It compares a value with any value returned by the subquery. If at least one
comparison is true, the condition is satisfied.

Example: Retrieve student names whose age is greater than at least one
student from Delhi

SELECT S_NAME FROM STUDENT


WHERE S_AGE > ANY (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);

Output

S_NA
ME

SUJIT

Explanation:

 The inner query fetches ages of students living in Delhi.

 The outer query checks which students have an age greater than at
least one of those ages.

 Returns students who satisfy that condition.

4. ALL Operator

It compares a value with all values returned by the subquery. The condition is
satisfied only if it is true for every value.
Example: Retrieve student names whose age is greater than all students
from Delhi

SELECT S_NAME FROM STUDENT


WHERE S_AGE > ALL (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);

Output

S_NAME

(No
rows)

Explanation:

 The inner query fetches ages of all students from Delhi.

 The outer query looks for students whose age is greater than every
one of those ages.

 Since no student fulfills this condition, no rows are returned.

Miscellaneous Topics
Explore advanced and useful SQL concepts to deepen your knowledge

 Wildcards Operators

 Comments

 Pivot and Unpivot

 Trigger

 Hosting

 Performance Tuning

 Stored Procedures

 Transactions
 Sub Queries

 Using Sequences

 Auto Increment

 Window functions

 Cursors

 Common Table Expressions

 Database Tuning

 Dynamic

 Regular Expressions

SQL Wildcard Characters

SQL wildcard characters are powerful tools that enable advanced pattern
matching in string data. They are especially useful when working with
the LIKE and NOT LIKE operators, allowing for efficient searches based on
partial matches or specific patterns. By using SQL wildcard characters, we
can greatly enhance the functionality of our SQL queries and perform
sophisticated data retrieval tasks.

In this comprehensive article, we will explain the various SQL wildcard


characters, how they work, and provide practical examples to help us use
them effectively in our queries.

What Are SQL Wildcard Characters?

SQL wildcard Characters are special characters used in SQL queries to


search for patterns within string data. These wildcards can help us
perform partial searches, matching parts of a string or allowing complex
filtering based on patterns. They are most commonly used with
the LIKE and NOT LIKE clauses in SQL. Using wildcard characters in SQL
allows us to search for patterns rather than exact matches, which is
especially useful in cases where we only know part of the string we are
looking for

Syntax

SELECT column1,column2 FROM table_name


WHERE column LIKE wildcard_operator;

Key Terms:

 column1,column2: fields in the table

 table_name: name of the table

 column: name of the field used for filtering data

Types of SQL Wildcard Characters

There are several wildcard characters in SQL, each serving a different


purpose in pattern matching. Let’s break down the most common wildcard
characters and their usage:

Wildcard
Character Description

% Represents zero or more characters.

_ Represents exactly one character.


Wildcard
Character Description

Represents a range of characters, used to match any


[]
single character within the range.

[ ] with ^ or ! Matches any character that is NOT in the specified range.

Example of SQL Wildcard Characters

Let’s dive into practical examples of how to use these wildcard characters
in SQL queries. The Customer table contains data about customers,
including columns such
as CustomerID, CustomerName, LastName, Country, Age, and Phone.
We will use a Customer table to demonstrate various search patterns

Customer Table

1. Using the % Wildcard

The % wildcard is used to substitute for zero or more characters. It’s very
flexible and is commonly used for matching partial strings.

Example 1: Records Starting with a Specific Letter

To fetch records where the CustomerName starts with the letter 'A'. This
query will return all records where the CustomerName starts with the
letter A, regardless of what comes after it.

Query:
SELECT *
FROM Customer
WHERE CustomerName LIKE 'A%';

Output

Table-1

Example 2: Records Ending with a Specific Letter

To fetch records from the Customer table with NAME ending with the letter
'A'. This query retrieves all customers whose name ends with A, regardless of
what comes before it.

Query:

SELECT *
FROM Customer
WHERE CustomerName LIKE '%A';

Output

Table - 2

Example 3: Records Containing a Specific Letter at Any Position

To fetch records from the Customer table with NAME with the letter 'A' at
any position. This query will return records where A appears anywhere within
the name, whether at the beginning, middle, or end.

Query

SELECT * FROM Customer WHERE CustomerName LIKE '%A%';

Output
Table -3

Example 4: Fetching Records with 'ra' in Country Field and Removing


Duplicates

To fetch records from the Customer table where the Country contains the
substring 'ra' at any position, and ensure the result set does not contain
duplicate data:

Query:

SELECT DISTINCT * FROM Customer WHERE Country LIKE '%ra%';

Output

Table - 4

2. Using the _ Wildcard

The _ wildcard is used to substitute for exactly one character. This is


useful when we know part of the string but need to match one specific
unknown character.

Example 1: Records with a Specific Prefix and Any Three Letters

To fetch records where the CustomerName starts with 'Nav' and is followed
by any three characters. This query will retrieve all records where the name
starts with Nav and has exactly three more characters after it
(e.g., Naveen).

Query:

SELECT * FROM Customer WHERE CustomerName LIKE 'Nav___';

Output
Table - 5

Example 2: Records with a Specific Length

To fetch records from the Customer table with Country containing a total of 7
characters. The query will return all records where the Country field has
exactly seven characters.

Query:

SELECT * FROM Customer WHERE Country LIKE '_______';

Output

Table - 6

3. Using the [ ] Wildcard

The [ ] wildcard allows us to specify a set or range of characters that we


want to match. It is especially useful when we need to search for specific
characters within a defined range or group.

Example 1: Matching One Character from a Set

To fetch records from the Customer table with LastName containing letters
'a, 'b', or 'c'. This query will return records where the last name starts
with A, B, or C.

Query

SELECT * FROM Customer WHERE LastName REGEXP '[A-C]';

Output
Table - 7

Example 2: Matching Characters Outside a Range

To fetch records from the Customer table with LastName not containing
letters 'y', or 'z'. This query retrieves customers whose last names do not
contain the letters Y or Z.

Query

SELECT * FROM Students WHERE LastName NOT LIKE '%[y-z]%';

Output

Table - 8

4. Combining Both % and _ Wildcard

We can also combine % and _ wildcards to perform more complex searches.


The % wildcard represents any sequence of characters, while
the _ wildcard represents exactly one character. By combining both, we
can create intricate patterns that match a wide range of string data with
greater precision, allowing us to filter data based on multiple criteria.

Example: Matching Specific Digits in a Phone Number

To fetch records where the Phone number starts with '8' in the first position,
has any two characters in the second and third positions, and then has '5' in
the fourth position.
Query

SELECT * FROM Student WHERE PHONE LIKE '8__5%';

Output

Table - 9

Conclusion

SQL wildcard characters are an important for performing advanced text


matching and filtering within our database queries. By using %, _, and
other wildcards, we can easily query datasets with partial or complex
patterns. Understanding how to use these characters effectively will
significantly enhance our ability to extract meaningful data from our
tables. Mastering wildcards allows us to build more dynamic and flexible
queries, which can be especially useful for data analysis and reporting
tasks.
SQL Comments

SQL comments play an essential role in enhancing


the readability, maintainability, and documentation of our SQL code. By
using comments effectively, developers can provide context, clarify
complex logic, and temporarily disable parts of the code. Whether we're
working alone or collaborating with a team, proper use of SQL
comments can significantly improve the quality and clarity of
our database queries.

In this article, we will explain different types of SQL comments: single-line


comments, multi-line comments, and in-line comments. We’ll also
explore their syntax, provide examples, and discuss best practices for using
SQL comments in our queries.

What Are SQL Comments?

SQL comments are annotations in our SQL code that are not executed by
the database engine. They serve as notes or explanations for human
readers, making it easier to understand and maintain the code. Whether
we're explaining complex logic, providing context for a query, or
temporarily disabling a part of our code, comments are indispensable
tool for any developer.

Types of SQL Comments

SQL Comments explain sections of SQL statements or prevent SQL


statements from being executed. These are the three commenting
methods in SQL, each with its unique use. Let's discuss these SQL
comments in detail below:

There are 3 types of comments in SQL:

1. Single-line comments

2. Multi-line comments

3. In-line comments

1. SQL Single Line Comments

Single-line comments are used to annotate a single line of SQL code. They
are often employed for brief explanations or to temporarily disable
lines of code without removing them. Single-line comments begin
with two hyphens (--), and the comment continues until the end of the line.

Syntax:

-- single line comment

Example

SELECT * FROM customers;

Explanation:

In this example, the comment -- query to fetch customer records explains the
purpose of the query, which is to retrieve all records from
the customers table.

2. SQL Multi-Line Comments

Multi-line comments are used when we need to comment out more than
one line of SQL code. These comments are enclosed between /* and */ and
can span multiple lines. They are typically used for longer explanations or
to disable larger sections of code temporarily.

Syntax:

/* multi line comment


another comment */

Example

SELECT *
FROM orders
WHERE YEAR(order_date) = 2022;

Explanation:

In this example, the multi-line comment explains that the query retrieves all
orders placed in the year 2022 from the orders table.

3. SQL In-Line Comments

In-line comments allow us to add comments within a query itself. They


are typically used to provide additional information or explanations for
specific parts of the query, without interrupting the flow of the SQL
statement. In-line comments start with /* and end with */.
Syntax:

SELECT * FROM /* Customers; */

Example

SELECT customer_name,
order_date
FROM orders;

Explanation:

In this example, in-line comments are used to describe the purpose of


the customer_name and order_date columns. This approach keeps the code
readable and helps future developers understand the logic quickly.

Important Points About SQL Comments

While SQL comments are crucial for code documentation, there are several
best practices to follow when using them:

1. Be Concise but Clear: Keep comments brief but descriptive. Avoid


unnecessary comments that do not add value to the code.

2. Explain Complex Queries: Use comments to explain why certain


decisions were made, especially for complex queries or business logic.

3. Avoid Commenting Obvious Code: Do not comment on trivial or


self-explanatory code. For example, there is no need to comment
simple SELECT statements with straightforward column names.

4. Use Comments to Temporarily Disable Code: Comments are often


used to "comment out" parts of SQL code that need to be tested or
temporarily disabled.

5. Consistent Formatting: Use a consistent style for comments


throughout your SQL codebase. This helps make the code easier to
read and understand, especially when working with a team.

Conclusion

SQL comments are an essential tool for any developer working


with databases. They allow us to annotate our code, making it easier
to understand, maintain, and debug. Whether we're using single-line
comments for quick explanations, multi-line comments for more detailed
descriptions, or in-line comments for specific parts of a query, proper
commenting practices will improve the clarity of our SQL code.

Pivot and Unpivot in SQL

In SQL, PIVOT and UNPIVOT are powerful operations used to transform


data and make it more readable, efficient, and manageable. These
operations allow us to manipulate tables by switching between rows and
columns, which can be crucial for summarizing data, reporting, and data
analysis. Understanding how to use PIVOT and UNPIVOT operators
effectively can significantly enhance our data manipulation capabilities.

In this article, we’ll explore what PIVOT and UNPIVOT are, their syntax, key
differences, and provide practical examples with explanations to help us
master these SQL operations.

What is Pivot in SQL?

The PIVOT operation in SQL allows us to rotate data from rows to


columns. This can be particularly useful when we need
to summarize, aggregate, or reorganize data for reporting purposes.
When we apply PIVOT, each unique value in a column is turned into its own
column, and the data is aggregated based on a specified function, such
as SUM, AVG, COUNT, etc.

Syntax:

SELECT (ColumnNames)
FROM (TableName)
PIVOT
(
AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias) //Alias is a temporary name for a table
Example of Pivot Operation:

Let’s say we have a sample table geeksforgeeks that contains data


about various courses, their categories, and their prices. We can use
the PIVOT operator to summarize the total price for each course category.

Pric
CourseName CourseCategory e

500
C PROGRAMMING
0

600
JAVA PROGRAMMING
0

800
PYTHON PROGRAMMING
0

PLACEMENT INTERVIEWPREPARATI 500


100 ON 0

Query:

SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION


FROM geeksforgeeks
PIVOT
(
SUM(Price)
FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION )
) AS PivotTable
Output

Output of Pivot operation

Explanation:

The PIVOT operation reorganizes the data, transforming


the CourseCategory values into columns, while the SUM(Price) function
aggregates the prices based on these categories. Notice that the original
rows are now represented as columns.

What is Unpivot in SQL?

The UNPIVOT operation in SQL is the reverse of PIVOT. It allows us to


convert columns back into rows, which can be useful when we need
to normalize or restructure data after performing a pivot
operation. UNPIVOT helps in data analysis where row-based operations
are required for analysis.

Syntax:

SELECT (ColumnNames)
FROM (TableName)
UNPIVOT
(AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias)

Example of Unpivot Operation:

Now, we use the same table "geeksforgeeks" created in the above


example and apply the UNPIVOT operation to reverse the PIVOT operation
above and retrieve the original data.

Query:
SELECT CourseName, CourseCategory, Price
FROM
(
SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION
FROM geeksforgeeks
PIVOT
(
SUM(Price)
FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)
) AS PivotTable
) AS P
UNPIVOT
(
Price FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)
) AS UnpivotTable;

Output

Output of Unpivot operation

Explanation:

The UNPIVOT operation transforms the column-based data (PROGRAMMING


and INTERVIEWPREPARATION) back into rows, allowing us to return to the
original structure. It essentially reverts the result set from
the PIVOT operation.

When to Use Pivot and Unpivot in SQL

 PIVOT: When you need to summarize or aggregate data and display it


in a columnar format, typically for reporting purposes.

 UNPIVOT: When you need to convert column data back to rows, often
after performing a PIVOT operation, for normalization or further
analysis.
Conclusion

Understanding the difference between PIVOT and UNPIVOT is essential for


advanced SQL querying. These operations allow you to manipulate our data
by rotating it, making it easier to analyze and report on. Whether we're
transforming data for better presentation (using PIVOT) or reverting it back
to a more normalized form (using UNPIVOT), mastering these SQL
operations will significantly enhance our ability to work with relational
databases.

SQL Triggers

A trigger is a special stored procedure in a database that automatically


executes when specific events (like INSERT, UPDATE, or DELETE) occur on a
table. Triggers help automate tasks, maintain data consistency, and record
database activities. Each trigger is tied to a particular table and runs without
manual execution.

Uses of SQL Triggers

 Automation: Handles repetitive tasks.

 Data Integrity: Ensures clean and accurate data.

 Business Rules: Enforces database logic.

 Audit Trails: Tracks and records changes.

Syntax:

create trigger [trigger_name]

[before | after]

{insert | update | delete}

on [table_name]

FOR EACH ROW


BEGIN

END;

In this explanation:

 trigger_name: The name of the trigger to be created

 BEFORE | AFTER: Specifies whether the trigger is


fired before or after the triggering event (INSERT, UPDATE, DELETE).

 {INSERT | UPDATE | DELETE}: Specifies the operation that will


activate the trigger.

 table_name: The name of the table the trigger is associated with.

 FOR EACH ROW: Indicates that the trigger is row-level, meaning it


executes once for each affected row.

 trigger_body: The SQL statements to be executed when the trigger is


fired.

Types of SQL Triggers

Triggers can be categorized into different types based on the action they are
associated with:

1. DDL Triggers

The Data Definition Language (DDL) command events such as Create_table,


Create_view, drop_table, Drop_view, and Alter_table cause the DDL
triggers to be activated. They allow us to track changes in the structure of
the database. The trigger will prevent any table creation, alteration, or
deletion in the database.

Example: Prevent Table Deletions

CREATE TRIGGER prevent_table_creation

ON DATABASE

FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE

AS

BEGIN

PRINT 'you can not create, drop and alter table in this database';

ROLLBACK;
END;

Output:

2. DML Triggers

DML triggers fire when we manipulate data with commands like INSERT,
UPDATE, or DELETE. These triggers are perfect for scenarios where we need
to validate data before it is inserted, log changes to a table, or cascade
updates across related tables.

Example: Prevent Unauthorized Updates Let’s say you want to prevent users
from updating the data in a sensitive students table. We can set up a trigger
to handle that:

CREATE TRIGGER prevent_update

ON students

FOR UPDATE

AS

BEGIN

PRINT 'You can not insert, update and delete this table i';

ROLLBACK;

END;

Output:

DML Trigger

3. Logon Triggers
Logon triggers fire in response to user logon events. They are used to
monitor login activity, restrict access, or limit active sessions for a login.
Messages and errors from these triggers appear in the SQL Server error log.
However, they cannot handle authentication errors.

Example: Track User Logins

CREATE TRIGGER track_logon

ON LOGON

AS

BEGIN

PRINT 'A new user has logged in.';

END;

Real-World Use Cases of SQL Triggers

1. Automatically Updating Related Tables (DML Trigger Example)

Triggers can automatically perform tasks, like updating related tables when
data changes. Imagine we have a database for students, where the
student_gradestable holds individual subject grades. If the grade of a student
is updated, we may also need to update the total_scorestable.

CREATE TRIGGER update_student_score

AFTER UPDATE ON student_grades

FOR EACH ROW

BEGIN

UPDATE total_scores
SET score = score + :new.grade

WHERE student_id = :new.student_id;

END;

This ensures that every time a student's grade is updated, the total score in
the total_scores table is automatically recalculated.

2. Data Validation (Before Insert Trigger Example)

Triggers can be used to validate data before it is inserted into a table,


ensuring that the data follows specific business rules. For instance, we may
want to ensure that the grades being inserted are within a valid range (say 0
to 100).

CREATE TRIGGER validate_grade

BEFORE INSERT ON student_grades

FOR EACH ROW

BEGIN

IF :new.grade < 0 OR :new.grade > 100 THEN

RAISE_APPLICATION_ERROR(-20001, 'Invalid grade value.');

END IF;

END;

The trigger checks if the inserted grade is valid. If not, it throws an error and
prevents the insertion.

Viewing and Managing Triggers in SQL

If we are working with many tables across multiple databases, we can use a
simple query to list all available triggers in our SQL Server instance. This is
helpful for tracking and managing triggers, especially when dealing with
tables that have similar names across databases.

SELECT name, is_instead_of_trigger

FROM sys.triggers

WHERE type = 'TR';

Key Terms
 name: The name of the trigger.

 is_instead_of_trigger: Whether the trigger is an INSTEAD OF trigger.

 type = 'TR': This filters the results to show only triggers.

The SQL Server Management Studio makes it very simple to display or list all
triggers that are available for any given table. The following steps will help
us accomplish this: Go to the Databases menu, select the desired database,
and then expand it.

 Select the Tables menu and expand it.

 Select any specific table and expand it.

 We will get various options here. When we choose the Triggers option,
it displays all the triggers available in this table.

BEFORE and AFTER Triggers

SQL triggers can be specified to run BEFORE or AFTER the triggering event.

 BEFORE Triggers: These run before the action (INSERT, UPDATE,


DELETE) is executed. They’re great for data validation or modifying
values before they are committed to the database.

 AFTER Triggers: Execute after the SQL statement completes. Useful


for logging or cascading updates to other tables.

Example: Using BEFORE Trigger for Calculations

Given Student Report Database, in which student marks assessment is


recorded. In such a schema, create a trigger so that the total and
percentage of specified marks are automatically inserted whenever a record
is inserted. Here, a trigger will invoke before the record is inserted so
BEFORE Tag can be used.

Query

mysql>>desc Student;

Output:
Student Datatype

Below SQL statement will create a trigger in the student database in which
whenever subjects marks are entered, before inserting this data into the
database, the trigger will compute those two values and insert them with the
entered values. In this way, triggers can be created and executed in the
databases.

Stud_marks

Output:

Output
SQL Hosting

SQL is the foundation of today’s database management systems. It is used to


create, retrieve, and process data. As organizations and applications rely
more and more on databases for storing and managing data, the hosting
environment has a critical role to play in delivering high-performance,
secure, and scalable SQL databases.

The article explores the concept of SQL- Hosting and delves into its
significance and various types. The article also covers the necessity for SQL
hosting in this era of databases where efficient data management is very
essential. Furthermore, the article explains the popular SQL hosting
databases such as Oracle, MYSQL, MS Access, and MS SQL highlighting their
features and suitability for web applications based on their purpose.

What is Hosting?

In the dynamic world of the internet, data is very important. Hence efficient
data management is very crucial for all web applications. Web hosting helps
us in data storage, thus reducing the cost and load of local storage. Almost
all websites require some kind of storage to store their content and data.
Web hosting allows data storage and thus helps reduce the cost of storing
data at local storage. It also comes with built-in support for security and
backups. A hosted database is stored on the server and its ownership is with
a third -party.

What is SQL Hosting?

SQL is an acronym for Structured Programming Language. SQL hosting is


the process of managing some databases using SQL. SQL is used to
access data stored in those databases. Through SQL hoisting we can
manage any Relational Database Management Systems linked to a website
using SQL. Any data of the website will be stored can be accessed using this.

If your web server is hosted on an Internet Service Provider (ISP) there are
various SQL hosting plans available.

Types of Hosting

SQL Hosting has various types that offer user a wide range of scalability,
performance, and cost, which gives organizations to freedom to choose the
most suitable option based on their need and requirements. SQL Hosting is
classified as:

 On-Premises Hosting

 Cloud Hosting

 Shared Hosting

 Dedicated Hosting

 Managed Hosting

 Serverless Hosting

On -Premises Hosting

On-Premises hosting involves the deploying of the SQL databases on server


that are located within the organization's premises. This way of hosting
provides full control over software as well as hardware. It helps to maintain
data security and assure users the optimum data protection as the hosting is
done in one location. One of the limitation of on-site hosting is the limit on
the storage space.

Cloud Hosting

Cloud Hosting involves hosting SQL databases on the virtual servers provided
by a cloud service provider. In this type of hosting, we get scalability,
flexibility and cost effectiveness as data can be scaled as per our
convenience. Some of the popular cloud hosting platforms are Microsoft
Azure, and Amazon Web Services(AWS).

Shared Hosting

When multiple websites share resources on a single server it comes under


Shared Hosting. Shared hosting is cost efficient, but if websites with high
traffic use the same server the performance would be declined.

Dedicated Hosting

Dedicated Hosting involves having a dedicated server only used for hosting
databases. They have high performance and security. They require technical
expertise for managing them and also are more expensive than shared
hosting.

Managed Hosting

The management of SQL databases is a task, when we outsource the


management of SQL database to a third-party provider this is known as
Managed Hosting. They have high security, have backups, and also provide
optimized performance.

Serverless Hosting

Serverless Hosting is also popularly known as Function as a Service(Faas), in


this type of hosting we do not need to manage the underlying infrastructure
when deploying on database. In this type, the developers only pay for the
resources that are used by the database query or transactions. It is cost-
effective when used for the right type of application. Some common
examples are Azure Functions and Google Cloud Functions.

Why Do We Need SQL Hosting?

The main purpose of SQL Hosting is to manage any Relational


Database Management Systems linked to your website this is done
using SQL. SQL is used to communicate with the database. It is with the help
of SQL that tasks such as updation on the data stored in the database, or the
retrieval of that data is done. For the websites that are hosted on
the Internet Service Provider(ISPs), various SQL hosting plans are available to
fulfill the diverse needs.

Some of the popular SQL hosting databases are:

Oracle

Oracle is a database that can be used for websites that have high traffic. It is
a preferred choice in the popular and demanding web applications. It is very
popular because of its various features like:

 High performance

 Robust

 Cost effectiveness

 Faster data access

 Low latency

MySQL

MySQL is a very popular Relational Database Management System used to


store data. It is easy to handle with various servers. Some reasons behind
the popularity of MySQL are:

 High performance

 High security

 Fast retrieval

 Cost effective

MS SQL Server

Microsoft SQL Server popularly known as MS SQL Server was developed by


Microsoft and its first release was in 1989. It can be used with websites that
have very high traffic. MS SQL Server has several features which make it
widely used:

 High scalability

 Easy to use

 High security

 High capacity to handle traffic

MS Access

When we have a website that does not require the usage of a complex
database we can use MS Access. It cannot be used for websites which have
high traffic. MS Access is much less efficient than MySQL, Oracle, or MS SQL.

Advantages of MS Access are:

 Cost-effective

 Easy to use

Examples of SQL Hoisting

E-commerce Websites: Nowadays, almost everyone uses E-commerce


sites to purchase items, as day by day online buyers increase the
management of that data also becomes a task. To manage this data
efficiently SQL hoisting is used. E-commerce platforms rely on SQL hosting to
manage product catalogs, customer data, order information, and transaction
records.

Social Media Platform: Social Media Platform widely use SQL Hosting for
storing and fast retrieval of data. The post that user updates, user profile,
user connections, etc. is all possible through SQL Hosting.

Conclusion

In conclusion, SQL hosting is the process of managing databases using SQL,


which is used to access stored data in the databases. The article also
discusses the various types of SQL Hosting and its advantages and
disadvantages. It is very important to see the advantages and limits of the
various SQL hoisting databases so that according to our requirement we can
use them.The choice should be based on factors such as the web application
needs to align with which features provided by these SQL hoisting databases.
The choice should be based on factors such as security it provides, the level
of scalability, performance. A informative decision of these aspects will
ensure selection of optimal SQL hosting database and this will result in
enhanced performance and data management.

SQL Performance Tuning

Last Updated : 23 Jul, 2025

SQL performance tuning is an essential aspect of database


management that helps improve the efficiency of SQL queries and
ensures that database systems run smoothly. Properly tuned
queries execute faster, reducing response times and minimizing the
load on the server
In this article, we'll discuss various techniques, tools, and strategies used
for SQL performance tuning. By mastering these concepts, we can
optimize our SQL queries and achieve superior performance in our database.

What is SQL Performance Tuning?

SQL performance tuning is the process of optimizing SQL queries to improve


the speed and efficiency of database operations. It involves various
techniques to optimize the execution of queries, manage system
resources more effectively, and ensure that the database responds quickly
to user requests.

Optimizing SQL performance is crucial because poorly optimized


queries can severely affect the speed of the database, increase CPU
usage, and lead to system downtime. By improving query execution
times and resource utilization, performance tuning enhances the overall
performance of the SQL database.

Factors Affecting SQL Speed

Some of the major factors that influence the computation and execution time
in SQL are:

 Table Size: Larger tables with millions of rows can slow down query
performance if the query hits a large number of rows.

 Joins: The use of complex joins, especially when joining multiple


tables, can significantly affect query execution time.

 Aggregations: Queries that aggregate large datasets require more


processing time and resources.

 Concurrency: Simultaneous queries from multiple users can


overwhelm the database, leading to slow performance.

 Indexes: Proper indexing speeds up data retrieval but, when misused,


can lead to inefficiencies.

Ways to Find Slow SQL Queries in SQL Server

1. Creating an Execution Plan

SQL Server Management Studio allows users to view the execution plan,
which details how SQL Server processes a query. This plan helps identify
inefficiencies like missing indexes or unnecessary table scans. To create an
execution plan:
 Start by selecting "Database Engine Query" from the toolbar of SQL
Server Management Studio.

 Enter the query after that, and then select "Include Actual Execution
Plan" from the Query option.

 It's time to run your query at this point. You can do that by pressing F5
or the "Execute" toolbar button.

 The execution plan will then be shown in the results pane, under the
"Execution Pane" tab, in SQL Server Management Studio.

2. Monitor Resource Usage

SQL Server's performance is closely tied to resource usage (CPU, memory,


and disk). Monitoring tools like Windows Performance Monitor can track
these metrics and highlight performance bottlenecks. We may view SQL
Server objects, performance counters, and other object activity with it.
Simultaneously watch Windows and SQL Server counters with System
Monitor to see if there is any correlation between the two services'
performance.

3. Use SQL DMVs to Find Slow Queries

The abundance of dynamic management views (DMVs) that SQL Server


includes is one of its best features, helping identify slow-running queries,
execution plans, and resource consumption. DMVs such
as sys.dm_exec_query_stats can be used to track query performance.

SQL Query Optimization Techniques

Inefficient queries or those containing errors can consume excessive


resources in the production database, leading to slower performance or
even disconnecting other users. It's important to optimize queries to
minimize their impact on overall database performance.

In this section, we’ll discuss several effective SQL performance tuning


techniques, along with practical examples, that can help optimize
queries and improve database efficiency. These methods focus on
reducing resource consumption and improving execution speed,
ensuring a smoother and faster user experience.

1. SELECT fields instead of using SELECT *

Using SELECT * retrieves all columns from a table, but if you only
need specific columns, this can unnecessarily increase processing time.
Instead, specify the columns needed. By using the SELECT statement, one
may direct the database to only query the data we actually need to suit your
business needs. For example:

Inefficient:

Select * from GeeksTable;

Efficient:

SELECT FirstName, LastName,


Address, City, State, Zip FROM GeeksTable;

2. Avoid SELECT DISTINCT

It is practical to get rid of duplicates from a query by using SELECT


DISTINCT. To get separate results, SELECT DISTINCT GROUPs for every field in
the query. However, a lot of computing power is needed to achieve this goal.
Instead of using DISTINCT, refine your query to return unique results
naturally by adjusting the selection criteria.

Inefficient:

SELECT DISTINCT FirstName, LastName,


State FROM GeeksTable;

Efficient:

SELECT FirstName, LastName,


State FROM GeeksTable WHERE State IS NOT NULL;

3. Use INNER JOIN Instead of WHERE for Joins

Joining tables using the WHERE clause can lead to inefficiencies and
unnecessary computations. It's more efficient to use INNER JOIN or LEFT
JOIN for combining tables.

Inefficient:

SELECT GFG1.CustomerID, GFG1.Name, GFG1.LastSaleDate


FROM GFG1, GFG2
WHERE GFG1.CustomerID = GFG2.CustomerID

Efficient:

SELECT GFG1.CustomerID, GFG1.Name, GFG1.LastSaleDate


FROM GFG1
INNER JOIN GFG2
ON GFG1.CustomerID = GFG2.CustomerID

4. Use WHERE Instead of HAVING

The HAVING clause is used after aggregation and can be less efficient. When
possible, use WHERE to filter results before aggregation to speed up the
query. A WHERE statement is more effective if the goal is to filter a query
based on conditions. Assuming 500 sales were made in 2019, for instance,
query to find how many sales were made per client that year.

Inefficient:

SELECT GFG1.CustomerID, GFG1.Name, GFG1.LastSaleDate


FROM GFG1 INNER JOIN GFG2
ON GFG1.CustomerID = GFG2.CustomerID
GROUP BY GFG1.CustomerID, GFG1.Name
HAVING GFG2.LastSaleDate BETWEEN "1/1/2019" AND "12/31/2019"

Efficient:

SELECT GFG1.CustomerID, GFG1.Name, GFG1.LastSaleDate


FROM GFG1 INNER JOIN GFG2
ON GFG1.CustomerID = GFG2.CustomerID
WHERE GFG2.LastSaleDate BETWEEN "1/1/2019" AND "12/31/2019"
GROUP BY GFG1.CustomerID, GFG1.Name

5. Limit Wildcards to the End of a Search Term

Wildcards enable the broadest search when searching unencrypted


material, such as names or cities. However, the most extensive search is
also the least effective. Using wildcards like % at the beginning of a string
makes it difficult for SQL to efficiently use indexes. It's better to place them
at the end of the search term.

Inefficient:

SELECT City FROM GeekTable WHERE City LIKE ‘%No%’

Efficient:

SELECT City FROM GeekTable WHERE City LIKE ‘No%’

6. Use LIMIT for Sampling Query Results

Limiting the results using LIMIT can help avoid querying the entire table
when first testing or analyzing a query. Only the given number of records are
returned by the LIMIT statement. By using a LIMIT statement, we can avoid
stressing the production database with a big query only to discover that it
needs to be edited or improved.

Query:

SELECT GFG1.CustomerID, GFG1.Name, GFG1.LastSaleDate


FROM GFG1
INNER JOIN GFG2
ON GFG1.CustomerID = GFG2.CustomerID
WHERE GFG2.LastSaleDate BETWEEN "1/1/2019" AND "12/31/2019"
GROUP BY GFG1.CustomerID, GFG1.Name
LIMIT 10

7. Run Queries During Off-Peak Hours

Running heavy queries during off-peak hours reduces the load on the
database, minimizing the impact on other users. About planning any query to
run at a time when it won't be as busy in order to reduce the impact of our
analytical queries on the database. When the number of concurrent users is
at its lowest, which is often overnight, the query should be executed.

Index Tuning

When choosing and building indexes, database tuning includes index


tuning. The index tuning objective is to speed up query processing. It
can be challenging to employ indexes in dynamic contexts with numerous
ad-hoc searches scheduled in advance. The queries that are based on
indexes are subject to index tweaking, and the indexes are generated
automatically as needed. Users of the database do not need to take any
specific activities to tune the index.

Advantages of Index Tuning

The performance of queries and databases can be improved by using the


Index tuning wizard. It accomplishes this using the following methods:

 Recommendations for optimal index usage based on query optimizer


analysis and workload

 Examination of changes in query distribution, index utilization, and


performance to determine impact

 Suggestion of fine-tuning strategies for problematic queries

 Use of SQL Profiler to record activity traces and improve performance


Points to consider while creating indexes:

 Short indexes for reduced disk space and faster comparisons

 Distinct indexes with minimal duplicates for better selectivity

 Clustered indexes covering all row data for optimal performance

 Static data columns for clustered indexes to minimize shifting

SQL Performance Tuning Tools

Utilizing index tuning tools and following best practices is essential for
maintaining high-performing SQL Server environments. Regular
monitoring, proactive maintenance, and continuous improvement are key to
optimizing database performance and supporting critical business
applications.

Several SQL performance tuning tools can help identify and optimize
database performance. Some of the popular tools include:

 SQL Sentry (SolarWinds)

 SQL Profiler (Microsoft)

 SQL Index Manager (Red Gate)

 SQL Diagnostic Manager (IDERA)

These tools assist with monitoring, identifying slow queries, and


recommending optimization strategies for improving database performance.

Conclusion

SQL performance tuning is important for ensuring


efficient database operations, especially as the size and complexity of
databases grow. By utilizing best practices for query
optimization, indexing, and performance monitoring, we can significantly
improve our database’s response time and reduce system resource
usage. Regular maintenance and performance tuning should be an integral
part of database management for businesses relying on SQL databases for
critical operations.
SQL Stored Procedures

Stored procedures are precompiled SQL statements that are stored in


the database and can be executed as a single unit. SQL Stored
Procedures are a powerful feature in database management
systems (DBMS) that allow developers to encapsulate SQL code and
business logic. When executed, they can accept input parameters and return
output, acting as a reusable unit of work that can be invoked multiple times
by users, applications, or other procedures.
What is a SQL Stored Procedure?

A SQL Stored Procedure is a collection of SQL statements bundled


together to perform a specific task. These procedures are stored in the
database and can be called upon by users, applications, or other procedures.
Stored procedures are essential for automating database tasks,
improving efficiency, and reducing redundancy. By encapsulating logic
within stored procedures, developers can streamline their workflow and
enforce consistent business rules across multiple applications and
systems.

Syntax:

CREATE PROCEDURE procedure_name


(parameter1 data_type, parameter2 data_type, ...)
AS
BEGIN
-- SQL statements to be executed
END

Key Terms

 CREATE PROCEDURE: This keyword creates the stored procedure


with the given name.

 @parameter1, @parameter2: These are input parameters that allow


you to pass values into the stored procedure.

 BEGIN...END: These keywords define the block of SQL statements that


make up the procedure body.

Types of SQL Stored Procedures

SQL stored procedures are categorized into different types based on their
use case and functionality. Understanding these categories can help
developers choose the right type of procedure for specific scenario

1. System Stored Procedures

These are predefined stored procedures provided by the SQL Server for
performing administrative tasks such as database management,
troubleshooting, or system configuration. Examples include:

 sp_help for viewing database object information

 sp_rename for renaming database objects.


2. User-Defined Stored Procedures (UDPs)

These are custom stored procedures created by the user to perform specific
operations. User-defined stored procedures can be tailored to a business's
needs, such as calculating totals, processing orders, or generating reports.
For example, creating a procedure that calculates the total sales for a
particular product category.

3. Extended Stored Procedures

These allow for the execution of external functions, which might be


implemented in other languages such as C or C++. Extended procedures
provide a bridge between SQL Server and external applications or tools, such
as integrating third-party tools into SQL Server.

4. CLR Stored Procedures

These are stored procedures written in .NET languages (like C#) and
executed within SQL Server. CLR stored procedures are useful when
advanced functionality is needed that isn't easily achievable with T-SQL
alone, such as complex string manipulation or working with external APIs.

Why Use SQL Stored Procedures?

There are several key reasons why SQL Stored Procedures are widely used in
database management:

1. Performance Optimization: Since stored procedures are


precompiled, they execute faster than running ad-hoc SQL queries. The
database engine can reuse the execution plan, eliminating the need for
repeated query parsing and optimization.

2. Security and Data Access Control: By using stored procedures,


developers can restrict direct access to sensitive data. Users can
execute procedures without accessing the underlying tables, helping to
protect critical information.

3. Code Reusability and Maintainability: SQL stored procedures can


be reused in multiple applications or different parts of an application.
This reduces the need to rewrite complex queries repeatedly.

4. Reduced Network Traffic: Instead of sending multiple individual


queries to the database server, stored procedures allow you to execute
multiple operations in one go, reducing network load.
5. Maintainability: Stored procedures simplify code maintenance.
Changes made to the procedure are automatically reflected wherever
the procedure is used, making it easier to manage complex logic.

Example of Creating a Stored Procedure

In this example, we create a stored procedure


called GetCustomersByCountry, which accepts a Country parameter and
returns the CustomerName and ContactName for all customers from that
country. The procedure is designed to query the Customers table, which
contains customer information, including their names, contact details,
and country.

Customers Table

By passing a country as a parameter, the stored procedure dynamically


fetches the relevant customer details from the table

Query:

-- Create a stored procedure named "GetCustomersByCountry"


CREATE PROCEDURE GetCustomersByCountry
@Country VARCHAR(50)
AS
BEGIN
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = @Country;
END;

-- Execute the stored procedure with parameter "Sri lanka"


EXEC GetCustomersByCountry @Country = 'Sri lanka';

Output
CustomerNa Contact
me Name

Naveen Tulasi

Note: We will need to make sure that the user account has the necessary
privileges to create a database. We can try logging in as a different
user with administrative privileges or contact the database administrator to
grant the necessary privileges to our user account. If we are using a cloud-
based database service, make sure that we have correctly configured the
user account and its permissions.

Advantages of Using SQL Stored Procedures

1. Improved Performance: Stored procedures are precompiled,


meaning they execute faster than running multiple individual queries.

2. Enhanced Security: Users can be granted permission to execute


stored procedures without directly accessing the underlying tables.

3. Code Reusability: Stored procedures allow for reusability, making it


easier to maintain and update code.

4. Reduced Network Traffic: By bundling multiple SQL statements into


one call, stored procedures reduce network load and improve
application performance.

5. Better Error Handling: SQL stored procedures provide a structured


way to manage errors using TRY...CATCH blocks.

Real-World Use Cases for SQL Stored Procedures

1. Order Processing System In an e-commerce application, a stored


procedure can automate the process of inserting new orders, updating
stock levels, and generating invoices.

2. Employee Management System A stored procedure can be used to


calculate salaries for employees, deduct taxes, and generate monthly
salary slips.

3. Data Validation Use stored procedures to validate data before it’s


inserted into the database. For example, checking if an email address
already exists before adding a new user.
4. Audit Logs Create a stored procedure that automatically logs changes
to sensitive data, such as changes to user roles or permissions, for
security and auditing purposes.

Best Practices for Writing SQL Stored Procedures

1. Keep Procedures Simple and Modular

Avoid making stored procedures too complex. Break up larger tasks into
smaller, more manageable procedures that can be combined as needed. This
improves readability and maintainability.

2. Use Proper Error Handling

Always use TRY...CATCH blocks to handle exceptions gracefully. This


ensures that errors are caught and logged, and the procedure can handle
unexpected scenarios without crashing.

3. Limit the Use of Cursors

While cursors can be useful, they are often less efficient than set-based
operations. Use cursors only when necessary, and consider alternatives
like WHILE loops or CTEs (Common Table Expressions).

4. Avoid Hardcoding Values

Instead of hardcoding values directly in stored procedures, use parameters


to make procedures more flexible and reusable across different contexts.

5. Optimize for Performance

Consider indexing, query optimization, and avoiding unnecessary joins within


stored procedures. Well-optimized queries in stored procedures ensure that
performance does not degrade as the database grows.

Conclusion

SQL stored procedures are an essential part of SQL development, offering


benefits such as improved performance, security, and maintainability.
By encapsulating SQL queries into reusable units, stored procedures simplify
database management, enhance efficiency, and ensure consistent business
logic execution. By using stored procedures, we can automate tasks,
minimize the risk of SQL injection, and ensure consistent execution of
complex SQL logic. Stored procedures are integral to modern database
management and an important component in building scalable, efficient, and
secure database systems.
SQL TRANSACTIONS

Last Updated : 30 Aug, 2025


An SQL transaction is a sequence of one or more SQL operations


(e.g., INSERT, UPDATE, DELETE) executed as a single unit of work.
Transactions ensure that either all operations succeed or none are applied,
maintaining data integrity.

Key Properties of SQL Transactions: ACID

The integrity of SQL transactions is governed by the ACID properties, which


guarantee reliable database transactions. These four properties work
together to guarantee that the database remains consistent and reliable.

 Atomicity: The outcome of a transaction can either be completely


successful or completely unsuccessful. The whole transaction must be
rolled back if one part of it fails.

 Consistency: Transactions maintain integrity restrictions by moving


the database from one valid state to another.

 Isolation: Concurrent transactions are isolated from one another,


assuring the accuracy of the data.

 Durability: Once a transaction is committed, its modifications remain


in effect even in the event of a system failure.

SQL Transaction Control Commands

In SQL, transaction control commands manage the execution of SQL


operations, ensuring the integrity and reliability of database
transactions. These commands help manage the start, commit, and
rollback of changes made to the database. Below are the key transaction
control commands in SQL, explained with syntax and examples for each.

1. BEGIN TRANSACTION Command

The BEGIN TRANSACTION command marks the beginning of a new


transaction. All SQL statements that follow this command will be part of the
same transaction until a COMMIT or ROLLBACK is encountered. This
command doesn't make any changes to the database, it just starts the
transaction.

Syntax:

BEGIN TRANSACTION transaction_name ;


Example of SQL Transaction with a Bank Transfer Scenario

Let’s look at an example of a bank transfer between two accounts. This


example demonstrates the usage of multiple queries in a single transaction.

BEGIN TRANSACTION;

-- Deduct $150 from Account A


UPDATE Accounts
SET Balance = Balance - 150
WHERE AccountID = 'A';

-- Add $150 to Account B


UPDATE Accounts
SET Balance = Balance + 150
WHERE AccountID = 'B';

-- Commit the transaction if both operations succeed


COMMIT;

If any error occurs, such as an issue with the UPDATE query, you can
use ROLLBACK to undo all changes made during the transaction:

ROLLBACK;

This ensures that the system doesn't end up in an inconsistent state, such as
deducting money from one account without adding it to another.

BEGIN TRANSACTION TransferFunds;

2. COMMIT Command

The COMMIT command is used to save all changes made during the current
transaction to the database. Once a transaction is committed, the changes
are permanent.

Syntax:

COMMIT;

Example

Here is the sample Student table that will be used to perform the operations
in this example. This table contains basic student details such
as ID, name, age, and other relevant information that will be manipulated
using various transaction control commands.
Student Table

Following is an example which would delete those records from the table
which have age = 20 and then COMMIT the changes in the database.

DELETE FROM Student WHERE AGE = 20;


COMMIT;

Output

output

3. ROLLBACK Command

The ROLLBACK command is used to undo all changes made in the current
transaction. It is used when an error occurs or when the desired changes
cannot be completed. The database will revert to the state it was in before
the BEGIN TRANSACTION was executed.

Syntax:

ROLLBACK;

Example

Delete those records from the table which have age = 20 and then
ROLLBACK the changes in the database. In this case, the DELETE operation is
undone, and the changes to the database are not saved.
DELETE FROM Student WHERE AGE = 20;
ROLLBACK;

Output:

output

4. SAVEPOINT Command

A SAVEPOINT is used to create a checkpoint within a transaction. We can roll


back to a specific SAVEPOINT instead of rolling back the entire transaction.
This allows us to undo part of the transaction rather than the entire
transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

Example

SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.

Output:

output
Explanation:

From the above example Sample table1, Delete those records from the
table which have age = 20 and then ROLLBACK the changes in the database
by keeping Savepoints. Here SP1 is first SAVEPOINT created before deletion.
In this example one deletion have taken place. After deletion again
SAVEPOINT SP2 is created.

5. ROLLBACK TO SAVEPOINT

The ROLLBACK TO SAVEPOINT command allows us to roll back the


transaction to a specific savepoint, effectively undoing changes made after
that point.

Syntax:

ROLLBACK TO SAVEPOINT SAVEPOINT_NAME;

Example

Deletion have been taken place, let us assume that we have changed our
mind and decided to ROLLBACK to the SAVEPOINT that we identified as SP1
which is before deletion. So, In this case the DELETE operation is undone,
and the transaction is returned to the state it was in at the SP1 savepoint.

ROLLBACK TO SP1;
//Rollback completed

Output:

output

6. RELEASE SAVEPOINT Command

This command is used to remove a SAVEPOINT that we have created. Once


a SAVEPOINT has been released, we can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT. It is
used to initiate a database transaction and used to specify characteristics
of the transaction that follows.

Syntax:

RELEASE SAVEPOINT SAVEPOINT_NAME;

Example

Once the savepoint SP2 is released, we can no longer roll back to it.

RELEASE SAVEPOINT SP2; -- Release the second savepoint.

Why Use Transactions in Banking?

In this case, without a transaction, you risk scenarios where money is


deducted from one account but not added to the other, leaving the system in
an inconsistent state. Transactions ensure that such issues are avoided by
guaranteeing that both operations succeed or fail together.

Types of SQL Transactions

There are different types of transactions based on their nature and the
specific operations they perform:

 Read Transactions: Used to only read the data, typically


with SELECT queries.

 Write Transactions: These involve modifying the data in the


database with INSERT, UPDATE, or DELETE operations.

 Distributed Transactions: These transactions span multiple


databases and ensure consistency across them.

 Implicit Transactions: Automatically started by SQL Server for


certain operations.

 Explicit Transactions: Manually controlled transactions where the


user begins and ends the transaction using BEGIN
TRANSACTION, COMMIT, and ROLLBACK.

Monitoring and Optimizing SQL Transactions

To maintain performance and prevent issues, consider the following


techniques:

1. Monitor Locks: Track locking behavior and adjust queries to minimize


locking conflicts.
2. Limit Transaction Scope: Limit the number of rows or records affected
by a transaction to speed up processing.

3. Use Batch Processing: If you're handling large amounts of data, break


the operations into smaller transactions or batches to avoid overwhelming
the system.

SQL Subquery

A subquery in SQL is a query nested inside another SQL query. It allows


complex filtering, aggregation and data manipulation by using the result of
one query inside another. They are an essential tool when we need to
perform operations like:

 Filtering: selecting rows based on conditions from another query.

 Aggregating: applying functions like SUM, COUNT, AVG with dynamic


conditions.

 Updating: modifying data using values from other tables.


 Deleting: removing rows based on criteria from another query.

While there is no universal syntax for subqueries, they are commonly used in
SELECT statements as follows.

Syntax:

SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);

Common SQL Clauses for Subqueries

Clauses that can be used with subqueries are:

 WHERE: filter rows based on subquery results.

 FROM: treat subquery as a temporary (derived) table.

 HAVING: filter aggregated results after grouping.

Types of Subqueries

1. Single-Row Subquery

 Returns exactly one row as the result.

 Commonly used with comparison operators such as =, >, <

Example:

SELECT * FROM Employees


WHERE Salary = (SELECT MAX(Salary) FROM Employees);

Output: Returns the employee(s) with the highest salary.

2. Multi-Row Subquery

 Returns multiple rows as the result.

 Requires operators that can handle multiple values, such as IN, ANY or
ALL

Example:

SELECT * FROM Employees


WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE
Location = 'New York');
Output: Fetches employees working in all New York departments.

3. Correlated Subquery

 A dependent subquery: it references columns from the outer query.

 Executed once for each row of the outer query, making it slower for
large datasets.

Example:

SELECT e.Name, e.Salary


FROM Employees e
WHERE e.Salary > (SELECT AVG(Salary)
FROM Employees
WHERE DepartmentID = e.DepartmentID);

Output: Returns employees earning more than the average salary of their
own department.

Examples of Using SQL Subqueries

These examples showcase how subqueries can be used for various


operations like selecting, updating, deleting or inserting data, providing
insights into their syntax and functionality. Through these examples, we will
understand flexibility and importance of subqueries in simplifying complex
database tasks.

Consider the following two tables:

Student Table

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ram 101 Chennai 9988775566

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344


ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

New_Student Table

ROLL_N SECTIO
NAME O N

Ravi 104 A

Sumat
105 B
hi

Raj 102 A

Example 1: Fetching Data Using Subquery in WHERE Clause

This example demonstrates how to use a subquery inside the WHERE clause.
The inner query retrieves roll numbers of students who belong to section 'A'
and the outer query fetches their corresponding details (name, location and
phone number) from the Student table.

Query:

SELECT NAME, LOCATION, PHONE_NUMBER


FROM Student
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM New_Student WHERE SECTION = 'A'
);

Output
NAM LOCATIO PHONE_NUMB
E N ER

Rav
Salem 8989898989
i

Coimbato
Raj 8877665544
re

Explanation:

 The subquery SELECT ROLL_NO FROM New_Student WHERE SECTION =


'A' finds roll numbers of students in section A.

 The outer query then uses these roll numbers to fetch details from the
Student table.

 Thus, only Ravi and Raj are returned, since they are in section A.

Example 2: Using Subquery with INSERT

Here we demonstrate how a subquery can be used with INSERT. Instead of


manually entering data, we copy data from another table (Temp_Students)
into the main Student table.

Temp_Students

ROLL_N LOCATI PHONE_NUMB


NAME O ON ER

Ajay 201 Mumbai 9090901234

Meen
202 Delhi 8080805678
a

Query:

INSERT INTO Student


SELECT * FROM Temp_Students;
Output

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Ram 101 Chennai 9988775566

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Ajay 201 Mumbai 9090901234

Meena 202 Delhi 8080805678

Explanation:

 The subquery SELECT * FROM Temp_Students selects all rows from the
helper table.

 The INSERT INTO Student adds these rows into the main Student table.

 Thus, Ajay and Meena are successfully added.

Example 3: Using Subquery with DELETE

In this example, we use a subquery with DELETE to remove certain rows from
the Student table. Instead of hardcoding roll numbers, the subquery finds
them based on conditions.

Query:
DELETE FROM Student
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM Student WHERE ROLL_NO <= 101 OR ROLL_NO =
201
);

Output

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Meena 202 Delhi 8080805678

Explanation:

 The subquery selects roll numbers 101 and 201.

 The outer query deletes students having those roll numbers.

 As a result, Ram (101) and Ajay (201) are removed.

Example 4: Using Subquery with UPDATE

Subqueries can also be used with UPDATE. In this example, we update


student names to "Geeks" if their location matches the result of a subquery.

Query:

UPDATE Student
SET NAME = 'Geeks'
WHERE LOCATION IN (
SELECT LOCATION FROM Student WHERE LOCATION IN ('Salem', 'Delhi')
);

Output

ROLL_N PHONE_NUMB
NAME O LOCATION ER

Coimbator
Raj 102 8877665544
e

Sasi 103 Madurai 7766553344

Geeks 104 Salem 8989898989

Sumat Kanchipura
105 8989856868
hi m

Geeks 202 Delhi 8080805678

Explanation:

 The subquery selects locations 'Salem' and 'Delhi'.

 The outer query updates the NAME field for students whose location
matches those values.

 Thus, Ravi and Meena are renamed to "Geeks".

Example 5: Simple Subquery in the FROM Clause

This example demonstrates using a subquery inside the FROM clause, where
the subquery acts as a temporary (derived) table.

Query:

SELECT NAME, PHONE_NUMBER


FROM (
SELECT NAME, PHONE_NUMBER, LOCATION
FROM Student
WHERE LOCATION LIKE 'C%'
) AS subquery_table;

Output

NAM PHONE_NUMB
E ER

Ra
9988775566
m

Raj 8877665544

Explanation:

 The subquery (SELECT NAME, PHONE_NUMBER, LOCATION FROM


Student WHERE LOCATION LIKE 'C%') fetches students whose location
starts with "C" (Coimbatore, Chennai, etc.).

 The outer query then selects only NAME and PHONE_NUMBER from this
derived table.

 Only Raj qualifies because his location is Coimbatore.

Example 6: Subquery with JOIN

We can also use subqueries along with JOIN to connect data across tables.

Query:

SELECT s.NAME, s.LOCATION, ns.SECTION


FROM Student s
INNER JOIN (
SELECT ROLL_NO, SECTION
FROM New_Student WHERE SECTION = 'A'
) ns
ON s.ROLL_NO = ns.ROLL_NO;

Output
NAM LOCATIO SECTIO
E N N

Rav
Salem A
i

Coimbato
Raj A
re

Explanation: The subquery extracts roll numbers of students in section A.


Joining this with the Student table on ROLL_NO returns Ravi and Raj along
with their locations and section

SQL | SEQUENCES

SQL sequences are an essential feature of relational database


management systems (RDBMS) used to generate unique numeric
values in a sequential order. These values are widely used for
generating primary keys, unique keys, and other numeric identifiers
in databases. SQL sequences offer flexibility, performance, and ease of use,
making them indispensable in managing and organizing data in large-scale
applications.

In this article, we will explain SQL sequences in-depth, explaining how they
work, their advantages, syntax, and real-world use cases.

What Are SQL Sequences?

SQL sequences are user-defined database objects designed to generate a


series of numeric values. Unlike identity columns, which are tightly bound
to specific tables, sequences are independent objects and can be used
across multiple tables. They allow applications to retrieve the next number in
a sequence whenever needed, offering a simple and efficient way to
generate unique numbers on demand.
The values in a sequence can be configured to be generated
in ascending or descending order, and the sequence can be set
to restart (cycle) once the maximum value is exceeded. This makes SQL
sequences particularly useful in scenarios where there is a need for
continuous, unique values, such as generating primary keys or serial
numbers.

Key Features of SQL Sequences

 Automatic Primary Key Generation: Sequences automatically


generate unique values that can be used for primary or unique keys in
database tables.

 Ascending or Descending Order: Sequences can be configured to


generate numbers in either ascending or descending order.

 Multiple Table Usage: A single sequence can be used to generate


values for multiple tables, making it flexible and reusable.

 Independent of Tables: Unlike identity columns, sequences are


independent and can be used across different tables.

 Efficient: Sequences reduce the complexity and overhead of manually


generating unique values, which saves time and reduces application
code.

How SQL Sequences Work

When creating a sequence, we specify the starting point,


the increment (how much the sequence increases with each step), and
optionally the minimum and maximum values. Sequences can be set to
cycle, which means they restart from the beginning when they reach
the maximum value.

Syntax:

CREATE SEQUENCE sequence_name


START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;

Example 1: Creating a Sequence in Ascending Order


CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;

Explanation:

The above query will create a sequence named sequence_1. The sequence
will start from 1 and will be incremented by 1 having maximum value of 100.
The sequence will repeat itself from the start value after exceeding 100.

Example 2: Creating a Sequence in Descending Order

CREATE SEQUENCE sequence_2


start with 100
increment by -1
min value 1
max value 100
cycle;

Explanation:

The above query will create a sequence named sequence_2. The sequence
will start from 100 and should be less than or equal to a maximum value and
will be incremented by -1 having a minimum value of 1.

Using SQL Sequences in Database Operations

Once a sequence is created, it can be used across multiple tables to


generate unique values, such as primary key identifiers or serial
numbers. This allows for consistent, efficient value generation, reducing
the need for manual input and ensuring uniqueness across different rows
and tables.

Example: Using a Sequence to Insert Values

Let's create a students table and use the sequence to automatically


generate unique student IDs. In this example, the NEXTVAL function is used
to retrieve the next value in the sequence (sequence_1) and insert it into
the ID column for each student.

Query:
CREATE TABLE students
(
ID number(10),
NAME char(20)
);

INSERT into students VALUES


(sequence_1.nextval,'Shubham');
INSERT into students VALUES
(sequence_1.nextval,'Aman');

Output

Using Sequence to Insert Values

Cache Management in SQL Sequences

To enhance performance, SQL Server employs cache management for


sequence numbers. The CACHE argument pre-allocates a set number of
sequence values in memory, which reduces disk access during normal
operations.

Example of Cache Management

For instance, if a sequence starts at 1 with a cache size of 15, SQL Server
will allocate values 1-15 in memory. When the 15th value is used, a new
cache with values 16-30 is allocated.

In the event of a server restart, the next sequence number will be the first
unused value in the cache. This approach ensures that sequence numbers
are generated quickly but may cause gaps in the sequence after a server
crash, which is normal.

If we want to avoid gaps, we can set the sequence to NOCACHE, though this
might reduce performance as it requires constant disk access.

Creating a Sequence with Cache

CREATE SEQUENCE sequence_3


START WITH 1
INCREMENT BY 1
CACHE 10;

Practical Use Cases for SQL Sequences

1. Primary Key Generation

Sequences are commonly used to generate unique primary key values for
database tables. This is especially useful in applications where a large
volume of records needs to be inserted into a table, and each record requires
a unique identifier.

2. Serial Numbers and Order IDs

SQL sequences can be used to generate serial numbers for products or


order IDs in e-commerce systems, ensuring that each order has a unique
identifier.

3. Auditing and Tracking

Sequences are also useful for tracking events or transactions that require
unique identifiers, such as logging system activities or generating unique
reference numbers for transactions.

Advantages of Using SQL Sequences

 Efficiency: Sequences simplify the process of generating unique


values without requiring complex application logic.

 Independence: Sequences can be used across multiple tables,


ensuring that unique values are consistently generated without tying
them to a specific table.

 Performance: By using the CACHE feature, sequences can enhance


performance by reducing disk access during value generation.

 Flexibility: SQL sequences can be configured to generate values in


ascending or descending order and can be set to cycle when reaching
the maximum value.

Conclusion

SQL sequences are a fundamental tool for generating unique numeric


values in databases, offering simplicity, flexibility, and improved
performance. Whether we need to generate primary keys, serial numbers,
or unique transaction IDs, sequences provide a reliable and efficient solution.
Understanding how to create and manage sequences, along with
optimizing cache settings, can significantly enhance the performance of
your database operations.

SQL Auto Increment


In SQL databases, a primary key is important for uniquely identifying
records in a table. However, sometimes it is not practical to manually
assign unique values for each record, especially when handling large
datasets. To simplify this process, SQL databases offer an Auto
Increment feature that automatically generates unique numerical
values for a specified column.

This article provides an in-depth guide on how to use the Auto


Increment feature across popular SQL databases such as SQL Server,
MySQL, PostgreSQL, MS Access, and Oracle, with practical examples
and use cases.

1. SQL Server Auto Increment

In SQL Server, the Auto Increment feature is implemented using


the IDENTITY property. This property allows the database to automatically
generate unique numbers for each new record in a table.

 starting_value - specifies where the numbering starts (in this case,


101).

 increment_value -determines how much the value will increase for


each new record (here, it’s 1).

Example

We will create a Student table with fields Student_ID, First_Name,


and Last_Name, we will auto-generate Student_ID by using auto-
increment and will make it the Primary Key for the table. Let the starting
value of IDENTITY be 101 and we will increment the auto-generated
key by 1 for each new record.
CREATE TABLE Students(
Student_ID int IDENTITY(101, 1) PRIMARY KEY,
First_Name varchar(255),
Last_Name varchar(255)
);

Inserting Data with Auto Increment:

To insert a new record into students table, we will not specify the value of
Student_ID as it will be added automatically.

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Deeksha', 'Jain');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Kavisha', 'Parikh');

Output:

2. MySQL Auto Increment

In MySQL, the AUTO_INCREMENT keyword is used to set a column as Auto


Increment. By default, the counter starts at 1 and increases by 1 for each
new row inserted.

Example

We will create Students table with


fields Student_ID, First_Name, Last_Name, we will auto generate
Student_ID by using auto increment and will make it Primary Key for the
table.

CREATE TABLE Students(


Student_ID int AUTO_INCREMENT PRIMARY KEY,
First_Name varchar(255),
Last_Name varchar(255)
);

Inserting Data with Auto Increment:

To insert a new record into students table, we will not specify the value
of Student_ID as it will be added automatically and the first record will have
key as 1 and key for every subsequent record will increase by 1.

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Anish', 'Jain');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Akshita', 'Sharma');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Shruti', 'Sogani');

Output:

Changing Auto Increment Start Value

To change the default starting value we can use ALTER TABLE command as
follows:

ALTER TABLE Students AUTO_INCREMENT = new_value;

Adjusting the Increment Interval:

In MySQL, we can also modify the interval at which


the AUTO_INCREMENT value increases. By default, it increments by 1, but
we can change it using the auto_increment_increment system variable.

To change the increment value (i.e., the step by which the value
increments), we can set the auto_increment_increment variable and
new_interval_value is the interval value we would like to use.
SET @@auto_increment_increment = new_interval_value;

3. PostgreSQL Auto Increment

In PostgreSQL, the SERIAL keyword is used for auto-incrementing a column.


This is a shorthand for creating an integer column that automatically
increments.

Example

We will create Students table with


fields Student_ID, First_Name, Last_Name, we will auto generate
Student_ID by using auto increment and will make it Primary Key for the
table.

CREATE TABLE Students(


Student_ID int SERIAL PRIMARY KEY,
First_Name varchar(255),
Last_Name varchar(255)
);

Inserting Data with Auto Increment

To insert a new record into students table, we will not specify the value of
Student_ID as it will be added automatically.

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Anish', 'Jain');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Akshita', 'Sharma');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Shruti', 'Sogani');

Output:
4. MS Access Auto Increment

In MS Access, the AUTOINCREMENT keyword is used to define a column


that automatically generates unique numeric values. Like MySQL and SQL
Server, the default value starts at 1 and increments by 1.

Example

We will create Students table with


fields Student_ID, First_Name, Last_Name, we will auto generate
Student_ID by using auto increment and will make it Primary Key for the
table.

CREATE TABLE Students(


Student_ID int AUTOINCREMENT PRIMARY KEY,
First_Name varchar(255),
Last_Name varchar(255)
);

Inserting Data with Auto Increment:

To insert a new record into students table, we will not specify the value
of Student_ID as it will be added automatically and the first record will have
key as 1 and key for every subsequent record will increase by 1.

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Anish', 'Jain');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Akshita', 'Sharma');

INSERT INTO Students(First_Name, Last_Name )


VALUES ('Shruti', 'Sogani');
Output:

Changing Auto Increment Starting Value:

In MS Access, to change the default starting value and increment


value we can use Autonumber Settings in the Table Design view as
follows:

AUTOINCREMENT(starting_value, increment_value)

Here starting_value is the starting value we would like to use


and increment_value is the value by which we would like to increment the
key for the subsequent record.

5. Oracle Auto Increment

In Oracle, to use auto increment feature we have to make the auto-


increment field with the sequence object which successively
generates a number sequence. The sequence generates a series of
numbers that can be used to auto-increment the primary key.

Syntax

CREATE SEQUENCE sequence_name


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;

Key Terms

 START WITH 101: Begins the sequence from 101.

 INCREMENT BY 1: Increments the value by 1 for each new record.

Example
The code below creates a sequence object called seq_students, that
starts with 101 and can increment by 1. It'll also cache up to 20 values for
performance.

CREATE SEQUENCE seq_students


MINVALUE 1
START WITH 101
INCREMENT BY 1
CACHE 20;

Inserting Data with Auto Increment

To insert a new record into the "Students" table, we will have to use
the nextval function that retrieves the next value from seq_students
sequence:

INSERT INTO Students(Student_ID, First_Name, Last_Name)


VALUES (seq_students.nextval, 'Deeksha', 'Jain');

INSERT INTO Students(Student_ID, First_Name, Last_Name)


VALUES (seq_students.nextval, 'Kavisha', 'Parikh');

Output:

Example 4

Conclusion

The Auto Increment feature simplifies the process of managing unique


values for primary keys across different SQL databases. Whether we are
working with SQL Server, MySQL, PostgreSQL, MS Access, or Oracle,
implementing auto-incrementing columns can help maintain data integrity
and streamline database management. This feature ensures that each new
record gets a unique identifier, automatically incrementing based on
the configuration specified during the table creation.
Window Functions in SQL

SQL window functions allow performing calculations across a set of rows that
are related to the current row, without collapsing the result into a single
value. They are commonly used for tasks like aggregates, rankings and
running totals.

The OVER clause defines the “window” of rows for the calculation. It can:

 PARTITION BY: divide the data into groups.

 ORDER BY: specify the order of rows within each group.

With this, functions such as SUM(), AVG(), ROW_NUMBER(), RANK() and


DENSE_RANK() can be applied in a controlled way.

Syntax

SELECT column_name1,
window_function(column_name2)
OVER ([PARTITION BY column_name3] [ORDER BY column_name4]) AS
new_column
FROM table_name;

Key Terms

 window_function: Any aggregate or ranking function (SUM(), AVG(),


ROW_NUMBER(), etc.)

 column_name1: Regular column(s) to be selected in the


outputand column_name2: Column on which the window function is
applied

 column_name3: Column used for dividing rows into groups


(PARTITION BY)and column_name4: Column used to define order of
rows within each partition (ORDER BY)

 new_column: Alias for calculated result of the window function

 table_name: table from which data is selected

Types of Window Functions in SQL

SQL window functions can be categorized into two primary


types: aggregate window functions and ranking window functions.
These two serve different purposes but share a common ability to perform
calculations over a defined set of rows while retaining the original data.

To understand these types better, we will use an Employees table that stores
details like employee name, age, department and salary.

Employees Table

Ag Departm Salar
Name e ent y

Rames 50,00
20 Finance
h 0

50,00
Suresh 22 Finance
0

Ram 28 Finance 20,00


Ag Departm Salar
Name e ent y

30,00
Deep 25 Sales
0

Pradee 20,00
22 Sales
p 0

1. Aggregate Window Function

Aggregate window functions calculate aggregates over a window of rows


while retaining individual rows. Common aggregate functions include:

 SUM(): Sums values within a window.

 AVG(): Calculates the average value within a window.

 COUNT(): Counts the rows within a window.

 MAX(): Returns the maximum value in the window.

 MIN(): Returns the minimum value in the window.

Example: Using AVG() to Calculate Average Salary within each department

SELECT Name, Age, Department, Salary,


AVG(Salary) OVER( PARTITION BY Department) AS Avg_Salary
FROM employee

Output

Ag Departm Salar Avg_Sal


Name e ent y ary

Rames 50,00
20 Finance 40,000
h 0
Ag Departm Salar Avg_Sal
Name e ent y ary

50,00
Suresh 22 Finance 40,000
0

20,00
Ram 28 Finance 40,000
0

30,00
Deep 25 Sales 25,000
0

Pradee 20,00
22 Sales 25,000
p 0

Explanation:

 For Finance: (50,000 + 50,000 + 20,000) ÷ 3 = 40,000.

 For Sales: (30,000 + 20,000) ÷ 2 = 25,000.

 This average is repeated for each employee in the same department.

2. Ranking Window Functions

These functions provide rankings of rows within a partition based on specific


criteria. Common ranking functions include:

 RANK(): Assigns ranks to rows, skipping ranks for duplicates.

 DENSE_RANK(): Assigns ranks to rows without skipping rank numbers


for duplicates.

 ROW_NUMBER(): Assigns a unique number to each row in the result


set.

 PERCENT_RANK(): Shows the relative rank of a row as a percentage


between 0 and 1.

2.1 RANK Function


It assigns ranks to rows within a partition, with the same rank given to rows
with identical values. If two rows share the same rank, the next rank is
skipped.

Example: Using RANK() to Rank Employees by Salary

SELECT Name, Department, Salary,


RANK() OVER(PARTITION BY Department ORDER BY Salary DESC) AS
emp_rank
FROM employee;

Output

Departm Salar emp_ra


Name ent y nk

Rames 50,00
Finance 1
h 0

50,00
Suresh Finance 1
0

20,00
Ram Finance 3
0

30,00
Deep Sales 1
0

Pradee 20,00
Sales 2
p 0

Explanation:

 RANK() function assigns a ranking within each department based on


salary (highest salary = rank 1).

 In Finance: Ramesh and Suresh both earn 50,000, so they share rank 1
and next salary (20,000) is assigned rank 3, skipping rank 2.
 In Sales: Deep earns the highest (30,000) -> rank 1 and Pradeep earns
less (20,000) -> rank 2.

2.2 DENSE RANK Function

When ranking rows in SQL, ties can sometimes create gaps in the ranking
sequence. DENSE_RANK() function is used to avoid this it assigns the same
rank to rows with equal values but continues ranking with the next
consecutive number, without skipping.

Example: Using DENSE_RANK() to Rank Employees by Salary

SELECT Name, Department, Salary,


DENSE_RANK() OVER(PARTITION BY Department ORDER BY Salary DESC)
AS emp_dense_rank
FROM employee;

Output

Departm Salar emp_dense_r


Name ent y ank

Rames 50,00
Finance 1
h 0

50,00
Suresh Finance 1
0

20,00
Ram Finance 2
0

30,00
Deep Sales 1
0

Pradee 20,00
Sales 2
p 0

Explanation:
 DENSE_RANK() works like RANK(), but it ensures the ranking sequence
has no gaps.

 In Finance: Ramesh and Suresh both earn 50,000, so they share rank 1
and next salary (20,000) is assigned rank 2 (not rank 3 as in RANK()).

 In Sales: Deep earns the highest (30,000) -> rank 1 and Pradeep earns
less (20,000) -> rank 2.

2.3 ROW NUMBER Function

ROW_NUMBER() gives each row a unique number. It numbers rows from one
to the total rows. The rows are put into groups based on their values. Each
group is called a partition. In each partition, rows get numbers one after
another. No two rows have the same number in a partition.

Example: Using ROW_NUMBER() for Unique Row Numbers

SELECT Name, Department, Salary,


ROW_NUMBER() OVER(PARTITION BY Department ORDER BY Salary
DESC) AS emp_row_no
FROM employee;

Output

Departm Salar emp_row_


Name ent y no

Rames 50,00
Finance 1
h 0

50,00
Suresh Finance 2
0

20,00
Ram Finance 3
0

30,00
Deep Sales 1
0
Departm Salar emp_row_
Name ent y no

Pradee 20,00
Sales 2
p 0

Explanation:

 In Finance, Ramesh is row 1, Suresh is row 2, Ram is row 3.

 In Sales, Deep is row 1, Pradeep is row 2.

2.4 PERCENT RANK Function

PERCENT_RANK() shows the relative position of a row compared to others in


the same partition. The formula is:

PERCENT_RANK=RANK−1Total Rows in Partition−1PERCENT_RANK=Total Ro


ws in Partition−1RANK−1

Example: Using PERCENT_RANK() to Find Relative Salary Position

SELECT Name, Department, Salary,


PERCENT_RANK() OVER(PARTITION BY Department ORDER BY Salary
DESC) AS emp_percent_rank
FROM employee;

Output

Departm Salar emp_percent_r


Name ent y ank

Rames 50,00
Finance 0.00
h 0

50,00
Suresh Finance 0.00
0

Ram Finance 20,00 1.00


Departm Salar emp_percent_r
Name ent y ank

30,00
Deep Sales 0.00
0

Pradee 20,00
Sales 1.00
p 0

Explanation:

 In Finance: Ramesh & Suresh are tied for highest -> 0.00, Ram (lowest)
-> 1.00.

 In Sales: Deep (highest) -> 0.00, Pradeep (lowest) -> 1.00.

 PERCENT_RANK helps understand relative standing as a percentage


within a department.

Troubleshooting Common Issues with Window Functions

While SQL window functions are incredibly powerful, there are some common
pitfalls and challenges that users may encounter:

 Partitioning Error: Ensure that the PARTITION BY clause is used


correctly. If no partition is defined, the entire result set is treated as a
single window.

 ORDER BY Within the Window: The ORDER BY clause within the


window function determines the order of calculations. Always verify
that it aligns with the logic of your calculation.

 Performance Considerations: Window functions can be


computationally expensive, especially on large datasets. Always ensure
that your window functions are optimized and, if necessary, combined
with appropriate indexes.

What is Cursor in SQL


A cursor in SQL is a database object used to process data one row at a time,
useful when row-by-row handling is needed instead of bulk processing. It
temporarily stores data for operations like SELECT, UPDATE, or DELETE.

 Useful for applying custom logic, conditional operations, or step-by-


step updates.

 Common in PL/SQL or T-SQL for tasks like loops, conditional logic, or


complex procedures.

Why Use a Cursor?

Cursors should be used carefully as they are helpful in scenarios like:

 Performing conditional logic row-by-row.

 Looping through data to calculate or transform fields

 Iterating over result sets for conditional updates or transformations.

 Handling hierarchical or recursive data structures.

 Performing clean-up tasks that can not be done with a single SQL
Query.

Types of Cursors in SQL

SQL offers two main types of cursors, each suited for different scenarios
and depending on how much control we want:

1. Implicit Cursors

In PL/SQL, when we perform INSERT, UPDATE or DELETE operations, an


implicit cursor is automatically created. This cursor holds the data to be
inserted or identifies the rows to be updated or deleted. We can refer to this
cursor as the SQL cursor in our code.

Usage: Managed entirely by the SQL engine without explicit declaration.

Useful Attributes:

 %FOUND: True if the SQL operation affects at least one row.

 %NOTFOUND: True if no rows are affected.

 %ROWCOUNT: Returns the number of rows affected.

 %ISOPEN: Checks if the cursor is open.

Example: Using Implicit Cursor for Bulk Updates


This program updates a table by increasing the salary of each employee by
1500. After the update, the SQL%ROWCOUNT attribute is used to find out
how many rows were affected by the operation.

Query:

DECLARE
total_rows number;
BEGIN
UPDATE Emp
SET Salary = Salary + 1500;

total_rows := SQL%ROWCOUNT;

dbms_output.put_line(total_rows || ' rows updated.');


END;

Output

5 Emp selected
PL/SQL procedure successfully completed.

Explanation:

In addition to these attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS


are specific to the FORALL statement, which is used to perform multiple DML
operations at once. %BULK_ROWCOUNT returns the number of rows affected
by each DML operation, while %BULK_EXCEPTION returns any exception that
occurred during the operations.

2. Explicit Cursors

These are user-defined cursors created explicitly by users for custom


operations. They provide complete control over every part of their lifecycle:
declaration, opening, fetching, closing, and deallocating.

Usage: Used for fetching data row-by-row with complete control over the
cursor lifecycle.

Explicit cursors are useful when:

 We need to loop through results manually

 Each row needs to be handled with custom logic

 We need access to row attributes during processing


Example: Using an Explicit Cursor

Here is a complete example of declaring, opening, fetching, closing, and


deallocating a cursor. This workflow demonstrates how to use explicit cursors
for row-by-row operations, including resource management and result
retrieval.

Query:

DECLARE emp_cursor CURSOR FOR SELECT Name, Salary FROM Employees;

BEGIN
-- Open the cursor
OPEN emp_cursor;

-- Fetch rows from the cursor


FETCH NEXT FROM emp_cursor INTO @Name, @Salary;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Name: ' + @Name + ', Salary: ' + CAST(@Salary AS VARCHAR);
FETCH NEXT FROM emp_cursor INTO @Name, @Salary;
END;

-- Close the cursor


CLOSE emp_cursor;

-- Deallocate the cursor


DEALLOCATE emp_cursor;
END;

Output
Output

Cursor Syntax Breakdown in SQL

SQL Cursors allow you to process query results one row at a time. Below is a
step-by-step explanation of how to create and use explicit cursors with
simplified explanations and examples.

1. Declare a Cursor

The first step in creating an explicit cursor is to declare it. This defines the
cursor and associates it with a SQL query that determines the result set.

Syntax:

DECLARE cursor_name CURSOR FOR SELECT * FROM table_name

Example:

DECLARE s1 CURSOR FOR SELECT * FROM studDetails

Explanation:

The DECLARE statement creates a cursor named s1, which is linked to the
query SELECT * FROM studDetails. This cursor will allow row-by-row
processing of the studDetails table.

2. Open Cursor Connection

After declaring the cursor, it needs to be opened. The OPEN statement


executes the query associated with the cursor and prepares it for fetching
rows. The OPEN s1 command initializes the cursor s1 and establishes a
connection to its result set.

Syntax:

OPEN cursor_connection
Example:

OPEN s1

Explanation: The cursor executes the associated query and makes the
result set available for row-by-row processing.

3. Fetch Data from the Cursor

To retrieve data from the cursor, use the FETCH statement. SQL provides six
methods to access data:

Mode Description

Fetches the first row in the result


FIRST
set

LAST Fetches the last row

Fetches the next row (default


NEXT
behavior)

PRIOR Fetches the previous row

ABSOLUTE
Fetches the nth row
n

RELATIVE Fetches a row relative to current


n position

Syntax:

FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n FROM cursor_name

Example:

FETCH FIRST FROM s1


FETCH LAST FROM s1
FETCH NEXT FROM s1
FETCH PRIOR FROM s1
FETCH ABSOLUTE 7 FROM s1
FETCH RELATIVE -2 FROM s1

4. Close Cursor Connection

After completing the required operations, the cursor should be closed to


release the lock on the result set and free up resources.

Syntax:

CLOSE cursor_name

Example:

CLOSE s1

Explanation:

The CLOSE statement closes the cursor s1, terminating its connection to
the result set. This ensures that the cursor is no longer available for fetching
data.

5. Deallocate Cursor Memory

The final step is to deallocate the cursor to free up server memory.


The DEALLOCATE statement removes the cursor definition and its
associated resources from the memory. The DEALLOCATE statement
completely removes the cursor s1 from memory, ensuring efficient resource
usage.

Syntax:

DEALLOCATE cursor_name

Example:

DEALLOCATE s1

Explanation: This permanently removes the cursor definition from memory,


keeping your server efficient.

How To Create an Implicit Cursor?

An implicit cursor is automatically created by SQL when we execute a SQL


statement. These cursors are managed behind the scenes by the SQL engine
and do not require explicit declaration or management. To create an implicit
cursor in PL/SQL, we simply need to execute a SQL statement.
Query:

BEGIN
FOR emp_rec IN SELECT * FROM emp LOOP
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.ename);
END LOOP;
END;

Explanation: This loop implicitly creates a cursor to iterate through each


row in the emp table and prints out employee names.

SQL Cursor Exceptions

When using SQL cursors, there is always a possibility of encountering


unexpected errors during execution. These errors can occur due to improper
usage or conflicting operations. Below are some common exceptions you
might face while working with cursors:

1. Duplicate Value Error

 This error occurs when the cursor attempts to insert a record or row
that already exists in the database, causing a conflict due to duplicate
values.

 Solution: Use proper error handling mechanisms such as TRY-


CATCH blocks or check for existing records before inserting data.

2. Invalid Cursor State

 This error is triggered when the cursor is in an invalid state, such as


attempting to fetch data from a cursor that is not open or already
closed.

 Solution: Ensure the cursor is properly opened before fetching data


and closed only after completing all operations.

3. Lock Timeout

 This happens when the cursor tries to obtain a lock on a row or table,
but the lock is already held by another transaction for an extended
time.

 Solution: Use appropriate isolation levels, manage transactions


efficiently, and minimize locking duration to prevent timeouts.

Comparison of Implicit and Explicit Cursors


Feature Implicit Cursors Explicit Cursors

Manual (requires
Creation Automatic
declaration)

Managem User-managed (open,


Fully managed by SQL engine
ent fetch, close)

%FOUND, %NOTFOUND, Same as implicit


Attributes
%ROWCOUNT, %ISOPEN cursors

Complex, row-by-row
Use Case Simple DML operations
operations

Advantages of Using Cursors

Despite their limitations, SQL cursors provide several benefits in specific use
cases:

 Row-by-Row Processing: Cursors allow data to be processed row-by-


row, which is particularly useful for tasks requiring detailed and
individualized operations, such as complex calculations or
transformations.

 Iterative Data Handling: With cursors, we can iterate over a result


set multiple times, making it ideal for scenarios where repeated
operations are necessary on the same data.

 Working with Complex Relationships: Cursors make it easier to


handle multiple tables with complex relationships, such as hierarchical
data structures or recursive queries.

 Conditional Operations: Cursors are effective for performing


operations like updates, deletions, or inserts based on specific
conditions.

 Processing Non-Straightforward Relationships: When the


relationships between tables are not straightforward or set-based
operations are impractical, cursors provide a flexible alternative.
Limitations of Cursors

While cursors are helpful in certain scenarios, they come with notable
limitations, and alternatives should be explored whenever possible:

 Performance Overhead: Cursors process one row at a time, which


can be significantly slower compared to set-based operations that
handle all rows at once.

 Resource Consumption: Cursors impose locks on tables or subsets of


data, consuming server memory and increasing the risk of resource
contention.

 Increased Complexity: Managing cursors requires explicit


declarations, opening, fetching, closing, and deallocating, which adds
to the complexity of the SQL code.

 Impact of Large Datasets: The performance of cursors decreases


with the size of the dataset, as larger rows and columns require more
resources and time to process.

CTE in SQL

Last Updated : 01 Sep, 2025

In SQL, a Common Table Expression (CTE) is an essential tool for simplifying


complex queries and making them more readable. By defining temporary
result sets that can be referenced multiple times, a CTE in SQL allows
developers to break down complicated logic into manageable parts.

Uses of CTEs

 Breaking down complex queries into smaller, reusable components.

 Improving readability and modularity by separating the logic.


 Enabling recursive operations for hierarchical data.

Syntax

WITH cte_name AS (
SELECT query
)
SELECT *
FROM cte_name;

In the above syntax:

 cte_name: A unique name for the CTE expression.

 query: A valid SQL query that returns a result set, which will be
treated as a virtual table within the main query.

 SELECT: The main query that can reference the CTE by its name.

Creating a Simple CTE in SQL

Let’s consider an Employees table that contains employee details such as


EmployeeID, Name, Department, Salary and ManagerID. This table is used to
demonstrate how to use a Common Table Expression (CTE) to
simplify SQL queries, particularly when aggregating or filtering data.

Employees Table
This table represents the hierarchical structure of employees within an
organization, based on a recursive Common Table Expression (CTE) query.
The table displays employees, their respective levels in the hierarchy, and
the managers who supervise them.

EmpLev Manage
FullName el r

John
1 NULL
Smith

John
Jane Doe 2
Smith

Alice John
2
Brown Smith

Bob
3 Jane Doe
Green

Charlie
3 Jane Doe
Ray

Example: Calculate Average Salary by Department

In this example, we will use a Common Table Expression (CTE) to calculate


the average salary for each department in the Employees table. The CTE
simplifies the query by breaking it into a manageable part that can be
referenced in the main query.

Query:

WITH AvgSalaryByDept AS (
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
)
SELECT *
FROM AvgSalaryByDept;

Output:

Departm AvgSal
ent ary

IT 75000

HR 60000

Finance 52500

Explanation:

 The WITH clause defines a CTE named AvgSalaryByDept.

 The main query references this CTE to retrieve the average salary for
each department.

Recursive Common Table Expression

A recursive CTE references itself and is useful for querying hierarchical data,
such as employees and their managers stored in the same table. It
repeatedly executes until the full hierarchy is returned. To avoid infinite loops
from incorrect definitions, use the MAXRECURSION hint in the
query’s OPTION clause.

Recursive CTEs consist of two parts:

1. Anchor member: The initial query that selects the base case (e.g.,
top-level managers).

2. Recursive member: The query that references the CTE itself, pulling
the next level of data.

Example: Hierarchical Employee Data

WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
)

SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

Output:

EmpLev Manage
FullName el r

John
1 NULL
Smith

John
Jane Doe 2
Smith

Alice John
2
Brown Smith

Bob
3 Jane Doe
Green
EmpLev Manage
FullName el r

Charlie
3 Jane Doe
Ray

Explanation:

 John Smith is at level 1 and has no manager (Top-level employee).

 Jane Doe and Alice Brown are at level 2, reporting to John Smith.

 Bob Green and Charlie Ray are at level 3, reporting to Jane Doe.

Managing Recursion with MAXRECURSION

To avoid infinite recursion, SQL Server imposes a recursion limit. By default,


the recursion depth is set to 100, but you can customize this using
the MAXRECURSION hint:

OPTION(MAXRECURSION 50);

This limits the recursion to 50 levels. If the recursion exceeds this limit, SQL
Server will stop and return an error.

Limitations of CTEs in SQL

 Temporary Scope: A CTE exists only during the execution of the


query. Once the query completes, the CTE is discarded.

 Performance Issues: For very large datasets, CTEs can sometimes


lead to performance degradation due to multiple references to the
same CTE.

 Not Allowed in All Database Operations: Some operations, such as


INSERT and UPDATE, may have restrictions when using CTEs in certain
databases.

CTE Vs Subqueries

CTE Subquery

Can be referenced multiple times. Typically used once.


CTE Subquery

Improves readability for complex Can become difficult to read when


queries. nested.

May be less efficient for repeated


Optimized for multiple references.
operations.

Regular Expressions in SQL

Last Updated : 23 Jul, 2025

Regular expressions (regex) are incredibly powerful tools that simplify


complex data processing tasks. They enable users to identify, replace,
or extract data based on specific patterns. Regular expressions, though
originating from computer science, are widely used in SQL
to manage and manipulate data effectively.

In this comprehensive guide, we will introduce you to regular expressions in


SQL, covering everything from basic concepts to advanced applications,
ensuring it becomes a valuable addition to our SQL toolkit.
What are Regular Expressions?

Regular expressions, often abbreviated as regex or regexp, are sequences


of characters that define a specific search pattern. They are widely used
in programming and data processing to perform sophisticated string
matching and manipulation tasks. By using these patterns, users can
efficiently search, validate, or extract specific data from large text
datasets.

Regex patterns consist of a combination of literal characters and special


symbols that dictate matching rules. Regular expressions can be used with
functions like REGEXP_LIKE, REGEXP_REPLACE, and REGEXP_SUBSTR to
process and analyze textual data stored in databases. They provide a more
flexible and powerful alternative to basic SQL string operations, enabling
developers to handle complex text-related requirements with ease.

Example:

SELECT email
FROM users
WHERE REGEXP_LIKE(email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]
{2,}$');

This query retrieves all emails from the users table that match the regex
pattern for valid email addresses.

Types of Regular Expressions in SQL

In SQL, there are three primary functions for working with regular
expressions:

1. REGEXP_LIKE

The REGEXP_LIKE function in SQL is used to determine whether a given


string matches a specific regular expression pattern. It evaluates the
string against the regex and returns TRUE if the string matches the pattern
and FALSE otherwise. This function is particularly useful for filtering data
based on complex string patterns.

Syntax

REGEXP_LIKE(column_name, 'pattern')

Example:
The following query selects all product names from the products table where
the names start with the letter 'A':

SELECT product_name
FROM products
WHERE REGEXP_LIKE(product_name, '^A');

Output

product_na
me

Apple

Apricot

Avocado

2. REGEXP_REPLACE

The REGEXP_REPLACE function in SQL is used to search for a pattern within


a string and replace all occurrences of that pattern with a specified
replacement string. This function is particularly useful
for cleaning and transforming data by removing unwanted characters or
formatting strings.

Syntax

REGEXP_REPLACE(string, 'pattern', 'replacement')

Example:

The following query removes all non-numeric characters from


the phone_number column in the contacts table:

SELECT REGEXP_REPLACE(phone_number, '[^0-9]', '') AS cleaned_number


FROM contacts;

Output
cleaned_num
ber

1234567890

1800555019
9

1234567890
123

9876543210

5551234567
8

Explanation:

 [^0-9]: Matches any character that is not a digit (0–9). The ^ inside
square brackets negates the range.

 ' ': The replacement string is an empty string, effectively removing all
non-numeric characters.

3. REGEXP_SUBSTR

The REGEXP_SUBSTR function in SQL is used to extract a substring from a


string that matches a specified regular expression pattern. It is particularly
useful for isolating portions of text within a larger string, such as extracting
domain names from email addresses or pulling specific elements from
formatted data.

Syntax

REGEXP_SUBSTR(string, 'pattern', start_position, occurrence,


match_parameter)

Example:
To extract the domain name from the email field in the users table:

SELECT REGEXP_SUBSTR(email, '@[^.]+') AS domain


FROM users;

Output

domain

@gmail

@outlook

@compa
ny

@yahoo

@exampl
e

Explanation:

This pattern extracts the part of the email immediately following


the @ symbol up to (but not including) the next period.
The REGEXP_SUBSTR function is a versatile tool for extracting meaningful
data from complex text fields, enabling targeted data analysis and
processing.

Basic Regular Expression Syntax Table

Regular expressions (regex) are constructed using a combination of


characters and special symbols, each with specific meanings. This table
format organizes regex elements and examples for quick reference, making
it easy to understand and apply them in practical scenarios.
Patter
n Description Example Matches

Matches any single character


. h.t hat, hit, hot
(except newline).

^ Matches the start of a string. ^A Apple, Apricot

$ Matches the end of a string. ing$ sing, bring

Acts as a
logical OR
` ` `cat
between
patterns.

Matches zero or more of the


* ab* a, ab, abb, abbb
preceding character.

Matches one or more of the


+ ab+ ab, abb, abbb
preceding character.

Matches zero or one of the


? colou?r color, colour
preceding character.

Matches exactly n occurrences


{n} a{3} aaa
of the preceding character.

Matches n or more occurrences


{n,} a{2,} aa, aaa, aaaa
of the preceding character.

{n,m Matches a{2,4} aa, aaa, aaaa


Patter
n Description Example Matches

between n and m occurrences


}
of the preceding character.

Matches any of the enclosed


[abc] [aeiou] a, e, i, o, u
characters.

[^ab Matches any character not Any non-vowel


[^aeiou]
c] enclosed. character

Matches any character in the


[a-z] [0-9] 0, 1, 2, ..., 9
specified range.

Escapes a special character to


\ \. Matches a literal .
treat it as a literal.

Matches a word boundary Matches cat but


\b \bcat\b
(space, punctuation). not scatter

Matches scatter b
\B Matches a non-word boundary. \Bcat
ut not cat

Groups characters together


(abc) (ha)+ ha, haha, hahaha
and remembers the match.

\1, \ Matches the content of a


(ab)\1 abab
2, ... captured group.

Common Regex Patterns


Pattern Description Example Matches

^[A-Za-z0-9._%
+-]+@[A-Za- Validates an email [email protected] Valid email
z0-9.-]+\\.[A- address. om addresses
Za-z]{2,}$

Matches a numeric 123, 456, 789


^[0-9]+$ 123456
string only. 0

Matches a URL
https://
https?://[^ ]+ starting URLs
example.com/
with http or https.

Matches
^[A-Za-z0-9]+ abc123, xyz7
alphanumeric User123
$ 89
strings.

Real-World Examples of Regular Expressions in SQL

Here’s how regular expressions can solve common data processing tasks in
SQL:

Example 1: Extracting URLs from Text

If we have a messages table containing text with embedded URLs, we can


extract the URLs as follows. This regex matches URLs starting
with http:// or https:// and extracts them.

Query:

SELECT REGEXP_SUBSTR(message, 'https?://[^ ]+') AS url


FROM messages;

Explanation:

 https?://: Matches http:// or https://.

 [^ ]+: Matches all characters up to the next space.

Example 2: Validating Email Addresses


To validate email addresses in the users table. This pattern ensures that the
email follows the standard format.

SELECT email
FROM users
WHERE REGEXP_LIKE(email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]
{2,}$');

Explanation:

Ensures the email address starts with alphanumeric characters, includes


an @ symbol, followed by a domain, and ends with a valid TLD (top-level
domain).

Example 3: Cleaning Up Phone Numbers

To remove non-numeric characters from phone numbers in


the contacts table. This query leaves only numeric characters in
the phone_number field.

SELECT REGEXP_REPLACE(phone_number, '[^0-9]', '') AS cleaned_number


FROM contacts;

Explanation:

 [^0-9]: Matches any character that is not a digit.

 ' ': Replaces non-numeric characters with an empty string.

Example 4: Finding Specific Patterns

Find all product names in the products table that contain digits:

SELECT product_name
FROM products
WHERE REGEXP_LIKE(product_name, '\d');

Explanation:

\\d: Matches any numeric digit (0–9).

Example 5: Extracting Subdomains

Extract the subdomain from URLs in the web_logs table:

SELECT REGEXP_SUBSTR(url, '^[^.]+') AS subdomain


FROM web_logs;

Explanation:
^[^.]+: Matches all characters from the start of the string up to the
first . (dot).

Example 6: Validating Numeric Strings

Find records where a field contains only numbers in the data_table:

SELECT record_id
FROM data_table
WHERE REGEXP_LIKE(field_name, '^[0-9]+$');

Explanation:

 ^[0-9]+$: Matches strings that consist entirely of digits.

Common Regular Expression Use Cases in SQL

1. Data Validation: Regular expressions can be used to ensure that data


fields adhere to specific formats, such as validating emails, phone
numbers, or numeric strings.

2. Data Cleaning: Regex can help remove unwanted characters,


whitespace, or other non-standard elements from strings to clean up
datasets.

3. Data Extraction: Extract meaningful substrings from larger text


fields, such as domain names from emails or URLs from text.

Conclusion

Regular expressions in SQL offer a powerful way


to manage and manipulate textual data. Whether we're validating
inputs, cleaning datasets, or extracting specific patterns, mastering regex
functions can significantly enhance our SQL capabilities. Start with
the basics and gradually explore advanced patterns to unlock the full
potential of this tool. By integrating regular expressions into our SQL
workflows, we can simplify complex data operations and improve overall
efficiency.

You might also like