SQL Tutorial
SQL Tutorial
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:
After your MySQL environment is set up, you can write your SQL program.
Below is the example to display " Hello World" using SQL.
USE test_db;
3. Create a table named 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!
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.
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
UPDATE Statement
DELETE Statement
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
IS NULL Operator
UNION Operator
EXCEPT Operator
BETWEEN Operator
INTERSECT Operator
EXISTS Operator
CASE Operator
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
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
DELETE JOIN
Recursive Join
SQL Functions
String Functions
Numeric Functions
Statistical Functions
JSON Functions
Conversion Functions
Datatype Functions
LTRIM Function
UPPER Function
RTRIM Function
SQL Views
CREATE VIEW
UPDATE VIEW
RENAME VIEW
DROP VIEW
SQL Indexes
Indexes
Create Index
Drop Index
Show Indexes
Unique 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
Wildcards Operators
Comments
Trigger
Hosting
Performance Tuning
Stored Procedures
Transactions
Sub Queries
Using Sequences
Auto Increment
Window functions
Cursors
Database Tuning
Dynamic
Regular Expressions
Exercises
Quiz
Interview Questions
Cheat Sheet
Introduction of ER Model
Rules of Inference
Denormalization in Databases
Database Design
Database Security
Injection
Data Encryption
Backup
Database Connectivity
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.
₹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
₹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
Applications of SQL
Quick Links:
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.
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).
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.
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.
Whitespace Allowed: Queries can span multiple lines, but use spaces
between keywords and names.
Comments
Single-line: -- comment
Multi-line: /* comment */
Data Constraints: Use NOT NULL, UNIQUE, PRIMARY KEY, etc., to ensure
data accuracy.
Naming Rules:
Comman
d Description
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.
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.
Comma
nd Description
Command Description
Benefits of SQL
Limitations of SQL
Complexity in Advanced Operations: Advanced functionalities such
as indexing, query optimization and performance tuning require in-
depth technical knowledge.
Memory-efficient storage
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 types are used when precise numeric values are needed, such
as for financial data, quantities, and counts. Some common exact numeric
types include:
-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
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
Data
Type Description Range
-1.79E+308 to
FLOAT Approximate numeric values
1.79E+308
Unicode data types are used to store characters from any language,
supporting a wider variety of characters. These are given in below table.
Data Storage
Type Description Size
DATETI store both the data and time (year, month, day,
8 Bytes
ME hour, minute, second)
Binary data types are used to store binary data such as images, videos or
other file types. These include:
Data
Type Description Max Length
The BOOLEAN data types are used to store logical values, typically TRUE or
FALSE. It is commonly used for flag fields or binary conditions.
XML Data Type: Used to store XML data and manipulate XML
structures in the database
SQL Operators
SQL operators are symbols or keywords used to perform operations on data
in SQL queries.
Arithmetic Operator
Comparison Operator
Logical Operator
Bitwise Operators
Compound Operators
Special Operators
Query:
Output:
Operat
or Description
= Equal to.
Greater than
>=
equal to.
In this example, we will retrieve all records from the "MATHS" table where the
value in the "MARKS" column is equal to 50.
Query:
Output:
Comparison Operation
Operat
or Description
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
Operat
or Description
| Bitwise OR operator
Operat
or Description
Bitwise OR and
|=
assign
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
Query:
Output:
Special Operator
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.
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:
Here,
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:
If suppose we want to fetch all the records from the Student table where Age
is 18 and ADDRESS is Delhi.
Query:
Output:
ROLL_N ADDRE Ag
O NAME SS PHONE e
XXXXXXXX
1 Ram Delhi 18
XX
SURES XXXXXXXX
4 Delhi 18
H XX
To fetch all the records from the Student table where NAME is Ram or NAME
is SUJIT.
Query:
Output:
XXXXXXXX
1 Ram Delhi 18
XX
XXXXXXXX
3 SUJIT ROHTAK 20
XX
XXXXXXXX
3 SUJIT ROHTAK 20
XX
Syntax:
Example
Query:
Output:
ROLL_N ADDRES Ag
O NAME S PHONE e
XXXXXXXX
1 Ram Delhi 18
XX
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.
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.
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:
CustomerName VARCHAR(50),
City VARCHAR(50),
PostalCode VARCHAR(10),
Country VARCHAR(50)
);
VALUES
(1, 'John Wick', 'New York', '1248', 'USA'),
New
1 John Wick 1248 USA
York
Around the
2 London WA1 1DP UK
Horn
New
3 Rohan 100084 India
Delhi
The following SQL statement selects all fields from Customers table where
the country is not UK.
Query:
SELECT *
FROM Customers
Output:
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.
The NOT operator can also be used with the IN condition to exclude multiple
values from the result set.
Query:
SELECT *
FROM Customers
Output:
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.
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:
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.
To exclude records where a column has a NULL value, combine NOT with the
IS NULL condition.
Query:
SELECT *
FROM Customers
Output:
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.
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
Output:
New
3 Rohan 100084 India
Delhi
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.
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
lets Consider the following Products Table and OrderDetails Table for
explaining the examples.
Products Table
OrderDetails Table
Queries
Query:
FROM Products
WHERE TRUE;
Output:
This query retrieves all product names from the Products table because TRUE
always evaluates as true for every row.
SELECT ProductName
FROM Products
FROM OrderDetails
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
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
Query:
FROM Products
FROM OrderDetails);
Output:
This query finds the distinct CategoryIDs of products that exist in the
OrderDetails table.
Query:
SELECT ProductName
FROM Products
FROM OrderDetails
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.
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.
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:
Query:
Output
Emp Table
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
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
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
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:
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
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
Feature BETWEEN IN
AND value2
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
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".
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
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS (
SELECT column_name(s)
FROM subquery_table
WHERE condition
);
Customers Table
Orders Table:
To fetch the first and last name of the customers who placed atleast one
order.
Query:
FROM Customers
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:
Fetch last and first name of the customers who has not placed any order.
FROM Customers
FROM Orders
Output:
Delete the record of all the customer from Order Table whose last name is
'Mehra'.
DELETE
FROM Orders
FROM customers
Output:
UPDATE Customers
FROM Customers
Output:
Conclusion
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
Instructor Table:
select name
from instructor
from instructor
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
lets Consider the following Products Table and OrderDetails Table for
explaining the examples.
Products Table
OrderDetails Table
Queries
Query:
FROM Products
WHERE TRUE;
Output:
This query retrieves all product names from the Products table because TRUE
always evaluates as true for every row.
SELECT ProductName
FROM Products
FROM OrderDetails
This query ensures that the product names returned have ALL quantities of 6
or 2 in the OrderDetails table.
SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
Query:
FROM Products
FROM OrderDetails);
Output:
This query finds the distinct CategoryIDs of products that exist in the
OrderDetails table.
SELECT ProductName
FROM Products
FROM OrderDetails
Output:
product names
This query retrieves product names where at least one record in the
OrderDetails table has a quantity of 9.
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
Syntax:
column2 datatype,
...
);
Let's create a Customers table where the Email column must be unique.
Name VARCHAR(100),
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.
The third insert will fail because the Email [email protected] already
exists in the Customers table.
CustomerID INT,
ProductID INT,
OrderDate DATE,
);
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
);
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
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
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
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.
Syntax:
columnN datatype(size)
);
Key Terms
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Phone int(10)
);
Output:
Explanation:
Age has a CHECK constraint, ensuring it’s within the range of 0 to 99.
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:
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.
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:
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
FROM customer;
Output:
Note: We can use * instead of column name to copy whole table to another
table.
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.
4. After creating a table, use the following command to view the structure of
your table:
DESC table_name;
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;
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 condition;
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:
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.
Syntax
Parameters:
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.
Output
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
Output
CustomerNa LastNa
me me
Liam Smith
Sophia Miller
Akira Tanaka
Hernand
Carlos
ez
Isabella Rossi
In this example, we will fetch all the fields from table Customer:
Query:
Output
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
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
Query:
Output
Count customer_co
ry unt
USA 3
Japan 1
Italy 1
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:
Output
Count
ry
USA
Japan
Italy
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:
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:
Output
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
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:
Syntax:
Parameters:
We will create a basic employee table structure in SQL for performing all the
where clause operation.
Query:
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
Query:
EmpI Countr Ag
D Name y e Mob
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
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:
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
Query:
Output:
EmpI Count Ag
D Name ry e Mob
Shubha 7384797
1 India 23
m 34
Query:
EmpI Count Ag
D Name ry e Mob
Shubha 7384797
1 India 23
m 34
Australi 4367895
2 Aman 21
a 55
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:
Output:
Name
Aman
Aditya
Shubha
m
= Equal to
BETWEE
In an inclusive Range
N
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.
Query execution order: FROM -> WHERE -> GROUP BY -> HAVING ->
SELECT -> ORDER BY.
Syntax:
Parameters:
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.
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
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:
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.
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:
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.
In this section, we will use Employee table(emp) first insert some sample
data, then perform GROUP BY queries combined with HAVING.
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.
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.
In this query, we group employees by age and display only those age groups
where average salary is above 60,000.
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
Syntax:
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
HAVING condition;
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 );
Output
Michael 6500
2 Male Sales 5
Smith 0
7500
4 James Davis Male Finance 7
0
Wilson e 0
In this Example we calculate the total salary of all employees and display it
only if it meets the specified condition.
Query:
Output
Total_Sal
ary
290000
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
In this example, we find the highest salary among employees and display it
only if it exceeds 70,000.
Query:
Output
Max_Sal
ary
75000
In this example, we find the least experienced employee and display it only if
their experience is less than 3 years.
Query:
Output
Min_Experie
nce
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:
Output
Total_Sal Average_Sal
ary ary
290000 58000
SQL Distinct Clause
Syntax:
Parameters:
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:
ROLL_NO INT,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(20),
AGE INT
);
VALUES
Output:
ROLL_N AG
O NAME ADDRESS PHONE E
98765432
3 Naveen Singh 789 Market Lane, Delhi 26
12
98765432
9 Naveen Singh 789 Market Lane, Delhi 26
12
Chennai 14
The query returns only unique names, eliminating the duplicate entries from
the table.
Query:
Output:
output
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
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:
Output:
AG
E
2
AG
E
2
3
2
4
2
6
2
7
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:
Output:
COUNT(DISTINCT
AGE)
Query:
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).
Syntax:
Key Terms:
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
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.
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:
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
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 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.
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
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
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.
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.
Syntax:
Query:
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
Comma
nd Description Syntax
Example:
This query inserts a new record into employees table with first name 'Jane',
last name 'Smith' and department 'HR'.
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.
Syntax:
Parameters:
Example: Let’s see how the INSERT INTO statement works with practical
examples.
Output
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:
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
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
Parameters:
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).
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).
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
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
Garcia xxx
Hana xxxxxxx
8 Osaka 18
Suzuki xxx
Amelia xxxxxxx
10 London 17
Brown xxx
Explanation:
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
Example: If you want to copy all data from the OldStudent table into the
Student table, use this query:
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
5 Isabella Rome 19
x
Mateo xxxxxxxxx
7 Madrid 15
Garcia x
Hana xxxxxxxxx
8 Osaka 18
Suzuki 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
Example: Let’s say we want to copy only the Name and Age columns from
OldStudent into Student:
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
Mateo xxxxxxx
Madrid 15
7 Garcia xxx
Hana xxxxxxx
Osaka 18
8 Suzuki xxx
Amelia xxxxxxx
London 17
10 Brown xxx
Arjun
NULL NULL 21
NULL Mehta
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
Mateo xxxxxxxxx
7 Madrid 15
Garcia x
Hana xxxxxxxxx
8 Osaka 18
Suzuki x
Amelia xxxxxxxxx
10 London 17
Brown x
Arjun 99999999
101 Mumbai 21
Mehta 99
88888888
102 Emily Clark Sydney 22
88
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;
Parameters
SET: The column(s) you want to update and their new values.
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.
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:
Output
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
78
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'.
Query:
UPDATE Customer
SET CustomerName = 'Satyam',
Country = 'USA'
WHERE CustomerID = 1;
Output:
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
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
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.
Syntax:
Parameter Explanation
table_name: The name of the table from which you want to delete the
rows
Output
Pravee praveen_dagger@yahoo
2 HR
n .com
4 Rithvik [email protected] IT
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
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:
Output:
Pravee praveen_dagger@yahoo
2 HR
n .com
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
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:
Output
id name email department
Pravee praveen_dagger@yahoo
2 HR
n .com
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
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:
Output:
All of the records in the table will be deleted, there are no records left to
display. The table GFG_Employees will become empty.
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:
Explanation: The ROLLBACK command will undo the changes made by the
DELETE statement, effectively restoring the records that were deleted during
the transaction.
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:
This command grants the user user_name the permissions to select and
update records in the employees table.
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;
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
Creating Database
Syntax:
Query:
Output
Creating a new database
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:
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.
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:
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
Syntax:
Here, we are creating a table named Student to store student details like ID,
name, subject, year and marks.
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
Syntax
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.
Query:
SHOW DATABASES;
Output
List of Databases
Now that the database is confirmed to exist, let’s use the DROP
DATABASE command, to delete the database 'GeeksforGeeks'.
Query:
Output
DROP DATABASE
Query
SHOW DATABASES;
Output
Deleted Data
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
Example:
This command will check if the database exists before attempting to drop it,
making it safer to run in scripts or on production systems.
Privileges: Make sure you have the necessary privilege to delete the
database. Usually an admin can delete the database.
Conclusion
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.
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:
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:
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:
Output:
Output:
Conclusion
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.
Syntax:
USE database_name;
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.
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
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.
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.
Output:
ag
name e
Bob 40
Charli
35
e
Eve 45
Frank 50
Hanna
38
h
The ORDER BY clause sorts the result set based on one or more columns.
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
Output:
salar
name y
Fran 7000
k 0
Eve 6500
salar
name y
6000
Bob
0
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.
Output:
departm average_sal
ent ary
Sales 52500
Marketin
62500
g
HR 57500
IT 50500
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
Syntax:
columnN datatype(size)
);
Key Terms
Query:
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Phone int(10)
);
Output:
Explanation:
Age has a CHECK constraint, ensuring it’s within the range of 0 to 99.
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)
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.
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:
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:
FROM customer;
Output:
Note: We can use * instead of column name to copy whole table to another
table.
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.
4. After creating a table, use the following command to view the structure of
your table:
DESC table_name;
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.
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:
The syntax of the command remains the same in Oracle, SQL Server and
MySQL.
To demonstrate how to use the DROP TABLE command, let's first create a
database and a table, and then we will drop it.
First, we will create a database and table on which the SQL queries will be
run.
Output:
At this point, the categories table has been created with three rows of
sample data.
Now, let’s use the DROP TABLE statement to delete the categories table
permanently
Query:
Output:
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.
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
Here are some common tasks you can achieve using the ALTER command:
Renaming a table.
1. Renaming a Table
2. Renaming a Column
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.
Let's insert some data and then perform ALTER operation to understand
better about alter command.
Output
Student Table
Syntax
Query:
Output
Output
Query:
Student_Details table
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
Query:
Output
output
Syntax
Query:
Output
nam ag
id e e email phone
99999999
1 Amit 20 [email protected]
99
[email protected] 77777777
3 Priya 21
om 77
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.
This command deletes the marks column entirely from the table
Conclusion
In this article, We will learn about SQL TRUNCATE TABLE in detail with the
help of various examples and so on.
Unlike the DELETE statement, which removes rows one at a time and
can be rolled back (depending on the database support
for transactions).
Syntax
First, we will create a demo SQL database and table, on which we will use the
TRUNCATE TABLE command.
EMP_ID INT(4),
NAME VARCHAR(20),
AGE INT(3),
DOB DATE,
SALARY DECIMAL(7,2));
Query:
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
WHERE
Not supported Supported
Clause
Permissio
Requires ALTER permission Requires DROP permission
ns
on the table. on the table.
Required
TRUNCATE TABLE is faster and uses fewer system and transaction logs
compared to DELETE.
Conclusion
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.
1. Simple Cloning
2. Deep Cloning
3. Shallow Cloning
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)
);
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
Example:
Let us see the example to understand how simple cloning syntax works
Output
Simp
le Cloning
Explanation:
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
Example:
Output
Shallow clone of student table (Original Table)
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
Example:
Output
STU
DENT_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
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?
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.
Syntax:
id name
1 Lalit
Atharv
2
a
There are 2 types of Temporary Tables: Local Temporary Table, and Global
Temporary Table. These are explained as following below.
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:
AS
BEGIN
END
EXECUTE ProcTemp
Global Temporary Table: To create a Global Temporary Table, add the "##"
symbol before the table name.
Example:
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.
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
Syntax:
Parameters:
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:
Example:
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:
Example:
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:
4. RENAME COLUMN
Query:
Example:
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:
Example:
ROLL_N
O NAME
1 Emma
2 Travis
Jennife
3
r
Roxann
4
e
To add new columns AGE and COURSE to the Student table, use ALTER TABLE
statement with the ADD clause.
Query:
ROLL_N AG COURS
O NAME E E
Jennife
null null
3 r
Roxann
null null
4 e
Query:
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
UPDATE Statement
DELETE Statement
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.
Syntax
Parameters:
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.
Output
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
Query:
Output
CustomerNa LastNa
me me
Liam Smith
Sophia Miller
CustomerNa LastNa
me me
Akira Tanaka
Hernand
Carlos
ez
Isabella Rossi
In this example, we will fetch all the fields from table Customer:
Query:
Output
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
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
Query:
Output
Count customer_co
ry unt
USA 3
Japan 1
Italy 1
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:
Output
Count
ry
USA
Japan
Italy
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:
Output
Count customer_co
ry unt
USA 3
In this example, we will use SELECT Statement with ORDER BY clause. Here,
Sort results by Age in descending order.
Query:
Output
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.
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:
Parameters:
Example: Let’s see how the INSERT INTO statement works with practical
examples.
Output
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:
Output
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
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
Parameters:
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).
Syntax
Output
ROLL_N AG
O NAME ADDRESS PHONE E
xxxxxxx
1 Liam New York 18
xxx
xxxxxxx
2 Sophia Berlin 18
xxx
xxx
xxxxxxx
4 Carlos Tokyo 18
xxx
xxxxxxx
5 Isabella Rome 19
xxx
Mateo xxxxxxx
7 Madrid 15
Garcia xxx
Hana xxxxxxx
8 Osaka 18
Suzuki xxx
Amelia xxxxxxx
10 London 17
Brown xxx
Explanation:
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
Example: If you want to copy all data from the OldStudent table into the
Student table, use this query:
Output
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
Mateo xxxxxxxxx
7 Madrid 15
Garcia x
Hana xxxxxxxxx
8 Osaka 18
Suzuki 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
Example: Let’s say we want to copy only the Name and Age columns from
OldStudent into Student:
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
Mateo xxxxxxx
Madrid 15
7 Garcia xxx
Hana xxxxxxx
Osaka 18
8 Suzuki xxx
Brown xxx
Arjun
NULL NULL 21
NULL Mehta
You can also insert specific rows based on a condition by using the WHERE
clause with the SELECT statement.
Output
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
Mateo xxxxxxxxx
7 Madrid 15
Garcia x
Hana xxxxxxxxx
8 Osaka 18
Suzuki 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
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.
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.
Query:
CREATE TABLE Employees (
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.
Query:
VALUES
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.
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
EmployeeName VARCHAR(100),
Age INT,
Department VARCHAR(50)
);
INSERT INTO NewEmployees (EmployeeID, EmployeeName, Age,
Department)
VALUES
Output:
5 Alice Johnson 29 HR
Engineerin
8 David Lee 40
g
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:
FROM NewEmployees
Output:
Employee EmployeeNa Ag
ID me e Department
Human
4 Lucy Green 25
Resources
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)
COMMIT;
Output:
Employee EmployeeNa Ag
ID me e Department
Resources
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
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;
Parameters
SET: The column(s) you want to update and their new values.
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.
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:
Output
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
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'.
Query:
UPDATE Customer
SET CustomerName = 'Satyam',
Country = 'USA'
WHERE CustomerID = 1;
Output:
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
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
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.
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.
Syntax:
Parameter Explanation
Output
Pravee praveen_dagger@yahoo
2 HR
n .com
id name email department
4 Rithvik [email protected] IT
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
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:
Output:
Pravee praveen_dagger@yahoo
2 HR
n .com
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
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:
Output
Pravee praveen_dagger@yahoo
2 HR
n .com
Quality
5 Suraj [email protected]
Assurance
6 Om [email protected] IT
Query:
Output:
All of the records in the table will be deleted, there are no records left to
display. The table GFG_Employees will become empty.
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:
Explanation: The ROLLBACK command will undo the changes made by the
DELETE statement, effectively restoring the records that were deleted during
the transaction.
Query:
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
Query:
Output
Explanation: This query will return the duplicate records based on the
combination of EMPNAME, DEPT, CONTACTNO, and CITY.
There are several ways to delete duplicate rows in SQL. Here, we will explain
five methods to handle this task effectively.
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()
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
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
You can create a temporary table to hold unique records and then replace
the original table with the new, clean data.
Steps:
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
65
You can use DISTINCT to select only unique rows and then insert them back
into the original table, effectively deleting duplicates.
Query:
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
G 1
914933569 MORADABA
5 SANJAY SALES
4 D
783599412
8 AMAN IT RAMPUR
65
Conclusion
WHERE Clause
WITH Clause
HAVING Clause
ORDER By Clause
Group By Clause
LIMIT Clause
Distinct Clause
FETCH
Aliases
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:
Syntax:
Parameters:
We will create a basic employee table structure in SQL for performing all the
where clause operation.
Query:
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
Query:
Output:
EmpI Countr Ag
D Name y e Mob
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
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:
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
Query:
Output:
EmpI Count Ag
D Name ry e Mob
Shubha 7384797
1 India 23
m 34
Query:
Output:
EmpI Count Ag
D Name ry e Mob
Shubha 7384797
1 India 23
m 34
Australi 4367895
2 Aman 21
a 55
Query:
Output:
Name
Aman
Aditya
Shubha
m
Operator Description
= Equal to
Operator Description
BETWEE
In an inclusive Range
N
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.
Syntax:
Key Terms
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
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:
Output
Employee Sala
ID Name ry
9400
100022 Bill
0
Walde 8000
100845
n 0
Explanation:
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
Airbus 6000
70007 Kim
380 0
2000
70002 Boeing Laura
0
Airbus 8005
10027 Will
380 0
2500
115585 Boeing Smith
0
380 0
Query:
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.
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.
2. Nested WITH Clauses: You can define multiple CTEs in a single query,
and they can reference each other.
Example:
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
Syntax:
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
HAVING condition;
First, we create the Employee table and insert sample data to demonstrate
the HAVING clause.
Query:
Output
Michael 6500
2 Male Sales 5
Smith 0
7500
4 James Davis Male Finance 7
0
In this Example we calculate the total salary of all employees and display it
only if it meets the specified condition.
Query:
Output
Total_Sal
ary
290000
In this example, we calculate the average salary of all employees and display
it only if the average exceeds 55,000.
Query:
Output
Average_Sal
ary
58000
In this example, we find the highest salary among employees and display it
only if it exceeds 70,000.
Query:
Output
Max_Sal
ary
75000
In this example, we find the least experienced employee and display it only if
their experience is less than 3 years.
Query:
Output
Min_Experie
nce
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:
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.
Syntax:
Key Terms:
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
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.
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:
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
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 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:
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
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.
Syntax:
Query:
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
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.
Query execution order: FROM -> WHERE -> GROUP BY -> HAVING ->
SELECT -> ORDER BY.
Syntax:
Parameters:
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.
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
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:
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.
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:
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.
In this section, we will use Employee table(emp) first insert some sample
data, then perform GROUP BY queries combined with HAVING.
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
In this query, we group employees by name and display only those whose
total salary is greater than 50,000.
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
In this query, we group employees by age and display only those age groups
where average salary is above 60,000.
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
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.
Syntax:
Key Terms
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:
Output:
Student Table
Query:
Output:
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:
Output:
Syntax:
OR
Query:
SELECT *
FROM Student
ORDER BY age
LIMIT 2 OFFSET 2;
Output:
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;
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:
Output:
SQL LIMIT to Get the nth Highest Value Example Output
Explanation:
Skips 2 records (LIMIT 2) and retrieves the next one (LIMIT 2,1).
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.
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:
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.
The LIMIT clause is used to set an upper limit on the number of tuples
returned by SQL.
The LIMIT clause can also be specified using the SQL 2008
OFFSET/FETCH FIRST clauses.
Conclusion
Syntax:
Parameters:
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:
ROLL_NO INT,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(20),
AGE INT
);
VALUES
(1, 'Shubham Kumar', '123 Main Street, Bangalore', '9876543210', 23),
Output:
ROLL_N AG
O NAME ADDRESS PHONE E
Mumbai 11
98765432
3 Naveen Singh 789 Market Lane, Delhi 26
12
98765432
9 Naveen Singh 789 Market Lane, Delhi 26
12
Kolkata 13
The query returns only unique names, eliminating the duplicate entries from
the table.
Query:
Output:
output
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:
Output:
AG
NAME E
Shubham
23
Kumar
Shreya Gupta 23
Naveen Singh 26
Aman Chopra 22
Aditya Patel 27
Avdeep Desai 24
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:
Output:
AG
E
2
2
AG
E
2
3
2
4
2
6
2
7
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:
Output:
COUNT(DISTINCT
AGE)
Query:
Output:
AGE
23
26
22
27
24
NUL
L
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.
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.
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.
SQL Server
MS Access
Syntax:
Here,
);
In this example, we will fetch the top 4 rows from the table.
Query:
SELECT TOP 4*
FROM Employee;
Output:
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
Output:
SQL SELECT TOP with ORDER BY Clause Example Output
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.
The PERCENT keyword is utilized to select the primary and percent of all-out
rows. For example,
Query:
FROM Employee;
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).
We can also include some situations using the TOP PERCENT with the WHERE
clause in the above query.
Query:
FROM Employee
WHERE Salary<50000;
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 limits the number of results returned in the results set.
The LIMIT Clause is utilized with the accompanying database systems:
MySQL
PostgreSQL
SQLite
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 (
);
Output:
In this example, we will use the SELECT LIMIT clause to display only 2 results.
Query:
LIMIT 2;
Output:
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.
The accompanying query selects the initial 4 records from the Employee
table with a given condition.
Query:
LIMIT 2;
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.
Query:
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 fetches the first given number of rows from the
table.
IBM DB2
Oracle
PostgreSQL
Syntax:
SELECT columns FROM table WHERE condition FETCH FIRST n ROWS ONLY;
Here,
In this example, we will fetch the first 3 rows from the table.
Query:
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.
In this example, we will fetch first 50% of the data from the table
Query:
SELECT *
FROM Employee
Output:
Here, the above query fetches the first 50% of the total number of rows (i.e.,
2 rows) from the table.
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
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
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT,
Phone VARCHAR(15)
);
VALUES
Output:
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:
Performing calculations
Syntax:
FROM table_name;
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).
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
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.
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:
FROM Customer AS c
Output:
Locati
Name on
Shubha
India
m
Australi
Aman
a
Sri
Naveen
Lanka
Aditya Austria
Nishant Spain
AND Operator
OR Operator
Logical Operators
LIKE Operator
IN Operator
NOT Operator
UNION Operator
EXCEPT Operator
BETWEEN Operator
INTERSECT Operator
EXISTS Operator
CASE Operator
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.
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:
Here,
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:
If suppose we want to fetch all the records from the Student table where Age
is 18 and ADDRESS is Delhi.
Query:
Output:
ROLL_N ADDRE Ag
O NAME SS PHONE e
XXXXXXXX
1 Ram Delhi 18
XX
SURES XXXXXXXX
4 Delhi 18
H XX
To fetch all the records from the Student table where NAME is Ram or NAME
is SUJIT.
Query:
Output:
XXXXXXXX
1 Ram Delhi 18
XX
XXXXXXXX
3 SUJIT ROHTAK 20
XX
XXXXXXXX
3 SUJIT ROHTAK 20
XX
Syntax:
Example
Query:
Output:
ROLL_N ADDRES Ag
O NAME S PHONE e
XXXXXXXX
1 Ram Delhi 18
XX
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.
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
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:
Output
output
Explanation:
2. IN Operator
Example
Retrieve the records of employees from the employee table who are located
in either 'Allahabad' or 'Patna'.
Query:
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:
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
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:
Example
Retrieve the records of employees from the employee table whose city
names start with the letter 'P'.
Query:
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
Inclusive Range – Includes both the lower and upper limits in the
result set.
Example
Query:
Output
output
Explanation:
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.
Example
Query:
Output
output
Explanation:
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.
Example
Query:
Output
Explanation:
9. EXISTS Operator
The EXISTS operator in SQL is used to check whether a subquery returns any
rows.
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
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.
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.
Example
Query:
Output
output
Explanation:
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.
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:
FROM table_name
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:
This following query will only return products whose name starts with "apple"
and is spelled exactly like that, without capital letters.
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:
Examples of Wildcards
The below table shows some examples on how wild card can be written and
what do they mean:
Pattern Meaning
'a%t' Match strings that contain the start with 'a' and end with 't'.
'%wow Match strings that contain the substring 'wow' in them at any
%' position.
'_wow Match strings that contain the substring 'wow' in them at the
%' second position.
Match strings that start with 'a and contain at least 2 more
'a_ _%'
characters.
In this tutorial on SQL LIKE Operator, we will use the following table in the
examples.
Supplier Table
Name VARCHAR(50),
Address VARCHAR(100)
);
VALUES
Supplier
ID Name Address
Paragon
S1 21-3, Okhla, Delhi
Suppliers
21, Faridabad,
S2 Mango Nation
Haryana
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.
FROM Supplier
Output:
S Caravan
2-A, Pitampura, Delhi
4 Traders
SELECT *
FROM Supplier
Output:
S Paragon
21-3, Okhla, Delhi
1 Suppliers
FROM Supplier
Output:
FROM Supplier
Output:
Supplier
ID Name Address
Caravan
S4 2-A, Pitampura, Delhi
Traders
FROM Supplier
WHERE Name NOT LIKE '%Mango%';
Output:
Supplier
ID Name Address
Paragon
S1 21-3, Okhla, Delhi
Suppliers
Caravan
S4 2-A, Pitampura, Delhi
Traders
Harish and
S5 Gurgaon, NCR
Sons
2/1, Faridabad,
S6 Om Suppliers
Haryana
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
IN Operator
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:
We will use the following SQL table for our examples below:
Output:
Ss Addres Se
Fname Lname n Bdate s x Salary
1990-07-
Harry Stark 2 Delhi M 3333.00
31
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
SQL Query to get Fname and Lname of employees who have address in Delhi
and Himachal
Query:
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.
We can use the SQL IN with the NOT operator to exclude specified data
from our result.
Query:
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
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:
Ss Addre Se
Fname Lname n Bdate ss x Salary
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.
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.
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.
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:
CustomerName VARCHAR(50),
City VARCHAR(50),
PostalCode VARCHAR(10),
Country VARCHAR(50)
);
INSERT INTO Customers (CustomerID, CustomerName, City, PostalCode,
Country)
VALUES
New
1 John Wick 1248 USA
York
Around the
2 London WA1 1DP UK
Horn
New
3 Rohan 100084 India
Delhi
The following SQL statement selects all fields from Customers table where
the country is not UK.
Query:
SELECT *
FROM Customers
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.
The NOT operator can also be used with the IN condition to exclude multiple
values from the result set.
Query:
SELECT *
FROM Customers
Output:
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.
We can also combine NOT with the LIKE operator to exclude records that
match a certain pattern.
Query:
SELECT *
FROM Customers
Output:
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.
To exclude records where a column has a NULL value, combine NOT with the
IS NULL condition.
Query:
SELECT *
FROM Customers
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.
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
Output:
New
3 Rohan 100084 India
Delhi
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.
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 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:
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:
name varchar(100),
contest_score int,
rank int,
coding_streak int
);
VALUES('vish3001','Vishu',100,01,150);
VALUES('neeraj119','Neeraj',99,02,125);
VALUES('ayush105','Aayush',98,03,110);
VALUES('sumit85','Sumit',99,02,100);
Output:
vish300
Vishu 100 1 150
1
neeraj1 Neera
99 2 125
19 j
ayush10 Aayus
98 3 110
5 h
harsh05 Harsh 98 3 95
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
In the above image, we can see we have all those rows displayed which do
not have their name equal to 'Harsh'.
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:
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.
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:
FROM geeksforgeeks
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.
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
In this article, we will learn how to use the IS NULL operator in SQL, with
practical examples to help you understand its functionality.
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.
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:
name varchar(100),
problems_solved int,
coding_score int,
email varchar(100)
);
VALUES
Output:
[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
To filter rows where the email column contains NULL, use the IS NULL
operator in a WHERE clause:
Query:
SELECT *
FROM students
Output:
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
Output:
FROM students
Output:
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.
Query:
UPDATE students
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]".
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:
Output:
SQl IS NULL is used to detect any rows that contain a NULL value in its
column.
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.
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.
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.
Each table used within UNION must have the same number of columns.
Syntax:
Note: SQL UNION and UNION ALL difference is that UNION operator removes
duplicate rows from results set and
Emp1 Table
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
Output:
Emp1 Table
Emp2 Table
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
Output:
Emp2 Table
In this example, we will find the cities (only unique values) from both the
"Table1" and the "Table2" tables:
Query:
UNION
ORDER BY Country;
Output:
output
In the below example, we will find the cities (duplicate values also) from both
the "Emp1" and the "Emp2" tables:
Query:
UNION ALL
ORDER BY Country;
Output:
Country
Australi
a
Austria
Englan
Country
France
India
India
Ireland
Spain
Spain
Sri
lanka
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
The following SQL statement returns the cities (duplicate values also) from
both the "Geeks1" and the "Geeks2" tables:
Query:
WHERE Name='Aditya'
UNION ALL
WHERE Country='Ireland'
ORDER BY Country;
Output:
output
The SQL UNION operator combines the result sets of two or more
SELECT queries.
Columns in the result set must be in the same order and have the
same data types.
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
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.
Syntax:
UNION ALL
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
UNION ALL
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.
Suppose We want to combine the ROLL_NO from both tables and align the
column names for consistency.
Query:
UNION ALL
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.
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.
Duplicate
Includes all duplicates Removes duplicate records
Records
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.
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.
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.
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.
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.
Students Table
Name VARCHAR(100),
Course VARCHAR(100)
);
Output:
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
CREATE TABLE TA (
Name VARCHAR(100),
Course VARCHAR(100)
);
Output:
Student Nam Cours
ID e e
Kevi
1 TOC
n
2 Sita IP
Mani
3 AP
k
Rekh
4 SNS
a
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.
Query:
Output:
Name
Roha
n
Mans
i
Mans
i
Megh
Name
While both EXCEPT and NOT IN are used to exclude certain records, there
are important differences between them.
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.
In this article, we will explore the SQL BETWEEN operator with examples.
The SQL BETWEEN operator is used to filter the result set within a
specified range.
SELECT column_name(s)
FROM table_name
Parameters:
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
0 01
6800 2019-05-
5 Tom Harris 38
0 12
Find employees whose last names are not alphabetically between 'B' and 'S'.
Query:
FROM Employees
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'.
Find employees hired between January 1, 2020 and December 31, 2021.
Query:
FROM Employees
Output:
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.
FROM Employees
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.
Find employees whose salaries are between 50,000 and 70,000 and
whose first names are either 'John', 'Sue', or 'Tom'.
Query:
FROM Employees
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
lets Consider the following Products Table and OrderDetails Table for
explaining the examples.
Products Table
OrderDetails Table
Queries
Query:
FROM Products
WHERE TRUE;
Output:
This query retrieves all product names from the Products table because TRUE
always evaluates as true for every row.
SELECT ProductName
FROM Products
FROM OrderDetails
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
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.
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.
Syntax:
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition(s));
Query:
FROM Products
FROM OrderDetails);
Output:
This query finds the distinct CategoryIDs of products that exist in the
OrderDetails table.
Query:
SELECT ProductName
FROM Products
FROM OrderDetails
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.
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.
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.
Syntax:
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
Query:
SELECT CustomerID
FROM Customers
INTERSECT
SELECT CustomerID
FROM Orders;
Output:
Customer
ID
Explanation:
Query:
SELECT CustomerID
FROM Customers
WHERE CustomerID BETWEEN 3 AND 8
INTERSECT
SELECT CustomerID
FROM Orders;
Output:
Customer
ID
8
Explanation:
The INTERSECT operator ensures that only customers from this filtered
set who have placed an order are included in the result.
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.
Column Count & Data Types: Both SELECT statements must have
the same number of columns with compatible data types.
Conclusion
SQL | EXISTS
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS (
SELECT column_name(s)
FROM subquery_table
WHERE condition
);
Orders Table:
To fetch the first and last name of the customers who placed atleast one
order.
Query:
FROM Customers
FROM Orders
Fetch last and first name of the customers who has not placed any order.
FROM Customers
FROM Orders
Output:
Delete the record of all the customer from Order Table whose last name is
'Mehra'.
DELETE
FROM Orders
FROM customers
Output:
UPDATE Customers
FROM Customers
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.
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.
Syntax:
We will be using this sample SQL table for our examples on SQL CASE
statement:
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
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
Query:
CASE
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.
Query:
CASE
END AS QuantityText
FROM Customer;
Output:
Ag
CustomerName e QuantityText
Nishant. Salchichas
22 The Age is over 30
S.A.
Query:
FROM Customer
ORDER BY
(CASE
ELSE Age
END);
Output:
Count
CustomerName ry
Australi
Aman
a
Aditya Austria
Nishant. Salchichas
Spain
S.A.
Sri
Naveen
lanka
Shubham India
The SQL CASE statement is a conditional expression that allows for the
execution of different queries based on specified conditions.
Conclusion
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
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().
1. Count()
Examples:
2. SUM()
Examples:
-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;
3. AVG()
Examples:
The MIN() and MAX() functions return the smallest and largest values,
respectively, from a column.
Examples:
Examples Queries
1 A 802
2 B 403
3 C 604
4 D 705
5 E 606
6 F NULL
Output:
TotalEmploy
ees
Output:
TotalSal
ary
3120
Output:
AverageSal
ary
624
Output:
HighestSal
ary
802
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.
Syntax
COUNT(expression)
Key Terms
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
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.
Query:
Output
COUNT(DISTINCT
Country)
Explanation:
The result 4 indicates that there are four distinct countries listed in the
table (Spain, Mexico, India, and Germany).
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.
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:
Output
CustomerCo
Country unt
Spain 4
CustomerCo
Country unt
Mexico 2
India 2
Germa
1
ny
Explanation:
The result shows the number of customers from each country: 4 from
Spain, 2 from Mexico, 2 from India, and 1 from Germany
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:
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.
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:
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.
Explanation:
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:
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
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 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.
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Key Terms
table_name: The name of the table from which to retrieve the data.
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
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:
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.
We can also use the SUM() function with an expression to calculate sums
based on some logic or mathematical operations.
Query:
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.
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.
Query:
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.
Query:
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.
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.
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:
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
Query:
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.
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
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.
Query:
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.
Query:
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
To sort groups by their minimum invoice price in ascending order, the query
uses the combination of GROUP BY and ORDER BY clauses:
Query:
Output:
InvoiceMo Lowest
nth Invoice
June $99
July $299
InvoiceMo Lowest
nth Invoice
This query filters groups where the smallest invoice price exceeds $150.
Query:
Output:
InvoiceMo Lowest
nth Invoice
July $299
Explanation:
This query filters groups where the smallest invoice price is below $150.
Query:
Output:
InvoiceMo Lowest
nth Invoice
June $99
Explanation:
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.
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:
Explanation:
This query retrieves the complete record associated with the lowest invoice
price.
Query:
SELECT *
FROM Sales
WHERE price = (SELECT MIN(price) FROM Sales);
Output:
Explanation:
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.
This query retrieves detailed information about the invoice associated with
the lowest price.
Query:
Output:
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
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.
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.
Sales Table
Sales 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:
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.
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:
Output:
Highest
Sale
1500.00
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:
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.
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:
Output:
Latest Sale
Date
2023-02-01
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:
1 500.00
2 1500.00
3 300.00
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
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.
In this, we will learn about the AVG() function, and its syntax by
understanding various examples and their output with explanation and so
on.
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:
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
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.
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
Output:
| average_science_score |
|-----------------------|
| 80 |
Considerations
While the AVG() function is a powerful tool for data analysis, there are some
considerations to keep in mind:
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.
Composite Key
Unique Constraints
Alternate Key
CHECK Constraints
DEFAULT Constraints
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.
Syntax:
(
column1 data_type(size) NOT NULL,
....
);
NOT NULL: ensures the column cannot have NULL (empty) values.
The syntax for applying the NOT NULL constraint can be as follows:
...
);
You can also add a NOT NULL constraint to an existing column in a table
using the ALTER TABLE statement:
Name VARCHAR(50),
Country VARCHAR(50),
Age INT(2),
Salary INT(10)
);
In this 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:
Now, the Name column will not accept NULL values, meaning every
employee record must have a name.
);
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.
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.
Syntax
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
FirstName varchar(255),
Age int
);
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
Output
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.
PersonID int,
Avoid NULL values: Always ensure that the columns involved in the
primary key do not accept NULL values.
Conclusion
Syntax:
);
The syntax to add a foreign key with ALTER TABLE statement is:
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:
DESC STUDENTS;
Output:
DESC COURSES;
Query:
The following query will create the 'customers' and 'orders' table.
CustomerID CustomerNa
(Primary Key) me
1 John
2 Jane
3 Bob
1 101 1
2 102 2
3 103 3
Output :
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:
Output:
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.
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.
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.
Creating a database:
CREATE School;
Using database:
USE School;
(rollNumber INT,
name VARCHAR(30),
class VARCHAR(30),
section VARCHAR(1),
mobile VARCHAR(10),
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.
OUTPUT:
When to Use a Composite Key?
Conclusion
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.
Syntax:
column2 datatype,
...
);
Let's create a Customers table where the Email column must be unique.
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.
The third insert will fail because the Email [email protected] already
exists in the Customers table.
CustomerID INT,
ProductID INT,
OrderDate DATE,
);
In this example, the combination of CustomerID and ProductID must be
unique, meaning a customer cannot order the same product more than once.
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
);
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
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.
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."
we are going to see how to create an ALTERNATE Key in SQL using sample
tables as shown.
Product Information
Washing
1001 25
Soap
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
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))
1. Creating a Database
2. Creating a Table
.....
)
Output :
Pro
duct Table
Customer Table
A pictorial view of all the keys present in the table is shown below :
KEYS
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.
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.
The CHECK constraint can be defined when creating a table or added later
using the ALTER statement.
2. Using CHECK with ALTER TABLE (to add a condition after table
creation):
Let’s look at some practical examples to better understand how the CHECK
constraint works in SQL.
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:
-- 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.
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:
-- Valid insert
INSERT INTO Employee (EmployeeID, Name, Age, Salary)
VALUES (1, 'Alice Johnson', 30, 50000);
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.
Query:
Syntax :
...
);
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:
Name VARCHAR(255),
Age INT,
);
-- Explicit value
INSERT INTO Geeks (ID, Name, Age, Location) VALUES (4, 'Mira', 23, 'Delhi');
INSERT INTO Geeks (ID, Name, Age, Location) VALUES (5, 'Hema', 27);
INSERT INTO Geeks (ID, Name, Age, Location) VALUES (6, 'Neha', 25, 'Delhi');
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.
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:
DROP DEFAULT;
Query:
ALTER TABLE Geeks
DROP DEFAULT;
Query:
Note - Dropping the default constraint will not affect the current data in the
table, it will only apply to new rows.
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
DELETE JOIN
Recursive 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.
Syntax:
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as 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:
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.
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
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
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
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Key Terms
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
Example:
Employee
1 Ram 10
2 Jon 30
3 Bob 50
Employee
Department
Dept_ Dept_na
id me
10 IT
30 HR
40 TIS
(Employee) ? (Department)
Output:
1 Ram 10 10 IT
2 Jon 30 30 HR
SQL Outer Join
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.
1. Employees Table
Employee Departmen
ID Name tID
1 John 101
2 Sarah 102
Micha
3 NULL
el
4 Emma 103
2. Departments Table
Departmen DepartmentN
tID ame
101 HR
102 IT
Departmen DepartmentN
tID ame
103 Marketing
104 Finance
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.
Syntax:
Output
Departmen DepartmentN
Name tID ame
John 101 HR
Sarah 102 IT
Micha
NULL NULL
el
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.
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:
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:
Output
Departmen DepartmentN
Name tID ame
John 101 HR
Sara
102 IT
h
Emm
103 Marketing
a
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:
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:
Departmen DepartmentN
Name tID ame
John 101 HR
Sarah 102 IT
Micha
NULL NULL
el
One need to include all records from one or both tables, even if no
match exists.
Merging datasets from different sources where some records may not
align perfectly.
Difference Between INNER JOIN and OUTER 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.
LEFT JOIN
Syntax:
SELECT column_name(s)
FROM tableA
Employee Table
CREATE TABLE Emp (
Name VARCHAR(50),
Country VARCHAR(50),
Age INT,
Salary INT,
department_id INT
);
Output:
Employee Table
Department Table
department_name VARCHAR(50),
department_head VARCHAR(50),
location VARCHAR(50)
);
Output:
Department Table
Query:
department_name, department.department_head,
department.location
FROM Emp
Explanation:
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:
FROM Emp e
Output:
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:
d.department_head, d.location
FROM Emp e
e.department_id = d.department_id;
Output:
Explanation:
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.
RIGHT JOIN
Syntax:
SELECT column_name(s)
FROM tableA
ON tableA.column_name = tableB.column_name;
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
ON employee.dept_no = department.dept_no;
Output:
emp_n d_nam
o emp_name e location
Amrita Hyderab
E2 HR
Aggarwal ad
[NUL
[NULL] Testing Noida
L]
[NUL Marketi
[NULL] Mathura
L] ng
Explanation:
1. Data Completeness: When you need to show all records from the right
table (e.g., all departments).
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
SELECT columns
FROM table1
ON table1.column = table2.column;
Parameters:
FULL JOIN table2: Specifies the second table to join with the first
table using a FULL JOIN.
This query retrieves all records from both table1 and table2, returning NULL
where there are no matches.
1. Books Table
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
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
Query:
SELECT
b.BOOK_ID,
b.BOOK_NAME,
a.AUTHOR_NAME,
p.PUBLISHER_NAME
FROM Books b
Output:
Shyam
2 GATE CRACKER Wiley
Sunder
NK
4 Mohan Gupta Springer
PUBLICATIONS
BIG BANG
5 Raj Kapoor Elsevier
THEORY
Explanation:
FULL JOIN ensures that all rows are included even if a match is missing.
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
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.
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:
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
JATIN
2 47 63996
VERMA
Table 2- Orders
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:
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;
Syntax:
SELECT columns
FROM table AS alias1
JOIN table AS alias2
ON alias1.column = alias2.related_column;
Here is the query to create the table and insert sample data:
1 Zaid 3
2 Rahul 3
3 Raman 4
4 Kamran NULL
5 Farhan 4
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:
Output
employee manager
Zaid Raman
employee manager
Rahul Raman
Raman Kamran
Farhan Kamran
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.
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
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.
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
Explanation:
The WHERE clause filters the rows for col1 = 21 and col1 = 31.
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
Explanation:
Conclusion
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.
Deletes rows from one primary table based on conditions set by joining
additional tables.
Syntax:
DELETE table1
FROM table1 JOIN table2
ON table1.attribute_name = table2.attribute_name
WHERE condition
Key Terms:
1. Student 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
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
The join with the students table helps identify exactly which rows to
remove.
We can only specify one table in the DELETE clause, even if multiple
tables are joined in the FROM clause.
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.
Syntax:
-- 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
)
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:
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 process repeats until all employees who report to Ankit (and
indirectly to others) are listed.
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
Date Functions
String Functions
Numeric Functions
Statistical Functions
JSON Functions
Conversion Functions
Datatype Functions
LTRIM Function
UPPER Function
RTRIM Function
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
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:
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:
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:
Output
current_ti
me
14:35:27
4. DATE()
Query:
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:
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:
Output
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()
Query:
AS sale_date_minus_3_days
FROM sales;
Output
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:
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()
Query:
Output
sale_i product_na
d me formatted_sale_date
10. ADDDATE()
Query:
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()
Query:
Output
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 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.
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:
Query:
Output:
John Doe
Query:
Output:
Query:
Output:
HELLO
hello
LENGTH() returns the length of a string in bytes. This can be useful for
working with multi-byte character sets.
Query:
Query:
Output:
Hello SQL
Query:
Output:
Hello
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:
Output:
Hello
World
Query:
Output:
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:
Output:
Hello World
Query:
Output:
olleH
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.
Syntax:
SELECT ascii('t');
Output:
116
Syntax:
Output:
geeks_for_geeks
Syntax:
Output:
Output:
‘98.10%’
Syntax:
Output:
Syntax:
Output:
geeksforgeeks to learn
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:
Output:
Syntax:
Output:
000geeks
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:
Output:
for
Syntax:
Output:
Syntax:
Output:
geeksgeeks
22. REPLACE(): Replace a Substring in a String
Syntax:
REPLACE('123geeks123', '123');
Output:
geeks
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’
Syntax:
RTRIM('geeksxyxzyyy', 'xyz');
Output:
‘geeks’
Syntax:
SELECT SPACE(7);
Output:
‘ ‘
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:
Syntax
Output:
left. '0');
Syntax:
SELECT ABS(number);
Example:
SELECT ABS(-25);
Output:
25
Syntax:
SELECT CEIL(number);
Example:
SELECT CEIL(12.34);
Output:
13
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
Syntax:
Example:
Output:
15.68
Syntax:
Example:
Output:
12.98
Syntax:
Example:
SELECT MOD(10, 3);
Output:
Syntax:
Example:
Output:
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:
Syntax:
SELECT EXP(number);
Example:
SELECT EXP(1);
Output:
2.718281828459045
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);
Example:
SELECT LOG(100);
Output:
4.605170186
Syntax:
SELECT RAND();
Example:
SELECT RAND();
Output:
0.287372
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.
Table :
StudentDetails
employees Table:
Table:Employees
sales_data:
Table:Sales_data
financial_data:
Table: financial_data
1. AVG() Function
Example Query:
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:
Example Query:
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:
Example Query:
Count of Student
Example Query:
Output:
4. Max() Function
Syntax:
Example Query:
Output:
Maximum marks
5. MIN() Function
Syntax:
Output:
Minimum marks
Syntax:
Example Query:
Output:
Variance marks
Syntax:
Example Query:
Output:
8. PERCENTILE_CONT() Function
Calculates a specified percentile value for a numeric column.
Syntax:
Example Query:
FROM employees;
Output:
9. CORR() Function
Syntax:
Example Query:
FROM sales_data;
Output:
correlation coefficient between 'sales'
and 'profit'
10 .COVAR_POP() Function
Syntax:
Example Query:
FROM financial_data;
Output:
Conclusion
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.
Now let us create a table named "Authors" and let us insert some data into
it as shown below:
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
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:
Let us see the important functionalities available in SQL Server which can be
used with JSON data.
{
"Information":
{"SchoolDetails":
[{"Name": "VidhyaMandhir"}, {"Name": "Chettinad"},
{"Name":"PSSenior"}]
}
}
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.
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
Example :
SELECT JSON_VALUE(@JSONData,'$.Information.SchoolDetails[0].Name') as
SchoolName
Example 3: JSON_QUERY(JSON string, path)
SELECT JSON_QUERY(@JSONData,'$.Information.SchoolDetails')
AS LISTOFSCHOOLS
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
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
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 :
Note: Even large data also can be placed. As a sample, we showed only a
single row.
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)
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.
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.
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.
Azure SQL provides several functions to work with JSON data, making it
simple to query, extract, and modify JSON stored in columns.
UPDATE Users
SET data = JSON_MODIFY(data, '$.address.city', 'New York')
WHERE UserID = 1;
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.
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.
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
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
SELECT employee_id,first_name,salary
FROM employees
WHERE salary > '15000';
Output:
In this query:
1. TO_CHAR Function
TO_CHAR(expression, 'format_model')
TO_CHAR(date, ’format_model’)
Example:
Output :
EMPLOYEE MONTH_HIR
_ID ED
205 06/94
MONT
Full name of the month
H
the week
ELEMENT DESCRIPTION
AM or PM Meridian indicator
MI Minute 0-59
SS Second 0-59
Other Formats
ELEME
NT DESCRIPTION
ELEMENT DESCRIPTION
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
Vanshik 5 August
a 2004
11 March
Faviet
2005
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
Example :
Output :
SALA
RY
$500
0
TO_NUMBER(char[, ’format_model’])
TO_DATE(char[, ’format_model’])
Example :
Output :
LASTNA
ME HIREDATE
24-MAY-
Kumar
1999
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.
Memory-efficient storage
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 types are used when precise numeric values are needed, such
as for financial data, quantities, and counts. Some common exact numeric
types include:
9,223,372,036,854,775,807
Standard integer
INT -2,147,483,648 to 2,147,483,647
values
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
-1.79E+308 to
FLOAT Approximate numeric values
1.79E+308
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.
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
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
DATETI store both the data and time (year, month, day,
8 Bytes
ME hour, minute, second)
Binary data types are used to store binary data such as images, videos or
other file types. These include:
Data
Type Description Max Length
The BOOLEAN data types are used to store logical values, typically TRUE or
FALSE. It is commonly used for flag fields or binary conditions.
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
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.
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:
LTRIM(Input_String, [Trim_Characters])
Parameters
The following diagram shows how the SQL LTRIM function affects strings in
the table.
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.
Now let us see some examples of LTRIM function in different use cases to
understand it's working better:
In this example, we will remove the leading white spaces from a string using
SQL LTRIM function.
Query:
Output:
Output
Query:
Output:
Out
put
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
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
Name VARCHAR(45)
);
Now to remove whitespace from this column, we can use the SQL query:
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.
SQL LTRIM is useful inbuilt function which can be used to remove the
whitespaces on left our data in the databases.
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.
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:
UPPER(input_text);
OR
UPPER(column_name);
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.
ID NAME
12@tEsla Elon
X Musk
Microsoft Bill
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:
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:
Output:
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.
Output:
Query:
Output:
Passing a column name to the UPPER() function and Converting it to Capital
Case.
It takes only one parameter and converts the entire string into upper
case.
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.
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.
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;
Let's see some examples of RTRIM function in SQL, and understand it's
working with examples of different use cases.
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
id integer,
name varchar(40));
(1,"kiran "),
Output:
Output of
GFG TABLE.
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.
DELIMITER //
BEGIN
-- Declare a variable
END //
DELIMITER ;
CALL RTRIM_Example();
Output:
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
Syntax:
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.
Query:
products Table:
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:
1 Laptop 800
2 Smartphone 600
3 Tablet 120
5 Monitor 200
Explanation:
We filter it so that it only includes rows with prices bigger than $100.
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:
Departments table:
department department_n
_id ame
101 Sales
102 Marketting
employee_department_info view:
Explanation:
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
Syntax:
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.
1 Kartik 70 math
scienc
Yash 80
2 e
3 Pratik 45 math
Adity scienc
75
4 a e
Prana
48 math
5 v
UPDATE view1
SET Marks=50
where Roll_no in (3,5);
Output:
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.
Query:
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.
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:
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.
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:
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.
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
Key Terms
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
The view sales_report aggregates the total quantity of each product from
the Sales table.
Explanation:
This view calculates the total quantity for each product (product_id) by
summing the quantity values. It simplifies querying the aggregated data.
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.
Output
product_ total_quan
id tity
1 100
2 150
3 100
Explanation:
In PostgreSQL, you can use the ALTER VIEW command to rename a view. This
is the preferred method in PostgreSQL for renaming views directly.
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
We will create a view named it_employees to list all employees who belong
to department 1 (IT department).
Explanation:
This query creates the it_employees view, which retrieves the name of
employees in the IT department (where department_id is 1).
Since we now have the employee view with the new name, we can safely
drop the old view if desired.
4. Verification
To confirm the renaming was successful, we query the newly renamed view
employee.
Output
name
John Doe
Mike
Johnson
Explanation:
Conclusion
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.
Syntax:
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
Query:
Output
Roha 5700
1 Manager HR
n 0
Senior 6000
3 Arpit IT
Developer 0
Query:
Output
Nam Departm
e Position ent
Arya
Developer IT
n
Senior
Arpit IT
Developer
Tara Developer IT
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:
Output
Arya 4500
2 Developer IT
n 0
Senior 6000
3 Arpit IT
Developer 0
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
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:
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.
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
Indexes
Create Index
Drop Index
Show Indexes
Unique Index
SQL Indexes
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.
Must be used wisely as too many indexes can slow down INSERT,
UPDATE and DELETE.
1. Creating an Index
There are 3 main ways to create an index in SQL. Let’s look at them one by
one.
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:
1 101 5 201
2 102 2 202
3 101 3 203
4 103 1 204
5 104 7 205
Example:
Example:
Explanation: This index allows database to quickly filter or join data based
on both product_id and quantity columns with a confirming message.
Syntax:
Example:
Explanation: This ensures no two rows in the Sales table can have same
customer_id.
2. Removing an Index
Syntax:
Example:
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:
Example:
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:
Example:
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
Syntax:
Example:
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.
Syntax:
Key Terms
column1, column2, ...: The columns that the index will be applied to.
Low Null Values: Indexes work best on columns that contain a low
number of NULL values.
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
Query:
CREATE INDEX idx
ON STUDENTS(NAME);
Explanation:
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:
Output
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.
Key Terms
Key Terms
Key Terms
Conclusion
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.
MySQL
MS Access
SQL Server
DB2/Oracle
PostgreSQL
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.
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.
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:
Output
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
Query:
Output
Dropping the
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:
PostgreSQL Verification:
Explanation:
The IF EXISTS clause can be used to conditionally drop the index only if
it exists.
Conclusion
The syntax for the SHOW INDEXES statement varies across different
database management systems. Here are some common examples:
MySQL:
Explanation:
This command displays all the indexes created for a particular table,
providing details such as index name, column names, and more.
PostgreSQL:
Explanation:
PostgreSQL uses the pg_indexes system catalog to store index details. This
query lists all indexes associated with a specific table.
SQL Server:
Explanation:
In SQL Server, this query retrieves information about indexes for a given
table by querying the sys.indexes catalog view.
1. table: The name of the table that has infomation about indexes being
shown.
3. key_name: It tells us the name of the index. The name for primary
key indexes is written as 'PRIMARY'.
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.
8. sub_part: Shows how long the part of columns that are just partly
indexed is. If NOTHING, the whole column is indexed.
10. visible: Shows if the list is seen by the query optimizer (say 'Yes'
if it can be, and not say anything for no).
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.
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.
Output
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.
Conclusion
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.
Syntax:
Key Terms:
table_name: The name of the table where the index will be created.
Query:
Query:
Output:
Explanation:
Query:
Output:
Explanation:
Query:
Output:
Explanation:
Query:
Output:
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.
Query:
Output:
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.
Conclusion
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:
Consider a table called Student where the Roll_No column is the primary
key. This automatically becomes a clustered index.
Roll_N Gend
o Name er Mob_No
femal 98765432
ankita
4 e 10
femal 96754328
anita
3 e 90
a e 01
Explaination:
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.
Key Characteristics:
Query:
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:
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.
Faster for range-based queries Slower for range-based queries but faster
and sorting. for specific lookups.
A table can have only one A table can have multiple non-clustered
clustered index. indexes.
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.
Ideal for range queries and Suitable for optimizing lookups and
sorting. queries on non-primary columns.
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
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 ...);
Types of Subqueries
1. Single-Row Subquery
Example:
2. Multi-Row Subquery
Requires operators that can handle multiple values, such as IN, ANY or
ALL
Example:
3. Correlated Subquery
Executed once for each row of the outer query, making it slower for
large datasets.
Example:
Student Table
ROLL_N PHONE_NUMB
NAME O LOCATION ER
Coimbator
Raj 102 8877665544
e
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
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:
Output
Rav
Salem 8989898989
i
Coimbato
Raj 8877665544
re
Explanation:
Thus, only Ravi and Raj are returned, since they are in section A.
Temp_Students
Meen
202 Delhi 8080805678
a
Query:
Output
ROLL_N PHONE_NUMB
NAME O LOCATION ER
Coimbator
Raj 102 8877665544
e
Sumat Kanchipura
105 8989856868
hi m
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.
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:
Output
ROLL_N PHONE_NUMB
NAME O LOCATION ER
Coimbator
Raj 102 8877665544
e
Sumat Kanchipura
105 8989856868
hi m
Explanation:
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
Sumat Kanchipura
105 8989856868
hi m
Explanation:
The outer query updates the NAME field for students whose location
matches those values.
This example demonstrates using a subquery inside the FROM clause, where
the subquery acts as a temporary (derived) table.
Query:
Output
NAM PHONE_NUMB
E ER
Ra
9988775566
m
Raj 8877665544
Explanation:
The outer query then selects only NAME and PHONE_NUMBER from this
derived table.
We can also use subqueries along with JOIN to connect data across tables.
Query:
Output
Rav
Salem A
i
NAM LOCATIO SECTIO
E N N
Coimbato
Raj A
re
Dynamic & Dependent: Subquery uses values from the outer query.
Syntax:
(SELECT column
FROM table2
Correlated subqueries are often used when you need to filter data based on a
condition that involves comparing values from the outer query.
(SELECT AVG(salary)
FROM employees
WHERE 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.
UPDATE employees e
FROM employees
Explanation:
(SELECT expression
This query deletes employees who do not belong to the 'HR' department by
using a correlated subquery in the NOT EXISTS clause.
FROM employees
WHERE manager_id =
outer.employee_id);
Output
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
FROM departments d
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 (Non-Correlated)
Subquery Correlated Subquery
Performance Considerations
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.
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.
1. STUDENT Table
The STUDENT table stores information about students, including their unique
ID, name, address, phone number and age.
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
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:
This query retrieves the IDs of the courses named 'DSA' or 'DBMS' from the
COURSE table.
Output
C_I
D
C1
C_I
D
C3
The inner query finds the course IDs and the outer query retrieves the
student IDs associated with those courses from the STUDENT_COURSE table
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.
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':
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.
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.
S_NAME
RAM
RAMES
H
SURES
H
Explanation:
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.
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
Output
S_NA
ME
SUJIT
Explanation:
The outer query checks which students have an age greater than at
least one of those ages.
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
Output
S_NAME
(No
rows)
Explanation:
The outer query looks for students whose age is greater than every
one of those ages.
Miscellaneous Topics
Explore advanced and useful SQL concepts to deepen your knowledge
Wildcards Operators
Comments
Trigger
Hosting
Performance Tuning
Stored Procedures
Transactions
Sub Queries
Using Sequences
Auto Increment
Window functions
Cursors
Database Tuning
Dynamic
Regular Expressions
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.
Syntax
Key Terms:
Wildcard
Character Description
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
The % wildcard is used to substitute for zero or more characters. It’s very
flexible and is commonly used for matching partial strings.
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
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
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
Output
Table -3
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:
Output
Table - 4
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:
Output
Table - 5
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:
Output
Table - 6
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
Output
Table - 7
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
Output
Table - 8
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
Output
Table - 9
Conclusion
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.
1. Single-line comments
2. Multi-line comments
3. In-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:
Example
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.
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:
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.
Example
SELECT customer_name,
order_date
FROM orders;
Explanation:
While SQL comments are crucial for code documentation, there are several
best practices to follow when using them:
Conclusion
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.
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:
Pric
CourseName CourseCategory e
500
C PROGRAMMING
0
600
JAVA PROGRAMMING
0
800
PYTHON PROGRAMMING
0
Query:
Explanation:
Syntax:
SELECT (ColumnNames)
FROM (TableName)
UNPIVOT
(AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias)
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
Explanation:
UNPIVOT: When you need to convert column data back to rows, often
after performing a PIVOT operation, for normalization or further
analysis.
Conclusion
SQL Triggers
Syntax:
[before | after]
on [table_name]
END;
In this explanation:
Triggers can be categorized into different types based on the action they are
associated with:
1. DDL Triggers
ON DATABASE
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:
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.
ON LOGON
AS
BEGIN
END;
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.
BEGIN
UPDATE total_scores
SET score = score + :new.grade
END;
This ensures that every time a student's grade is updated, the total score in
the total_scores table is automatically recalculated.
BEGIN
END IF;
END;
The trigger checks if the inserted grade is valid. If not, it throws an error and
prevents the insertion.
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.
FROM sys.triggers
Key Terms
name: The name of the trigger.
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.
We will get various options here. When we choose the Triggers option,
it displays all the triggers available in this table.
SQL triggers can be specified to run BEFORE or AFTER the triggering event.
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
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.
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
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
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
Serverless Hosting
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
Low latency
MySQL
High performance
High security
Fast retrieval
Cost effective
MS SQL Server
High scalability
Easy to use
High security
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.
Cost-effective
Easy to use
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
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.
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.
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:
Efficient:
Inefficient:
Efficient:
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:
Efficient:
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:
Efficient:
Inefficient:
Efficient:
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:
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
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:
Conclusion
Syntax:
Key Terms
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
These are predefined stored procedures provided by the SQL Server for
performing administrative tasks such as database management,
troubleshooting, or system configuration. Examples include:
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.
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.
There are several key reasons why SQL Stored Procedures are widely used in
database management:
Customers Table
Query:
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.
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.
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).
Conclusion
Syntax:
BEGIN TRANSACTION;
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.
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.
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
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
Syntax:
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
Syntax:
Example
Once the savepoint SP2 is released, we can no longer roll back to it.
There are different types of transactions based on their nature and the
specific operations they perform:
SQL Subquery
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 ...);
Types of Subqueries
1. Single-Row Subquery
Example:
2. Multi-Row Subquery
Requires operators that can handle multiple values, such as IN, ANY or
ALL
Example:
3. Correlated Subquery
Executed once for each row of the outer query, making it slower for
large datasets.
Example:
Output: Returns employees earning more than the average salary of their
own department.
Student Table
ROLL_N PHONE_NUMB
NAME O LOCATION ER
Coimbator
Raj 102 8877665544
e
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
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:
Output
NAM LOCATIO PHONE_NUMB
E N ER
Rav
Salem 8989898989
i
Coimbato
Raj 8877665544
re
Explanation:
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.
Temp_Students
Meen
202 Delhi 8080805678
a
Query:
ROLL_N PHONE_NUMB
NAME O LOCATION ER
Coimbator
Raj 102 8877665544
e
Sumat Kanchipura
105 8989856868
hi m
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.
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
Sumat Kanchipura
105 8989856868
hi m
Explanation:
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
Sumat Kanchipura
105 8989856868
hi m
Explanation:
The outer query updates the NAME field for students whose location
matches those values.
This example demonstrates using a subquery inside the FROM clause, where
the subquery acts as a temporary (derived) table.
Query:
Output
NAM PHONE_NUMB
E ER
Ra
9988775566
m
Raj 8877665544
Explanation:
The outer query then selects only NAME and PHONE_NUMBER from this
derived table.
We can also use subqueries along with JOIN to connect data across tables.
Query:
Output
NAM LOCATIO SECTIO
E N N
Rav
Salem A
i
Coimbato
Raj A
re
SQL | SEQUENCES
In this article, we will explain SQL sequences in-depth, explaining how they
work, their advantages, syntax, and real-world use cases.
Syntax:
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.
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.
Query:
CREATE TABLE students
(
ID number(10),
NAME char(20)
);
Output
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.
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.
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.
Conclusion
Example
To insert a new record into students table, we will not specify the value of
Student_ID as it will be added automatically.
Output:
Example
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.
Output:
To change the default starting value we can use ALTER TABLE command as
follows:
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;
Example
To insert a new record into students table, we will not specify the value of
Student_ID as it will be added automatically.
Output:
4. MS Access Auto Increment
Example
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.
AUTOINCREMENT(starting_value, increment_value)
Syntax
Key Terms
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.
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:
Output:
Example 4
Conclusion
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:
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
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
30,00
Deep 25 Sales
0
Pradee 20,00
22 Sales
p 0
Output
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:
Output
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:
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.
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.
Output
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.
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.
Output
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:
Output
Rames 50,00
Finance 0.00
h 0
50,00
Suresh Finance 0.00
0
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.
While SQL window functions are incredibly powerful, there are some common
pitfalls and challenges that users may encounter:
Performing clean-up tasks that can not be done with a single SQL
Query.
SQL offers two main types of cursors, each suited for different scenarios
and depending on how much control we want:
1. Implicit Cursors
Useful Attributes:
Query:
DECLARE
total_rows number;
BEGIN
UPDATE Emp
SET Salary = Salary + 1500;
total_rows := SQL%ROWCOUNT;
Output
5 Emp selected
PL/SQL procedure successfully completed.
Explanation:
2. Explicit Cursors
Usage: Used for fetching data row-by-row with complete control over the
cursor lifecycle.
Query:
BEGIN
-- Open the cursor
OPEN emp_cursor;
Output
Output
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:
Example:
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.
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.
To retrieve data from the cursor, use the FETCH statement. SQL provides six
methods to access data:
Mode Description
ABSOLUTE
Fetches the nth row
n
Syntax:
Example:
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.
Syntax:
DEALLOCATE cursor_name
Example:
DEALLOCATE s1
BEGIN
FOR emp_rec IN SELECT * FROM emp LOOP
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.ename);
END LOOP;
END;
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.
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.
Manual (requires
Creation Automatic
declaration)
Complex, row-by-row
Use Case Simple DML operations
operations
Despite their limitations, SQL cursors provide several benefits in specific use
cases:
While cursors are helpful in certain scenarios, they come with notable
limitations, and alternatives should be explored whenever possible:
CTE in SQL
Uses of CTEs
Syntax
WITH cte_name AS (
SELECT query
)
SELECT *
FROM cte_name;
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.
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
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 main query references this CTE to retrieve the average salary for
each department.
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.
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.
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:
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.
OPTION(MAXRECURSION 50);
This limits the recursion to 50 levels. If the recursion exceeds this limit, SQL
Server will stop and return an error.
CTE Vs Subqueries
CTE Subquery
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.
In SQL, there are three primary functions for working with regular
expressions:
1. REGEXP_LIKE
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
Syntax
Example:
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
Syntax
Example:
To extract the domain name from the email field in the users table:
Output
domain
@gmail
@outlook
@compa
ny
@yahoo
@exampl
e
Explanation:
Acts as a
logical OR
` ` `cat
between
patterns.
Matches scatter b
\B Matches a non-word boundary. \Bcat
ut not cat
^[A-Za-z0-9._%
+-]+@[A-Za- Validates an email [email protected] Valid email
z0-9.-]+\\.[A- address. om addresses
Za-z]{2,}$
Matches a URL
https://
https?://[^ ]+ starting URLs
example.com/
with http or https.
Matches
^[A-Za-z0-9]+ abc123, xyz7
alphanumeric User123
$ 89
strings.
Here’s how regular expressions can solve common data processing tasks in
SQL:
Query:
Explanation:
SELECT email
FROM users
WHERE REGEXP_LIKE(email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]
{2,}$');
Explanation:
Explanation:
Find all product names in the products table that contain digits:
SELECT product_name
FROM products
WHERE REGEXP_LIKE(product_name, '\d');
Explanation:
Explanation:
^[^.]+: Matches all characters from the start of the string up to the
first . (dot).
SELECT record_id
FROM data_table
WHERE REGEXP_LIKE(field_name, '^[0-9]+$');
Explanation:
Conclusion