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

Structured Query Languages SQL

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Query Language (DQL), Data Control Language (DCL), and Transaction Control Language (TCL). SQL allows users to perform operations such as querying, updating, and managing permissions on the data stored in relational databases.

Uploaded by

patel.keni1993
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Structured Query Languages SQL

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Query Language (DQL), Data Control Language (DCL), and Transaction Control Language (TCL). SQL allows users to perform operations such as querying, updating, and managing permissions on the data stored in relational databases.

Uploaded by

patel.keni1993
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Structured Query Languages (SQL)

Introduction to Structured Query Language


(SQL)
Structured Query Language (SQL)
Structured Query Language is a standard Database language that is used to
create, maintain, and retrieve the relational database. In this article, we will
discuss this in detail about SQL. Following are some interesting facts about
SQL. Let’s focus on that.
SQL is case insensitive. But it is a recommended practice to use keywords (like
SELECT, UPDATE, CREATE, etc.) in capital letters and use user-defined things
(like table name, column name, etc.) in small letters.
We can write comments in SQL using “–” (double hyphen) at the beginning of
any line. SQL is the programming language for relational databases (explained
below) like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-
relational databases (also called NoSQL) databases like MongoDB,
DynamoDB, etc. do not use SQL.
Although there is an ISO standard for SQL, most of the implementations
slightly vary in syntax. So we may encounter queries that work in SQL Server
but do not work in MySQL.
What is Relational Database?
A relational database means the data is stored as well as retrieved in the form
of relations (tables). Table 1 shows the relational database with only one
relation called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE, and AGE of students.
STUDENT Table
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

Important Terminologies
These are some important terminologies that are used in terms of relation.
 Attribute:Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME etc.
 Tuple:Each row in the relation is known as tuple. The above relation
contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18
 Degree:The number of attributes in the relation is known as degree
of the relation. The STUDENT relation defined above has degree 5.
 Cardinality:The number of tuples in a relation is known as
cardinality. The STUDENTrelation defined above has cardinality 4.
 Column:Column represents the set of values for a particular
attribute. The column ROLL_NO is extracted from relation STUDENT.
ROLL_NO

How Queries can be Categorized in Relational


Database?
The queries to deal with relational database can be categorized as:
 Data Definition Language:It is used to define the structure of the
database. e.g; CREATE TABLE, ADD COLUMN, DROP COLUMN and
so on.
 Data Manipulation Language:It is used to manipulate data in the
relations. e.g.; INSERT, DELETE, UPDATE and so on.
 Data Query Language:It is used to extract the data from the
relations. e.g.; SELECT So first we will consider the Data Query
Language. A generic query to retrieve data from a relational database
is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to
retrieve from a relational database. The statements written inside [] are
optional. We will look at the possible query combination on relation shown in
Table 1.
Different Query Combinations
Case 1: If we want to retrieve attributes ROLL_NO and NAMEof all students,
the query will be:
SELECT ROLL_NO, NAME FROM STUDENT;

ROLL_NO NAME

1 RAM

2 RAMESH

3 SUJIT

4 SURESH

Case 2: If we want to retrieve ROLL_NO and NAME of the students


whose ROLL_NO is greater than 2, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME

3 SUJIT

4 SURESH

CASE 3: If we want to retrieve all attributes of students, we can write * in


place of writing all attributes as:
SELECT * FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18


CASE 4: If we want to represent the relation in ascending order by AGE, we
can use ORDER BY clause as:
SELECT * FROM STUDENT ORDER BY AGE;

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

4 SURESH DELHI 9156768971 18

3 SUJIT ROHTAK 9156253131 20

Note:
ORDER BY AGEis equivalent to ORDER BY AGE ASC.
If we want to retrieve the results in descending order of AGE, we can
use ORDER BY AGE DESC.

CASE 5: If we want to retrieve distinct values of an attribute or group of


attribute, DISTINCT is used as in:
SELECT DISTINCT ADDRESS FROM STUDENT;

ADDRESS

DELHI

GURGAON

ROHTAK

If DISTINCT is not used, DELHI will be repeated twice in result set. Before
understanding GROUP BY and HAVING, we need to understand aggregations
functions in SQL.
Aggregation Functions
Aggregation functions are used to perform mathematical operations on data
values of a relation. Some of the common aggregation functions used in SQL
are:
 COUNT: Count function is used to count the number of rows in a
relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;

COUNT(PHONE)

 SUM: SUM function is used to add the values of an attribute in a


relation. e.g;
SELECT SUM(AGE) FROM STUDENT;

SUM(AGE)

74

In the same way, MIN, MAX and AVG can be used. As we have seen above, all
aggregation functions return only 1 row. AVERAGE: It gives the average values
of the tupples. It is also defined as sum divided by count values.
Syntax:
AVG(attributename)
OR
SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
 MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:
MAX(attributename)
 MINIMUM:It extracts the minimum value amongst the set of all the
tupples.
Syntax:
MIN(attributename)
 GROUP BY:Group by is used to group the tuples of a relation based
on an attribute or group of attribute. It is always combined with
aggregation function which is computed on group. e.g.;
SELECT ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);

In this query, SUM(AGE) will be computed but not for entire table but for each
address. i.e.; sum of AGE for address DELHI(18+18=36) and similarly for other
address as well. The output is:
ADDRESS SUM(AGE)

DELHI 36

GURGAON 18

ROHTAK 20

If we try to execute the query given below, it will result in error because
although we have computed SUM(AGE) for each address, there are more than
1 ROLL_NO for each address we have grouped. So it can’t be displayed in
result set. We need to use aggregate functions on columns after SELECT
statement to make sense of the resulting set whenever we are using GROUP
BY.
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);

NOTE:
An attribute which is not a part of GROUP BY clause can’t be used for
selection.
Any attribute which is part of GROUP BY CLAUSE can be used for
selection but it is not mandatory.
But we could use attributes which are not a part of the GROUP BY clause
in an aggregate function.

Conclusion
SQL is a standard language used to manage data in relational databases. SQL
is mainly divided into four main categories: Data definition language, data
manipulation language, transaction control language, and data query language
and SQL is a powerful language that can be used to carry out a wide range of
operations like insert, delete and update.

Parts of SQL, Data Manipulation Language in


SQL, Data Definition in SQL

SQL Commands | DDL, DQL, DML, DCL and TCL


Commands
SQL commands are crucial for managing databases effectively. These
commands are divided into categories such as Data Definition Language (DDL),
Data Manipulation Language (DML), Data Control Language (DCL), Data Query
Language (DQL), and Transaction Control Language (TCL).
In this article, we will explain the different types of SQL commands,
including DDL, DML, DCL, DQL, and TCL. These SQL sublanguages serve
specific purposes and are important for effective database management.
What are SQL Commands?
SQL commands are the fundamental building blocks for communicating with
a database management system (DBMS). It is used to interact with the
database with some operations. It is also used to perform specific
tasks, functions, and queries of data. SQL can perform various tasks like
creating a table, adding data to tables, dropping the table, modifying the table,
set permission for users.
SQL Commands are mainly categorized into five categories:
 DDL – Data Definition Language
 DQL – Data Query Language
 DML – Data Manipulation Language
 DCL – Data Control Language
 TCL – Transaction Control Language

1. DDL – Data Definition Language


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

Create database or its


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

Delete objects from the


DROP DROP TABLE table_name;
database

Alter the structure of the ALTER TABLE table_name ADD


ALTER COLUMN column_name data_type;
database

Remove all records from


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

Add comments to the COMMENT 'comment_text' ON


COMMENT TABLE table_name;
data dictionary

Rename an object RENAME TABLE old_table_name


RENAME TO new_table_name;
existing in the database

Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
In this example, a new table called employees is created with columns for
employee ID, first name, last name, and hire date.
2. DQL – Data Query Language
DQL statements are used for performing queries on the data within schema
objects. The purpose of the DQL Command is to get some schema
relation based on the query passed to it. This command allows getting the data
out of the database to perform operations with it. When a SELECT is fired
against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program.
DQL Command
Command Description Syntax

It is used to retrieve data SELECT column1, column2, ...FROM


SELECT table_name WHERE condition;
from the database

Example:
SELECT first_name, last_name, hire_date
FROM employees
WHERE department = 'Sales'
ORDER BY hire_date DESC;
This query retrieves employees’ first and last names, along with their hire dates,
from the employees table, specifically for those in the ‘Sales’ department,
sorted by hire date.
3. DML – Data Manipulation Language
The SQL commands that deal with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes
most of the SQL statements. It is the component of the SQL statement that
controls access to data and to the database. Basically, DCL statements are
grouped with DML statements.
Common DML Commands
Command Description Syntax

Insert data into a INSERT INTO table_name (column1,


INSERT column2, ...) VALUES (value1, value2,
table ...);

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

Delete records
DELETE from a database DELETE FROM table_name WHERE condition;
table

Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency

Call a PL/SQL or
CALL JAVA CALL procedure_name(arguments);
subprogram
Command Description Syntax

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

Example:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Jane', 'Smith', 'HR');
This query inserts a new record into the employees table with the first name
‘Jane’, last name ‘Smith’, and department ‘HR’.
4. DCL – Data Control Language
DCL (Data Control Language) includes commands such
as GRANT and REVOKE which mainly deal with the rights, permissions, and
other controls of the database system. These commands are used to control
access to data in the database by granting or revoking permissions.
Common DCL Commands
Command Description Syntax

Assigns new privileges


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

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

Example of DCL
GRANT SELECT, UPDATE ON employees TO user_name;
This command grants the user user_name the permissions to select and
update records in the employees table.
5. TCL – Transaction Control Language
Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group are
successfully completed. If any of the tasks fail, the transaction fails. Therefore,
a transaction has only two results: success or failure. We can explore more
about transactions here.
Common TCL Commands
Command Description Syntax

BEGIN BEGIN TRANSACTION


Starts a new transaction [transaction_name];
TRANSACTION

Saves all changes made


COMMIT COMMIT;
during the transaction

Undoes all changes made


ROLLBACK ROLLBACK;
during the transaction

Creates a savepoint within


SAVEPOINT SAVEPOINT savepoint_name;
the current transaction

Example:
BEGIN TRANSACTION;
UPDATE employees SET department = 'Marketing' WHERE department =
'Sales';
SAVEPOINT before_update;
UPDATE employees SET department = 'IT' WHERE department = 'HR';
ROLLBACK TO SAVEPOINT before_update;
COMMIT;
In this example, a transaction is started, changes are made, and a savepoint is
set. If needed, the transaction can be rolled back to the savepoint before being
committed.
Most Important SQL Commands
There are also a few other SQL Commands we often rely on when
writing powerful queries. While they don’t fit neatly into the five main
categories, they’re absolutely essential for working with data effectively.
Command Description

SELECT Retrieves data from one or more tables.

INSERT Adds new rows (records) to a table.

UPDATE Modifies existing data in a table.


Command Description

DELETE Removes specific rows from a table.

CREATE TABLE Creates a new table in the database.

Modifies the structure of an existing table (e.g., add or


ALTER TABLE
remove columns).

DROP TABLE Permanently deletes a table and its data.

TRUNCATE Removes all rows from a table but keeps its structure
TABLE intact.

WHERE Filters records based on a condition.

ORDER BY Sorts the result set in ascending or descending order.

Groups rows that have the same values in specified


GROUP BY
columns.

HAVING Filters grouped data (used with GROUP BY).

Combines rows from two or more tables based on a related


JOIN
column.

DISTINCT Removes duplicate values from the result set.

IN / BETWEEN /
Used for advanced filtering conditions.
LIKE

UNION Combines the result of two or more SELECT queries.

GRANT Gives user privileges or permissions.

REVOKE Removes user privileges.

COMMIT Saves all changes made in the current transaction.


Command Description

ROLLBACK Undoes changes if something goes wrong in a transaction.

SAVEPOINT Sets a point in a transaction to roll back to if needed.

Conclusion
SQL commands such as DDL, DML, DCL, DQL, and TCL are foundational for
effective database management. From creating and modifying tables
with DDL commands to managing transactions with TCL commands in SQL,
understanding each type of command enhances our database skills. Whether
we are manipulating data, or managing data, SQL provides all sets of tools.
Now, with this detailed guide, we hope you have gained a deep understanding
of SQL commands, their categories, and syntax with examples.

Joins in SQL
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in
relational databases. Joins allow efficient data retrieval, which is essential for
generating meaningful observations and solving complex business queries.
Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT
JOIN, FULL JOIN, and NATURAL JOIN, is critical for working with relational
databases.
In this article, we will cover the different types of SQL joins, including INNER
JOIN, LEFT OUTER JOIN, RIGHT JOIN, FULL JOIN, and NATURAL JOIN. Each
join type will be explained with examples, syntax, and practical use cases to
help us understand when and how to use these joins effectively.
What is SQL Join?
An SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them. It can access data from
multiple tables simultaneously using common key values shared across
different tables. We can use SQL JOIN with multiple tables. It can also be
paired with other clauses, the most popular use will be using JOIN with WHERE
clause to filter data retrieval.
Before diving into the specifics, let’s visualize how each join type operates:
 INNER JOIN: Returns only the rows where there is a match in both
tables.
 LEFT JOIN (LEFT OUTER JOIN): Returns all rows from the left table,
and the matched rows from the right table. If there’s no match, NULL
values are returned for columns from the right table.
 RIGHT JOIN (RIGHT OUTER JOIN): Returns all rows from the right
table, and the matched rows from the left table. If there’s no match,
NULL values are returned for columns from the left table.
 FULL JOIN (FULL OUTER JOIN): Returns all rows when there is a
match in one of the tables. If there’s no match, NULL values are
returned for columns from the table without a match.
1. SQL INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining all
rows from both the tables where the condition satisfies i.e value of the
common field will be the same.
Syntax
SELECT table1.column1,table1.column2,table2.column1,…. FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.

Example of INNER JOIN


Consider the two tables, Student and StudentCourse, which share a common
column ROLL_NO. Using SQL JOINS, we can combine data from these tables
based on their relationship, allowing us to retrieve meaningful information like
student details along with their enrolled courses.
Student Table
StudentCourse Table

Let’s look at the example of INNER JOIN clause, and understand it’s working.
This query will show the names and age of students enrolled in different
courses.
Query:
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output
2. SQL LEFT JOIN
A LEFT JOIN returns all rows from the left table, along with matching rows
from the right table. If there is no match, NULL values are returned for columns
from the right table. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax
SELECT table1.column1,table1.column2,table2.column1,….
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the
same.

LEFT JOIN Example


In this example, the LEFT JOIN retrieves all rows from the Student table and
the matching rows from the StudentCourse table based on
the ROLL_NO column.
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output

3. SQL RIGHT JOIN


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

4. SQL FULL JOIN


FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both tables.
For the rows for which there is no matching, the result-set will contain NULL
values.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Key Terms
 table1: First table.
 table2: Second table
 matching_column: Column common to both the tables.

FULL JOIN Example


This example demonstrates the use of a FULL JOIN, which combines the results
of both LEFT JOIN and RIGHT JOIN. The query retrieves all rows from
the Student and StudentCourse tables. If a record in one table does not have
a matching record in the other table, the result set will include that record
with NULL values for the missing fields
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output
NAME COURSE_ID

HARSH 1

PRATIK 2
NAME COURSE_ID

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4

5. SQL Natural Join (?)


Natural join can join tables based on the common columns in the tables being
joined. A natural join returns all rows by matching values in common columns
having same name and data type of columns and that column should be
present in both tables.
 Both table must have at least one common column with same
column name and same data type.
 The two table are joined using Cross join.
 DBMS will look for a common column with same name and data
type. Tuples having exactly same values in common columns are
kept in result.
Natural join Example
Look at the two tables below- Employee and Department
Employee

Emp_id Emp_name Dept_id

1 Ram 10
Employee

2 Jon 30

3 Bob 50

Department

Dept_id Dept_name

10 IT

30 HR

40 TIS

Problem: Find all Employees and their respective departments.


Solution Query: (Employee) ? (Department)
Emp_id Emp_name Dept_id Dept_id Dept_name

1 Ram 10 10 IT

2 Jon 30 30 HR

Employee data Department data

Conclusion
SQL joins are essential tools for anyone working with relational databases.
Understanding the different types of joins in SQL, like INNER JOIN, LEFT
OUTER JOIN, RIGHT JOIN, and FULL JOIN, allows us to combine and query
data effectively. With the examples and syntax covered here, we should feel
confident applying these SQL join types to our data to retrieve meaningful
observations and manage complex queries with ease. Use these SQL join
techniques to streamline our data handling and enhance our SQL skills.

Inner VS Outer Join


Inner Join vs Outer Join
Inner Join and Outer Join are the types of join. The inner join has the work to
return the common rows between the two tables, whereas the Outer Join has
the work of returning the work of the inner join in addition to the rows that are
not matched.
Let’s discuss both of them in detail in this article. Before moving ahead, let’s
discuss what is Join in SQL.
In a relational database management system (RDBMS), there are different
types of joins that can be used to combine data from two or more tables in a
database. The two most common types of joins are Inner Join and Outer Join.
What is Join in SQL?
SQL Joins are simply a way to combine data from two or more tables based on
a common field between them. SQL joins are of two types. We will discuss the
types of SQL in detail.
 Inner Join
 Outer Join
Let’s proceed with an example demonstrating the process of Inner Join and
Outer Join.
Student Table
EnrollNo StudentName Address

1001 geek1 geeksquiz1

1002 geek2 geeksquiz2

1003 geek3 geeksquiz3

1004 geek4 geeksquiz4

StudentCourse Table
CourseID EnrollNo

1 1001

2 1001

3 1001

1 1002
CourseID EnrollNo

2 1003

Inner Join/Simple Join


In an INNER join, it allows retrieving data from two tables with the same ID.
An Inner Join returns only the matching rows between the two tables based on
a specified condition. It combines data from two tables based on a common
column between them, which is specified using the ON keyword in SQL. Only
the rows that meet the join condition from both tables are returned. If a row in
one table does not have a matching row in the other table, that row will not be
included in the result set.

Inner Join

Syntax:
SELECT COLUMN1, COLUMN2 FROM
[TABLE 1] INNER JOIN [TABLE 2]
ON Condition;
The following is a join query that shows the names of students enrolled in
different courses.
Query:
SELECT StudentCourse.CourseID,Student.StudentName
FROM Student
INNER JOIN StudentCourse
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID;
Note: Inner is optional above. Simple JOIN is also considered as INNER JOIN
The above query would produce the following result.
CourseID StudentName

1 geek1
CourseID StudentName

1 geek2

2 geek1

2 geek3

3 geek1

Example:
For example, let’s say we have two tables, Table1 and Table2, with the
following data:
Table 1
ID Name

1 John

2 Sarah

3 David

Table 2
ID Address

1 123 Main St.

2 456 Elm St.

4 789 Oak St.

If we perform an Inner Join on these tables using the ID column, the result set
would only include the matching rows from both tables, which are the rows
with ID values of 1 and 2:
Query:
SELECT Table1.ID,
Table 1. Name, Table 2.Address
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.ID
Output:
ID Name Address

1 John 123 Main St.

2 Sarah 456 Elm St.

How To Use Inner Join?


Inner Join is basically performed by just selecting the records having the
common values or the matching values in both tables. In case of no common
values, no data is shown in the output.
Syntax:
Select Table1.Col_Name, Table2.Col_Name....
From Table1
Inner Join Table2
on Table1.Common_Col = Table2.Common_Col;
If there are 3 Tables present in the database, then the Inner Join works as
follows:
Select Table1.Col_Name, Table2.Col_Name, Table3.Col_Name....
From ((Table1
Inner Join Table2
on Table1.Common_Col = Table2.Common_Col)
Inner Join Table3
on Table1.Common_Col = Table3.Common_Col);
Advantages of Inner Join
 Reduced Data Duplication: Inner joins only return rows that have
matching values in both tables being joined, which can reduce the
amount of duplicate data returned in the result set.
 Efficient Query Execution: Since inner joins only involve rows that
match in both tables, they can be more efficient in terms of query
execution time compared to outer joins.
 Data Accuracy: Inner joins only return rows that have matching
values in both tables, which can improve data accuracy by excluding
irrelevant or mismatched data.
Disadvantages of Inner Join
 Data Loss: Since inner joins only return rows that have matching
values in both tables, some data may be lost if there are no matching
values.
 Query Complexity: Inner joins can become complex and difficult to
write and understand when working with multiple tables.
 Overlapping Data: In some cases, inner joins may return overlapping
data that needs not to be duplicated in post-processing.
Outer Join
An Outer Join returns all the rows from one table and matching rows from the
other table based on a specified condition. It combines data from two tables
based on a common column between them, which is also specified using the
ON keyword in SQL. In addition to the matching rows, it also includes rows from
one table that do not have matching rows in the other table.
Outer Join is of three types:
1. Left outer join
2. Right outer join
3. Full Join
1. Left Outer join
Left Outer Join returns all rows of a table on the left side of the join. For the
rows for which there is no matching row on the right side, the result contains
NULL on the right side.
Left Outer Join returns all the rows from the left table and matching rows from
the right table. If a row in the left table does not have a matching row in the
right table, the result set will include NULL values for the columns in the right
table.

Left Outer Join

Syntax:
SELECT T1.C1, T2.C2
FROM TABLE T1
LEFT JOIN TABLE T2
ON T1.C1= T2.C1;
Query:
SELECT Student.StudentName,StudentCourse.CourseID
FROM Student
LEFT OUTER JOIN StudentCourse
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID;
Note: OUTER is optional above. Simple LEFT JOIN is also considered as LEFT
OUTER JOIN
StudentName CourseID

geek4 NULL

geek2 1

geek1 1

geek1 2

geek3 2

geek1 3

2. Right Outer Join


Right Outer Join is similar to Left Outer Join (Right replaces Left everywhere).
Right Outer Join returns all the rows from the right table and matching rows
from the left table. If a row in the right table does not have a matching row in
the left table, the result set will include NULL values for the columns in the left
table.

Right Outer Join

Syntax:
SELECT T1.C1, T2.C2
FROM TABLE T1
RIGHT JOIN TABLE T2
ON T1.C1= T2.C1;
Example:
Table Record
Roll_Number Name Age

1 Harsh 18
Roll_Number Name Age

2 Ankesh 19

3 Rupesh 18

4 Vaibhav 15

5 Naveen 13

6 Shubham 15

7 Ankit 19

8 Bhupesh 18

Table Course
Course_ID Roll_Number

1 1

2 2

2 3

3 4

1 5

4 9

5 10

4 11

Query:
SELECT Record.NAME,Course.COURSE_ID
FROM Record
RIGHT JOIN Course
ON Course.Roll_Number = Record.Roll_Number;
Output:
Name Course_ID

Harsh 1

Ankesh 2

Rupesh 2

Vaibhav 3

Naveen 1

NULL 4

NULL 5

NULL 4

3. Full Outer Join


Full Outer Join contains the results of both the Left and Right outer joins. It is
also known as cross-join. It will provide a mixture of two tables.
Full Outer Join returns all the rows from both tables, including matching and
non-matching rows. If a row in one table does not have a matching row in the
other table, the result set will include NULL values for the columns in the table
that do not have a match.

Full Outer Join

Syntax:
SELECT * FROM T1
CROSS-JOIN T2;
Query:
SELECT Record.NAME,Course.COURSE_ID
FROM Record
FULL JOIN Course
ON Course.Roll_Number = Record.Roll_Number;
Output:
Name Course_ID

Harsh 1

Ankesh 2

Rupesh 2

Vaibhav 3

Naveen 1

Shubham NULL

Ankit NULL

Bhupesh NULL

NULL 4

NULL 5

NULL 4

How To Use Outer Join?


Outer Join is performed by the selection of the records from all the tables given
there. Left Outer Join works by selecting all records from the left table and
matching records from the right table. Similarly, Right Outer Join works by
selecting all records from the right table and matching records from the left
table and the Full Outer Join returns all records if a match occurs in the left or
the right table.
Advantages of Outer Join
 Increased Data Retrieval: Outer joins can retrieve more data than
inner joins since they include non-matching rows in the result set.
 Data Integrity: Outer joins can help maintain data integrity by
ensuring that all records in the primary table are returned, even if
there are no corresponding records in the secondary table.
 Data Analysis: Outer joins can be useful for data analysis, especially
when exploring relationships between data sets and identifying
trends and patterns.
Disadvantages of Outer Join
 Slow Query Execution: Outer joins can be slower to execute than
inner joins, especially when dealing with large data sets.
 Data Duplication: Outer joins can return duplicate data when the
secondary table has multiple matching records.
 Data Quality: Outer joins may return inaccurate or incomplete data if
the tables being joined have incomplete or inconsistent data.
Inner Join vs Outer Join (Difference Table)
Feature Inner Join Outer Join

Returns rows with It is directly opposite of Inner join


matching values in both returns rows but return all of them
Defination tables by filtering out. including the unmatched also.

when we need all data without


Used when we want
concerning about match and
matching data.
Use cases unmatched.

Three different Types: Left Outer Join,


Single Type.
Types Right Outer Join, Full Outer Join.

Only the common data All data from one or both tables, with
Example between one or more giving NULLs for non-matching rows
Result tables. or the unmatched ones.

Conclusion
In SQL, The selection between Inner vs Outer is what are requirements of our
scenario including the data we are using in. A inner join is used when we need
to use filtering data which have matching values from both tables, ensuring
related data must be come up as result. Whereas, Outer Join is used when we
need to retain all records from both the tables without considering the matching
records overheads. Generally, Inner Joins are faster than the Outer Join as they
only retrieve the matching data. Understanding the Inner Join and Outer Join
makes a SQL data administrator a robust database manager to retain and
retrieve data effectively and quickly.
Having Vs Where Clause
Having vs Where Clause in SQL
In SQL, filtering data is important for extracting meaningful insights from large
datasets. While both the WHERE and HAVING clauses allow us to filter data,
they serve distinct purposes and operate at different stages of the query
execution process. Understanding the difference between these clauses is key
to writing efficient SQL queries.
In this article, we will explain the fundamental difference between
the WHERE and HAVING clauses, provides practical examples, and discuss
when to use each clause. By the end of this article, we will have a clear
understanding of how to use WHERE and HAVING for more effective data
filtering in SQL.
Difference Between HAVING and WHERE Clause in SQL
Here’s a table highlighting the key differences between
the WHERE and HAVING clauses in SQL:
Criteria WHERE Clause HAVING Clause

Filters rows before


Purpose Filters rows after aggregation.
aggregation.

Works with Works with grouped or aggregated


Used With
individual rows. data.

Columns in the table Aggregated results


Applicable To
(individual records). (e.g., SUM(), COUNT()).

Stage of
Filters data
Query Filters data after GROUP BY.
before GROUP BY.
Execution

Aggregate Cannot be used with


Can be used with aggregate functions.
Functions aggregate functions.

Generally more
Can be less efficient, as it filters after
Efficiency efficient, as it filters
aggregation.
data earlier.
Criteria WHERE Clause HAVING Clause

Example HAVING
WHERE column_name
aggregate_function(column_name) >
Usage = value
value

Order in Appears
Appears after GROUP BY.
Query before GROUP BY.

What is the WHERE Clause in SQL?


The WHERE clause is used to filter records before
any grouping or aggregation is done. It operates on individual rows and
applies conditions to the raw data. We can use WHERE to filter out rows that
don’t meet our criteria, such as filtering out customers with sales below a
certain amount, or employees from a specific department.
Syntax:
SELECT column1, column2
FROM table_name
WHERE condition;

What is the HAVING Clause in SQL?


The HAVING clause, on the other hand, is used to filter records after the data
has been grouped or aggregated. It works on aggregated data and is often
used in conjunction with the GROUP BY clause to filter out groups based
on aggregate functions like SUM(), AVG(), COUNT(), etc.
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;

Example 1: Using WHERE Clause for Row-Level


Filtering
Consider the following table Marks, which contains student names, their
respective courses, and the scores they achieved. This example demonstrates
how the WHERE clause can filter data at the individual row level, before
any grouping or aggregation takes place.
Using Where Clause

To select students with a score greater than or equal to 40, we can use
the WHERE clause. This query filters rows before any aggregation, selecting
only students with scores greater than or equal to 40.
Query:
SELECT Student, Score
FROM Marks
WHERE Score >= 40;
Output
Student Score

a 40

a 50

b 60

d 70

e 80

Example 2: Using HAVING Clause for Aggregated Data


Filtering
Now, suppose you want to calculate the total score of each student and only
show students whose total score is greater than 70. We can use
the HAVING clause:
Query:
SELECT Student, SUM(Score) AS Total
FROM Marks
GROUP BY Student
HAVING Total > 70;
Output
Student Total

a 90

e 80

Explanation:
Here, we are using HAVING to filter groups of students after summing their
scores. This is because HAVING works on aggregated data,
whereas WHERE cannot be used for filtering after aggregation.
Conclusion
The WHERE and HAVING clauses in SQL are both used for filtering data, but
they work at different stages in the query execution process. WHERE filters
individual rows before aggregation, while HAVING filters groups after
aggregation. Understanding when to use each clause is essential for writing
effective and efficient SQL queries. By
using WHERE and HAVING appropriately, we can refine our data retrieval
process and gain more precise insights from our database.

Database Objects
Database Objects in DBMS
A database object is any defined object in a database that is used to store or
reference data.Anything which we make from create command is known as
Database Object.It can be used to hold and manipulate the data.Some of the
examples of database objects are : view, sequence, indexes, etc.
 Table – Basic unit of storage; composed rows and columns
 View – Logically represents subsets of data from one or more tables
 Sequence – Generates primary key values
 Index – Improves the performance of some queries
 Synonym – Alternative name for an object
Different database Objects :
1. Table – This database object is used to create a table in database.
Syntax :
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);

Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));

Output :
DESCRIBE dept;

2. View – This database object is used to create a view in database.A


view is a logical table based on a table or another view. A view
contains no data of its own but is like a window through which data
from tables can be viewed or changed. The tables on which a view is
based are called base tables. The view is stored as a SELECT
statement in the data dictionary.
Syntax :
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT
constraint]]
[WITH READ ONLY [CONSTRAINT
constraint]];

Example :
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;

Output :
SELECT *
FROM salvu50;

3. Sequence – This database object is used to create a sequence in


database.A sequence is a user created database object that can be
shared by multiple users to generate unique integers. A typical usage
for sequences is to create a primary key value, which must be unique
for each row.The sequence is generated and incremented (or
decremented) by an internal Oracle routine.
Syntax :
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

Example :
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

Check if sequence is created by :


SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;

4. Index – This database object is used to create a indexes in


database.An Oracle server index is a schema object that can speed
up the retrieval of rows by using a pointer.Indexes can be created
explicitly or automatically. If you do not have an index on the column,
then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its
purpose is to reduce the necessity of disk I/O by using an indexed
path to locate data quickly. The index is used and maintained
automatically by the Oracle server. Once an index is created, no
direct activity is required by the user.Indexes are logically and
physically independent of the table they index. This means that they
can be created or dropped at any time and have no effect on the base
tables or other indexes.
Syntax :
CREATE INDEX index
ON table (column[, column]...);
Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);

5. Synonym – This database object is used to create a indexes in


database.It simplify access to objects by creating a synonym(another
name for an object). With synonyms, you can Ease referring to a table
owned by another user and shorten lengthy object names.To refer to
a table owned by another user, you need to prefix the table name
with the name of the user who created it followed by a period.
Creating a synonym eliminates the need to qualify the object name
with the schema and provides you with an alternative name for a
table, view, sequence,procedure, or other objects. This method can be
especially useful with lengthy object names, such as views.
In the syntax:
PUBLIC : creates a synonym accessible to all users
synonym : is the name of the synonym to be created
object : identifies the object for which the synonym is created
Syntax :
CREATE [PUBLIC] SYNONYM synonym FOR object;

Example :
CREATE SYNONYM d_sum FOR dept_sum_vu;

Nested Queries in SQL


Nested queries, also known as subqueries, are an essential tool in SQL for
performing complex data retrieval tasks. They allow us to embed one query
within another, enabling us to filter, aggregate, and perform sophisticated
calculations. Whether we’re handling large datasets or performing advanced
analytics, nested queries can greatly enhance the efficiency and flexibility of
our SQL queries.
What Are Nested Queries in SQL?
A nested query (also called a subquery) is a query embedded within another
SQL query. The result of the inner query is used by the outer query to perform
further operations. Nested queries are commonly used
for performing calculations, filtering data, or joining datasets indirectly
without explicitly using joins
Key Characteristics of Nested Queries
 The inner query runs first, providing data for the outer query.
 The output query uses the results of the inner query
for comparison or as input.
 Nested queries are particularly useful for breaking down complex
problems into smaller, manageable parts, making it easier to retrieve
specific results from large datasets.
To better understand nested queries, we will use the following sample
tables: STUDENT, COURSE, and STUDENT_COURSE. These tables simulate
a real-world scenario of students, courses, and their enrollment details, which
will be used in the examples below.
1. STUDENT Table
The STUDENT table stores information about students, including their unique
ID, name, address, phone number, and age.

STUDENT Table

2. COURSE Table
The STUDENT_COURSE table maps students to the courses they have
enrolled in. It uses the student and course IDs as foreign keys.

COURSE Table

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

Student_Course Table

Types of Nested Queries in SQL


There are two primary types of nested queries in SQL, Independent Nested
Queries and Correlated Nested Queries. Each type has its own use case and
benefits depending on the complexity of the task at hand.
Independent Nested Queries
In an independent nested query, the execution of the inner query
is independent of the outer query. The inner query runs first, and its result is
used directly by the outer query. Operators like IN, NOT IN, ANY, and ALL are
commonly used with independent nested query.
Example 1: Using IN
In this Example we will find the S_IDs of students who are enrolled in the
courses ‘DSA’ or ‘DBMS’. We can break the query into two parts:
Step 1: Find the C_IDs of the courses:
This query retrieves the IDs of the courses named ‘DSA’ or ‘DBMS’ from
the COURSE table.
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS');
Output
C_ID

C1

C3

Step 2: Use the result of Step 1 to find the corresponding S_IDs:


The inner query finds the course IDs, and the outer query retrieves the student
IDs associated with those courses from the STUDENT_COURSE table
SELECT S_ID FROM STUDENT_COURSE WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
);
Output
S_ID

S1

S2

S4

Explanation: In this example, the inner query retrieves the C_IDs of the courses
‘DSA’ and ‘DBMS’, and the outer query retrieves the student IDs ( S_IDs)
enrolled in those courses.
Correlated Nested Queries
In correlated nested queries, the inner query depends on the outer query for its
execution. For each row processed by the outer query, the inner query is
executed. This means the inner query references columns from the outer query.
The EXISTS keyword is often used with correlated queries.
Example 2: Using EXISTS
In this Example, we will find the names of students who are enrolled in the
course with C_ID = ‘C1’:
SELECT S_NAME FROM STUDENT S
WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
Output
S_NAME

RAM

RAMESH

Explanation:
For each student in the STUDENT table, the inner query checks if an entry
exists in the STUDENT_COURSE table with the same S_ID and the
specified C_ID. If such a record exists, the student’s name is included in the
output.
Common SQL Operators for Nested Queries
SQL provides several operators that can be used with nested queries to filter,
compare, and perform conditional checks.
1. IN Operator
The IN operator is used to check whether a column value matches any value in
a list of values returned by a subquery. This operator simplifies queries by
avoiding the need for multiple OR conditions.
Example: Retrieve student names who enrolled in ‘DSA’ or ‘DBMS’:
This query filters the students enrolled in the specified courses by chaining
multiple nested queries.
SELECT S_NAME FROM STUDENT
WHERE S_ID IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
2. NOT IN Operator
The NOT IN operator excludes rows based on a set of values from a subquery.
It is particularly useful for filtering out unwanted results. This operator helps
identify records that do not match the conditions defined in the subquery.
Example: Retrieve student IDs not enrolled in ‘DSA’ or ‘DBMS’:
This query excludes students who are enrolled in the courses ‘DSA’ or
‘DBMS’.
SELECT S_ID FROM STUDENT
WHERE S_ID NOT IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
Output
S_ID

S3

3. EXISTS Operator
The EXISTS operator checks for the existence of rows in a subquery. It returns
true if the subquery produces any rows, making it efficient for conditional
checks. This operator is often used to test for relationships between tables.
Example: Find student names enrolled in ‘DSA’
The inner query checks for matching records in the STUDENT_COURSE table,
and the outer query returns the corresponding student names.
SELECT S_NAME FROM STUDENT S
WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
4. ANY and ALL Operators
 ANY: Compares a value with any value returned by the subquery.
 ALL: Compares a value with all values returned by the subquery.
Example using ANY:
SELECT S_NAME FROM STUDENT
WHERE S_AGE > ANY (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);
Example using ALL:
SELECT S_NAME FROM STUDENT
WHERE S_AGE > ALL (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);
Why Use Nested Queries?
Nested queries are highly useful when:
 You need to retrieve data based on the results of another query.
 You want to perform filtering or aggregation without using joins.
 You need to break down complex operations into smaller steps.
Advantages of Nested Queries
 Simplifies complex queries: Nested queries allow us to divide
complicated SQL tasks into smaller, more manageable parts. This
modular approach makes queries easier to write, debug, and
maintain.
 Enhances flexibility: By enabling the use of results from one query
within another, nested queries allow dynamic filtering and indirect
joins, which can simplify query logic.
 Supports advanced analysis: Nested queries empower developers to
perform operations like conditional aggregation, subsetting, and
customized calculations, making them ideal for sophisticated data
analysis tasks.
 Improves readability: When properly written, nested queries can
make complex operations more intuitive by encapsulating logic
within inner queries.
Best Practices for Using Nested Queries
1. Optimize independent queries: Use independent nested queries
whenever possible, as they are easier to execute and debug. Ensure
that inner queries are optimized for performance by adding
appropriate indexes.
2. Prefer joins for simple queries: For cases where nested queries add
unnecessary complexity, consider using joins instead. Joins are
typically faster and more readable for straightforward relationships.
3. Avoid deep nesting: Limit the levels of nesting in queries to improve
performance and maintain readability. Deeply nested queries can be
computationally expensive and difficult to debug.
4. Use EXISTS and IN wisely: Choose the appropriate operator based
on the scenario. Use EXISTS for checking existence and IN for
comparing with a list of values.
5. Test query performance: Analyze the execution plan of our queries
to identify bottlenecks and improve efficiency. Rewrite queries where
necessary to enhance performance.
6. Maintain clarity: Use meaningful table aliases and comments to
ensure that nested queries remain understandable to other
developers or your future self.
Conclusion
Nested queries in SQL are a flexible feature that simplifies retrieving and
analyzing complex datasets. By understanding and applying the different
types of nested queries, such as independent and correlated subqueries, we
can optimize our database operations and streamline data management.
Nested queries are not only powerful but also essential for writing efficient and
effective SQL code. Use this article as our go-to resource for mastering SQL
nested queries and improving our database querying skills.

Join operation Vs Nested query in DBMS


The growth of technology and automation coupled with exponential amounts
of data has led to the importance and omnipresence of databases which,
simply put, are organized collections of data. Considering a naive approach,
one can theoretically keep all the data in one large table, however that
increases the access time in searching for a record, security issues if the
master table is destroyed, redundant storage of information and other issues.
So tables are decomposed into multiple smaller tables.
For retrieving information from multiple tables, we need to extract selected
data from different records, using operations called join(inner join, outer
join and most importantly natural join). Consider 2
table schemas employee(employee_name, street, city)with n rows and
works(employee_name, branch_name, salary) with m rows. A cartesian
product of these 2 tables creates a table with n*m rows. A natural join selects
from this n*m rows all rows with same values for employee_name. To avoid
loss of information(some tuples in employee have no corresponding tuples in
works) we use left outer join or right outer join.
A join operation or a nested query is better subject to conditions:

 Suppose our 2 tables are stored on a local system. Performing a join


or a nested query will make little difference. Now let tables be stored
across a distributed databases. For a nested query, we only extract
the relevant information from each table, located on different
computers, then merge the tuples obtained to obtain the result. For a
join, we would be required to fetch the whole table from each site
and create a large table from which the filtering will occur, hence
more time will be required. So for distributed databases, nested
queries are better.
 RDBMS optimizer is concerned with performance related to the
subquery or join written by the programmer. Joins are universally
understood hence no optimization issues can arise. If portability
across multiple platforms is called for, avoid subqueries as it may run
into bugs(SQL server more adept with joins as its usually used with
Microsoft’s graphical query editors that use joins).
 Implementation specific: Suppose we have queries where a few of
the nested queries are constant. In MySQL, every constant subquery
would be evaluated as many times as encountered, there being no
cache facility. This is an obvious problem if the constant subquery
involves large tuples. Subqueries return a set of data. Joins return a
dataset which is necessarily indexed. Working on indexed data is
faster so if the dataset returned by subqueries is large, joins are a
better idea.
 Subqueries may take longer to execute than joins depending on how
the database optimizer treats them(may be converted to joins).
Subqueries are easier to read, understand and evaluate than cryptic
joins. They allow a bottom-up approach, isolating and completing
each task sequentially.

Join operation and nested queries are both used in relational database
management systems (RDBMS) to combine data from multiple tables, but
they differ in their approach.
Join operation:
A join operation combines data from two or more tables based on a common
column or columns. The join operation is performed using the JOIN keyword in
SQL, and it returns a single result set that contains columns from all the
tables involved in the join.
For example, let’s say we have two tables, Table1 and Table2, with the
following data:
Table1
ID | Name
1 | John
2 | Sarah
3 | David
Table2
ID | Address
1 | 123 Main St.
2 | 456 Elm St.
4 | 789 Oak St.
If we want to combine the data from these two tables based on the ID
column, we can perform an inner join using the following SQL query:
SELECT Table1.ID, Table1.Name, Table2.Address
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.ID
Result:
ID | Name | Address
1 | John | 123 Main St.
2 | Sarah | 456 Elm St.
Nested query:
A nested query is a SQL query that is embedded within another SQL query. It
is used to retrieve data from one or more tables based on a condition that is
evaluated using the results of another query. The nested query is executed
first, and its results are used to evaluate the outer query.
For example, let’s say we have the same two tables as before:
Table1
ID | Name
1 | John
2 | Sarah
3 | David
Table2
ID | Address
1 | 123 Main St.
2 | 456 Elm St.
4 | 789 Oak St.
If we want to retrieve the names of the people who have an address in
Table2, we can use a nested query as follows:
SELECT Name
FROM Table1
WHERE ID IN (SELECT ID FROM Table2)
Result:
Name
John
Sarah
In this case, the nested query is executed first, and it returns the ID values of
the rows in Table2. These ID values are then used to evaluate the outer query,
which retrieves the names of the people who have those ID values in Table1.
The choice between using a join operation or a nested query depends on the
specific requirements of the task at hand. Joins are often faster and more
efficient for large datasets, but nested queries can be more flexible and allow
for more complex conditions to be evaluated.

Indexing in Databases – Set 1


Indexing improves database performance by minimizing the number of disc
visits required to fulfill a query. It is a data structure technique used to locate
and quickly access data in databases. Several database fields are used to
generate indexes. The main key or candidate key of the table is duplicated in
the first column, which is the Search key. To speed up data retrieval, the values
are also kept in sorted order. It should be highlighted that sorting the data is
not required. The second column is the Data Reference or Pointer which
contains a set of pointers holding the address of the disk block where that
particular key value can be found.

Structure of Index in Database


Attributes of Indexing
 Access Types: This refers to the type of access such as value-based
search, range access, etc.
 Access Time: It refers to the time needed to find a particular data
element or set of elements.
 Insertion Time: It refers to the time taken to find the appropriate
space and insert new data.
 Deletion Time: Time taken to find an item and delete it as well as
update the index structure.
 Space Overhead: It refers to the additional space required by the
index.
Structure of Index in Database

In general, there are two types of file organization mechanisms that are
followed by the indexing methods to store the data:
Sequential File Organization or Ordered Index File
In this, the indices are based on a sorted ordering of the values. These are
generally fast and a more traditional type of storing mechanism. These Ordered
or Sequential file organizations might store the data in a dense or sparse format.
 Dense Index
o For every search key value in the data file, there is an
index record.
o This record contains the search key and also a
reference to the first data record with that search key
value.

Dense Index

 Sparse Index
o The index record appears only for a few items in the
data file. Each item points to a block as shown.
o To locate a record, we find the index record with the
largest search key value less than or equal to the
search key value we are looking for.
o We start at that record pointed to by the index record,
and proceed along with the pointers in the file (that is,
sequentially) until we find the desired record.
o Number of Accesses required=log₂(n)+1, (here
n=number of blocks acquired by index file)

Sparse Index

Hash File Organization


Indices are based on the values being distributed uniformly across a range of
buckets. The buckets to which a value is assigned are determined by a function
called a hash function. There are primarily three methods of indexing:
 Clustered Indexing: When more than two records are stored in the
same file this type of storing is known as cluster indexing. By using
cluster indexing we can reduce the cost of searching reason being
multiple records related to the same thing are stored in one place
and it also gives the frequent joining of more than two tables
(records).
The clustering index is defined on an ordered data file. The data file
is ordered on a non-key field. In some cases, the index is created on
non-primary key columns which may not be unique for each record. In
such cases, in order to identify the records faster, we will group two
or more columns together to get the unique values and create an
index out of them. This method is known as the clustering index.
Essentially, records with similar properties are grouped together, and
indexes for these groupings are formed.
Students studying each semester, for example, are grouped together.
First-semester students, second-semester students, third-semester
students, and so on are categorized.
Clustered Indexing

 Primary Indexing: This is a type of Clustered Indexing wherein the


data is sorted according to the search key and the primary key of the
database table is used to create the index. It is a default format of
indexing where it induces sequential file organization. As primary
keys are unique and are stored in a sorted manner, the performance
of the searching operation is quite efficient.
 Non-clustered or Secondary Indexing: A non-clustered index just
tells us where the data lies, i.e. it gives us a list of virtual pointers or
references to the location where the data is actually stored. Data is
not physically stored in the order of the index. Instead, data is
present in leaf nodes. For eg. the contents page of a book. Each entry
gives us the page number or location of the information stored. The
actual data here(information on each page of the book) is not
organized but we have an ordered reference(contents page) to where
the data points actually lie. We can have only dense ordering in the
non-clustered index as sparse ordering is not possible because data
is not physically organized accordingly.
It requires more time as compared to the clustered index because
some amount of extra work is done in order to extract the data by
further following the pointer. In the case of a clustered index, data is
directly present in front of the index.
Non Clustered Indexing

 Multilevel Indexing: With the growth of the size of the database,


indices also grow. As the index is stored in the main memory, a
single-level index might become too large a size to store with
multiple disk accesses. The multilevel indexing segregates the main
block into various smaller blocks so that the same can be stored in a
single block. The outer blocks are divided into inner blocks which in
turn are pointed to the data blocks. This can be easily stored in the
main memory with fewer overheads.

Multilevel Indexing

Advantages of Indexing
 Improved Query Performance: Indexing enables faster data retrieval
from the database. The database may rapidly discover rows that
match a specific value or collection of values by generating an index
on a column, minimizing the amount of time it takes to perform a
query.
 Efficient Data Access: Indexing can enhance data access efficiency
by lowering the amount of disk I/O required to retrieve data. The
database can maintain the data pages for frequently visited columns
in memory by generating an index on those columns, decreasing the
requirement to read from disk.
 Optimized Data Sorting: Indexing can also improve the performance
of sorting operations. By creating an index on the columns used for
sorting, the database can avoid sorting the entire table and instead
sort only the relevant rows.
 Consistent Data Performance: Indexing can assist ensure that the
database performs consistently even as the amount of data in the
database rises. Without indexing, queries may take longer to run as
the number of rows in the table grows, while indexing maintains a
roughly consistent speed.
 By ensuring that only unique values are inserted into columns that
have been indexed as unique, indexing can also be utilized to ensure
the integrity of data. This avoids storing duplicate data in the
database, which might lead to issues when performing queries or
reports.
Overall, indexing in databases provides significant benefits for improving query
performance, efficient data access, optimized data sorting, consistent data
performance, and enforced data integrity
Disadvantages of Indexing
 Indexing necessitates more storage space to hold the index data
structure, which might increase the total size of the database.
 Increased database maintenance overhead: Indexes must be
maintained as data is added, destroyed, or modified in the table,
which might raise database maintenance overhead.
 Indexing can reduce insert and update performance since the index
data structure must be updated each time data is modified.
 Choosing an index can be difficult: It can be challenging to choose
the right indexes for a specific query or application and may call for a
detailed examination of the data and access patterns.
Features of Indexing
 The development of data structures, such as B-trees or hash tables,
that provide quick access to certain data items is known as indexing.
The data structures themselves are built on the values of the indexed
columns, which are utilized to quickly find the data objects.
 The most important columns for indexing columns are selected
based on how frequently they are used and the sorts of queries they
are subjected to. The cardinality, selectivity, and uniqueness of the
indexing columns can be taken into account.
 There are several different index types used by databases, including
primary, secondary, clustered, and non-clustered indexes. Based on
the particular needs of the database system, each form of index
offers benefits and drawbacks.
 For the database system to function at its best, periodic index
maintenance is required. According to changes in the data and usage
patterns, maintenance work involves building, updating, and
removing indexes.
 Database query optimization involves indexing, which is essential.
The query optimizer utilizes the indexes to choose the best execution
strategy for a particular query based on the cost of accessing the
data and the selectivity of the indexing columns.
 Databases make use of a range of indexing strategies, including
covering indexes, index-only scans, and partial indexes. These
techniques maximize the utilization of indexes for particular types of
queries and data access.
 When non-contiguous data blocks are stored in an index, it can result
in index fragmentation, which makes the index less effective. Regular
index maintenance, such as defragmentation and reorganization, can
decrease fragmentation.
Conclusion
Indexing is a very useful technique that helps in optimizing the search time
in database queries. The table of database indexing consists of a search key
and pointer. There are four types of indexing: Primary, Secondary Clustering,
and Multivalued Indexing. Primary indexing is divided into two types, dense and
sparse. Dense indexing is used when the index table contains records for every
search key. Sparse indexing is used when the index table does not use a search
key for every record. Multilevel indexing uses B+ Tree. The main purpose of
indexing is to provide better performance for data retrieval.

SQL-Clauses
SQL Views
iews in SQL are a type of virtual table that simplifies how users interact with
data across one or more tables. Unlike traditional tables, a view in SQL does
not store data on disk; instead, it dynamically retrieves data based on a pre-
defined query each time it’s accessed.
SQL views are particularly useful for managing complex queries, enhancing
security, and presenting data in a simplified format. In this guide, we will cover
the SQL create view statement, updating and deleting views, and using the
WITH CHECK OPTION clause.
What is a View in SQL?
A view in SQL is a saved SQL query that acts as a virtual table. Unlike regular
tables, views do not store data themselves. Instead, they dynamically
generate data by executing the SQL query defined in the view each time it is
accessed. It can fetch data from one or more tables and present it in
a customized format, allowing developers to:
 Simplify Complex Queries: Encapsulate complex joins and
conditions into a single object.
 Enhance Security: Restrict access to specific columns or rows.
 Present Data Flexibly: Provide tailored data views for different
users.
We will be using these two SQL tables for examples.
StudentDetails
-- Create StudentDetails table
CREATE TABLE StudentDetails (
S_ID INT PRIMARY KEY,
NAME VARCHAR(255),
ADDRESS VARCHAR(255)
);

INSERT INTO StudentDetails (S_ID, NAME, ADDRESS)


VALUES
(1, 'Harsh', 'Kolkata'),
(2, 'Ashish', 'Durgapur'),
(3, 'Pratik', 'Delhi'),
(4, 'Dhanraj', 'Bihar'),
(5, 'Ram', 'Rajasthan');

StudentMarks
-- Create StudentMarks table
CREATE TABLE StudentMarks (
ID INT PRIMARY KEY,
NAME VARCHAR(255),
Marks INT,
Age INT
);

INSERT INTO StudentMarks (ID, NAME, Marks, Age)


VALUES
(1, 'Harsh', 90, 19),
(2, 'Suresh', 50, 20),
(3, 'Pratik', 80, 19),
(4, 'Dhanraj', 95, 21),
(5, 'Ram', 85, 18);

CREATE VIEWS in SQL


We can create a view using CREATE VIEW statement. A View can be created
from a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2…..
FROM table_name
WHERE condition;
Key Terms:
 view_name: Name for the View
 table_name: Name of the table
 condition: Condition to select rows

Example 1: Creating a Simple View from a Single Table


Let’s look at some examples of CREATE VIEW Statement in SQL to get a better
understanding of how to create views in SQL. In this example, we will create a
View named DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
Use the below query to retrieve the data from this view
SELECT * FROM DetailsView;
Output:
Here, we will create a view named StudentNames from the table StudentDetails.
Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

Example 2: Creating a View From Multiple Tables


In this example we will create a View MarksView that combines data from
both tables StudentDetails and StudentMarks. To create a View from multiple
tables we can simply include multiple tables in the SELECT statement.
Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:

Managing Views: Listing, Updating, and Deleting


1. Listing all Views in a Database
We can list all the Views in a database, using the SHOW FULL
TABLES statement or using the information_schema table. A View can be
created from a single table or multiple tables
USE "database_name";
SHOW FULL TABLES WHERE table_type LIKE "%VIEW";
Using information_schema
SELECT table_name
FROM information_schema.views
WHERE table_schema = 'database_name';

OR

SELECT table_schema, table_name, view_definition


FROM information_schema.views
WHERE table_schema = 'database_name';
2. Deleting a View
SQL allows us to delete an existing View. We can delete or drop View using
the DROP statement. Here’s how to remove the MarksView:
DROP VIEW view_name;
Example: In this example, we are deleting the View MarksView.
DROP VIEW MarksView;
3. Updating a View Definition
If we want to update the existing data within the view, use
the UPDATE statement.
UPDATE view_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
If you want to update the view definition without affecting the data, use
the CREATE OR REPLACE VIEW statement. For example, let’s add
the Age column to the MarksView:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: Not all views can be updated using the UPDATE statement.
Rules to Update Views in SQL:
Certain conditions need to be satisfied to update a view. If any of these
conditions are not met, the view can not be updated.
1. The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex
queries.
5. The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
Advanced Techniques with Views
1. Updating Data Through Views
We can use the CREATE OR REPLACE VIEW statement to add or replace
fields from a view If we want to update the view MarksView and add the field
AGE to this View from StudentMarks Table, we can do this by:
Example:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

2. Inserting Data into Views


We can insert a row in a View in the same way as we do in a table. We can use
the INSERT INTO statement of SQL to insert a row in a View. In the below
example, we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table“.
Example:
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

3. Deleting a row from a View


Deleting rows from a view is also as simple as deleting rows from a table. We
can use the DELETE statement of SQL to delete rows from a view. Also deleting
a row from a view first deletes the row from the actual table and the change is
then reflected in the view. In this example, we will delete the last row from the
view DetailsView which we just added in the above example of inserting rows.
Example:
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

4. WITH CHECK OPTION Clause


The WITH CHECK OPTION clause in SQL is a very useful clause for views. It
applies to an updatable view. It is used to prevent data modification (using
INSERT or UPDATE) if the condition in the WHERE clause in the CREATE VIEW
statement is not satisfied.
If we have used the WITH CHECK OPTION clause in the CREATE VIEW
statement, and if the UPDATE or INSERT clause does not satisfy the conditions
then they will return an error. In the below example, we are creating a View
SampleView from the StudentDetails Table with a WITH CHECK OPTION
clause.
Example:
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this view, if we now try to insert a new row with a null value in the NAME
column then it will give an error because the view is created with the
condition for the NAME column as NOT NULL. For example, though the View
is updatable then also the below query for this View is not valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
Uses and Benefits of SQL Views
A good database should contain views for the given reasons:
1. Restricting data access – Views provide an additional level of table
security by restricting access to a predetermined set of rows and
columns of a table.
2. Hiding data complexity – A view can hide the complexity that exists
in multiple joined tables.
3. Simplify commands for the user – Views allow the user to select
information from multiple tables without requiring the users to
actually know how to perform a join.
4. Store complex queries – Views can be used to store complex
queries.
5. Rename Columns – Views can also be used to rename the columns
without affecting the base tables provided the number of columns in
view must match the number of columns specified in a select
statement. Thus, renaming helps to hide the names of the columns of
the base tables.
6. Multiple view facility – Different views can be created on the same
table for different users.
Conclusion
SQL Views provides an efficient solution for simplifying complex queries,
improving security, and presenting data in a more accessible format. By
mastering the creation, management, and updating of views, we can improve
the maintainability and performance of our database systems. By
understanding and Using views, we can significantly enhance both the accuracy
and security of our database systems.

SQL Indexes
When it comes to relational database performance optimizing, SQL indexes are
a game changer. Imagine them like an index in a book instead of flipping
through every page (row), the database can jump right to the data it requires.
SQL Indexes are crucial elements in relational databases that greatly
improve data retrieval speeds by minimizing the need for full table scans. By
providing quick access paths, indexes allow queries to perform faster,
especially on large datasets. However, while indexes speed up SELECT
queries, they can slow down data manipulation operations (INSERT, UPDATE,
DELETE)
What Are Indexes in SQL?
An index in SQL is a schema object that improves the speed of data
retrieval operations on a table. It works by creating a separate data
structure that provides pointers to the rows in a table, making it faster to look
up rows based on specific column values. Indexes act as a table of contents for
a database, allowing the server to locate data quickly and efficiently, reducing
disk I/O operations.
Benefits of Indexes:
 Faster Queries: Speeds up SELECT and JOIN operations.
 Lower Disk I/O: Reduces the load on your database by limiting the
amount of data scanned.
 Better Performance on Large Tables: Essential when working with
millions of records.
Creating an Index
Creating an index allows us to define a quick access path to data. SQL
indexes can be applied to one or more columns and can be
either unique or non-unique. Unique indexes ensure that no duplicate
values are entered in the indexed columns, while non-unique indexes simply
speed up queries without enforcing uniqueness. You can create:
 Single-column indexes: For basic queries
 Multi-column indexes: For queries using multiple filters
 Unique indexes: To ensure data uniqueness
Syntax:
CREATE INDEX index
ON TABLE column;
Example
CREATE INDEX idx_product_id
ON Sales (product_id);
Explanation:
This creates an index named idx_product_id on the product_id column in
the Sales table, improving the speed of queries that filter or join based on this
column.
Multi – Column Indexes
If queries often use more than one column in conditions, we can create a multi-
column index for better performance.
Syntax:
CREATE INDEX index
ON TABLE (column1, column2,…..);
Example
CREATE INDEX idx_product_quantity
ON Sales (product_id, quantity);
Explanation:
This index allows the database to quickly filter or join data based on
both product_id and quantity columns.
Unique Indexes
A unique index ensures that all values in the indexed column(s) are unique,
preventing duplicates. These are useful for maintaining the integrity of the data,
ensuring that no two rows have the same values in the indexed columns.
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column_name);
Example
CREATE UNIQUE INDEX idx_unique_employee_id
ON Employees (employee_id);
Explanation:
This index ensures that no two rows in the Employees table have the
same employee_id, which maintains data integrity and prevents duplicate
entries.
Removing an Index
If an index is no longer needed, it can be removed to improve write
performance or save storage space. As indexes can slow down
operations like INSERT, UPDATE, and DELETE due to the overhead of
maintaining them, dropping unnecessary indexes can improve overall
database efficiency. The DROP INDEX command is used for this purpose.
Syntax
DROP INDEX index;
Explanation:
This command removes an index from the database schema. It does not affect
the underlying data in the table but may slow down future queries that would
have benefited from the index.
Altering an Index
If an index requires adjustments, such as reorganizing or rebuilding, it can be
altered without affecting the data. This is useful for optimizing index
performance as tables grow larger.
Syntax:
ALTER INDEX IndexName
ON TableName REBUILD;
Explanation:
This command rebuilds the specified index, which can optimize query
performance by reorganizing its structure, especially in large tables.
Confirming and Viewing Indexes
We can view all the indexes in a database to understand which ones are in use
and confirm their structure. In SQL, the following query helps us see the indexes
for a given table:
Syntax:
SELECT * from USER_INDEXES;
Explanation:
This query retrieves all the indexes in the database schema, showing their
names and the columns they are associated with. We can use this information
to audit or manage existing indexes.
Renaming an Index
In some cases, renaming an index might be necessary for clarity or consistency.
While SQL doesn’t directly support renaming indexes, we can use a
combination of commands to achieve this.
Syntax:
EXEC sp_rename ‘old_index_name’, ‘new_index_name’, ‘INDEX’;
Explanation:
This command allows us to rename an existing index, which helps maintain
clarity in our database schema.
When Should Indexes Be Created?
Indexes can significantly improve query performance, but they should be used
judiciously. The following scenarios warrant creating indexes:
1. Wide Range of Values: Indexes are helpful when a column has a
wide range of values, such as product IDs or customer names, as they
speed up search operations.
2. Non-NULL Values: Columns that don’t contain many NULL values
are ideal candidates for indexing, as NULLs complicate the indexing
process.
3. Frequent Query Conditions: Indexes should be created on columns
frequently used in WHERE clauses or as part of a join condition.
When Should Indexes Be Avoided?
While indexes enhance performance, they may not always be beneficial,
especially in certain situations:
1. Small Tables: Indexes are not needed for small tables as queries will
likely perform well without them.
2. Infrequent Query Use: If a column is rarely used in queries, indexing
it will only add overhead.
3. Frequently Updated Columns: Avoid indexing columns that are
frequently updated, as the index will need to be updated with each
change, adding overhead.
Why SQL Indexing is Important?
Indexing in SQL is a critical feature for optimizing query performance,
especially for large datasets. Here are some common scenarios where indexing
proves beneficial:
1. Large Data Tables: SQL queries on tables with millions of rows can
significantly slow down due to full table scans. Indexes provide a
faster alternative by allowing quick access to relevant rows.
2. Join Optimization: Indexes on columns used for joining tables (such
as foreign keys) improve the performance of complex joins.
3. Search Operations: Queries that search for specific values in a
column can be sped up with indexes, reducing the time required to
perform lookups.
4. However, it is essential to be mindful of the storage cost and
performance tradeoffs associated with indexes. Over-indexing can
lead to unnecessary overhead, while under-indexing may slow down
data retrieval
Conclusion
SQL Indexing is important in database optimization as it accelerates data
retrieval, query performance, and database management as a
whole. Knowing when and how to create, maintain, and drop indexes can
help database administrators optimize application performance
while ensuring an efficient and scalable database schema.
Always make sure that indexes are created wisely based on
query requirements and data structure to achieve the correct balance between
read and write performance.
SQL Queries on Clustered and Non-Clustered
Indexes
ndexes in SQL play a pivotal role in enhancing database performance by
enabling efficient data retrieval without scanning the entire table. The two
primary types of indexes Clustered Index and Non-Clustered Index serve
distinct purposes in optimizing query performance.
In this article, we will explain Clustered and Non-Clustered Indexes in detail,
their creation, use cases, and examples to help us master the concepts.
What are Indexes in SQL?
Indexing in SQL is similar to the index page in a book, they allow the database
to quickly locate data without scanning the entire table. Without indexing, SQL
Server performs a full table scan, which can be time-consuming for large
datasets. By creating indexes, SQL Server optimizes query execution, reducing
retrieval time. In the same way, a table’s index allows us to locate the exact
data without scanning the whole table.
Key Benefits of Indexing
 Faster SELECT queries.
 Efficient data access for UPDATE, DELETE, and JOIN operations.
 Minimizes disk I/O operations.
Types of Indexes in SQL
1. Clustered index
2. Non-clustered index
Clustered Index
A clustered index is the type of indexing that establishes a physical sorting
order of rows. The data rows are stored directly in the order of the indexed
column(s). Each table can have only one clustered index because it dictates
the data’s physical storage. A clustered index is like a Dictionary in which the
sorting order is alphabetical and there is no separate index page.
Suppose we have a table Student_info which contains ROLL_NO as a primary
key, then the clustered index which is self-created on that primary key will sort
the Student_info table as per ROLL_NO.
Example: Creating a Clustered Index
CREATE TABLE Student_info
(
ROLL_NO int(10) primary key,
NAME varchar(20),
DEPARTMENT varchar(20),
);
INSERT INTO Student_info values(1410110405, 'H Agarwal', 'CSE');
INSERT INTO Student_info values(1410110404, 'S Samadder', 'CSE');
INSERT INTO Student_info values(1410110403, 'MD Irfan', 'CSE');

SELECT * FROM Student_info;


Output
ROLL_NO NAME DEPARTMENT

1410110403 MD Irfan CSE

1410110404 S Samadder CSE


ROLL_NO NAME DEPARTMENT

1410110405 H Agarwal CSE

Explanation:
 The ROLL_NO column is the primary key, making it the Clustered
Index by default.
 Rows are stored in ascending order of ROLL_NO.

Dropping and Creating a Custom Clustered Index


If we want to create a Clustered index on another column, first we have to
remove the primary key, and then we can remove the previous index. Note
that defining a column as a primary key makes that column the Clustered
Index of that table.
To create a clustered index on a different column:
1. Remove the existing primary key (if any).
2. Drop the previous clustered index.
Syntax
DROP INDEX table_name.index_name;

CREATE CLUSTERED INDEX IX_table_name_column_name


ON table_name (column_name ASC);
Example
CREATE CLUSTERED INDEX IX_Student_info_NAME
ON Student_info (NAME ASC);
Non-Clustered Index
Non-Clustered index is an index structure separate from the data stored in a
table that reorders one or more selected columns. The non-clustered index is
created to improve the performance of frequently used queries not covered by
a clustered index. It’s like a textbook, the index page is created separately at
the beginning of that book.
Example: Creating a Non-Clustered Index
We start by creating the Student_info table and inserting some sample data.
CREATE TABLE Student_info
(
ROLL_NO int(10),
NAME varchar(20),
DEPARTMENT varchar(20),
);

INSERT INTO Student_info values(1410110405, 'H Agarwal', 'CSE');


INSERT INTO Student_info values(1410110404, 'S Samadder', 'CSE');
INSERT INTO Student_info values(1410110403, 'MD Irfan', 'CSE');

SELECT * FROM Student_info;


Output
ROLL_NO NAME DEPARTMENT

1410110405 H Agarwal CSE

1410110404 S Samadder CSE

1410110403 MD Irfan CSE

Syntax
create NonClustered index IX_table_name_column_name on table_name
(column_name ASC)
We will create a Non-Clustered Index on the NAME column to improve query
performance when searching by name. Here is the SQL Query for the same
Query:
create NonClustered index IX_Student_info_NAME on Student_info (NAME
ASC)
Output
NAME ROW_ADDRESS

H Agarwal 1

MD Irfan 3

S Samadder 2

Differences between Clustered and Non-clustered Index


Aspect Clustered Index Non-Clustered Index

Data Storage Determines the physical order Does not affect the physical
Order of data in the table. order of data.

Number of Multiple indexes can be


Only one per table.
Indexes created on a table.

The index is the table; data The index is a separate


Index
rows are stored in the index structure with pointers to data
Structure
order. rows.
Aspect Clustered Index Non-Clustered Index

Useful for quick lookups and


Optimized for range queries
Performance searches on non-primary key
and ordered data retrieval.
columns.

If no clustered index is
Primary Key specified, the primary key Can be created on any column,
Default usually becomes the clustered not necessarily a primary key.
index.

More flexible as multiple non-


Less flexible due to the single
Flexibility clustered indexes can be
ordering constraint.
created.

Ideal for tables where data is Ideal for optimizing search


frequently retrieved in a queries on columns that are
Use Case
sorted order or requires range not the primary key or
queries. clustered index.

Optimizing Queries with Clustered and Non-Clustered


Indexes
Below are detailed examples of SQL queries and the advantages of
using Clustered Indexes and Non-Clustered Indexes, along with practical
scenarios to illustrate their impact on query performance.
1. SELECT Queries with WHERE Clause
Clustered Index
When executing a SELECT query with a WHERE clause on a table with a Clustered
Index, the database engine uses the index to directly locate rows matching the
condition, minimizing disk I/O.
Example
-- Create a table with a clustered index on ROLL_NO
CREATE TABLE Student_info (
ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(20),
DEPARTMENT VARCHAR(20)
);

INSERT INTO Student_info VALUES


(1410110405, 'H Agarwal', 'CSE'),
(1410110404, 'S Samadder', 'CSE'),
(1410110403, 'MD Irfan', 'CSE');
-- Query using the clustered index
SELECT *
FROM Student_info
WHERE ROLL_NO = 1410110404;
Output
ROLL_NO NAME DEPARTMENT

1410110404 S Samadder CSE

Non-Clustered Index
If a Non-Clustered Index is created on the NAME column, the query optimizer
uses the index to locate matching rows efficiently.
Example
-- Create a non-clustered index on NAME
CREATE NONCLUSTERED INDEX IX_Student_info_NAME
ON Student_info (NAME ASC);

-- Query using the non-clustered index


SELECT *
FROM Student_info
WHERE NAME = 'H Agarwal';
Output
ROLL_NO NAME DEPARTMENT

1410110405 H Agarwal CSE

2. UPDATE Queries
Clustered Index
When updating a row in a table with a Clustered Index, the database can
quickly locate the row to modify based on the indexed column.
Example:
-- Update the DEPARTMENT of a specific ROLL_NO
UPDATE Student_info
SET DEPARTMENT = 'ECE'
WHERE ROLL_NO = 1410110403;
Output
ROLL_NO NAME DEPARTMENT

1410110403 MD Irfan ECE

Non-Clustered Index
If the UPDATE query references columns that are not part of the clustered
index, SQL Server may need to perform additional disk writes to update the
non-clustered index as well.
Example:
-- Update NAME for a specific ROLL_NO
UPDATE Student_info
SET NAME = 'Harsh Agarwal'
WHERE ROLL_NO = 1410110405;
Output
ROLL_NO NAME DEPARTMENT

1410110405 Harsh Agarwal CSE

1410110404 S Samadder CSE

1410110403 MD Irfan CSE

3. JOIN Queries
Clustered Index
When performing a JOIN operation between two large tables, SQL Server can
use the clustered index on the join column(s) to efficiently match the rows from
both tables. This can significantly reduce the time required to complete the
query.
Example:
-- Create another table for join
CREATE TABLE Course_enrollments (
ROLL_NO INT,
COURSE_NAME VARCHAR(20)
);

INSERT INTO Course_enrollments VALUES


(1410110405, 'Data Structures'),
(1410110404, 'Algorithms'),
(1410110403, 'Databases');

-- Join query
SELECT s.ROLL_NO, s.NAME, e.COURSE_NAME
FROM Student_info s
JOIN Course_enrollments e
ON s.ROLL_NO = e.ROLL_NO;
Output
ROLL_NO NAME COURSE_NAME

1410110405 H Agarwal Data Structures

1410110404 S Samadder Algorithms


ROLL_NO NAME COURSE_NAME

1410110403 MD Irfan Databases

Non-Clustered Index
If the JOIN operation references columns that are not part of the clustered
index, SQL Server can use a non-clustered index to find the matching rows.
However, this may require additional disk reads and slow down the query.
Conclusion
Both clustered and non-clustered indexes play important roles in
optimizing SQL query performance. While clustered indexes physically
reorder the table’s data for better range queries, non-clustered indexes offer
flexibility by providing fast lookups without altering data order. Understanding
when and how to implement these indexes is key to
improving database performance.

SQL Tutorial
SQL is a Structured query language used to access and manipulate data in
databases. SQL stands for Structured Query Language. We can create, update,
delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc.
Overall, SQL is a query language that communicates with databases.
In this SQL tutorial, you’ll learn all the basic to advanced SQL concepts
like SQL queries, SQL join, SQL injection, SQL insert, and creating tables in
SQL.
SQL Uses
SQL's integration with various technologies makes it essential for managing
and querying data in databases. Whether it's in traditional relational databases
(RDBMS) or modern technologies such as machine learning, AI, and blockchain,
SQL plays a key role. It works seamlessly with DBMS (Database Management
Systems) to help users interact with data, whether stored in
structured RDBMS or other types of databases.
 Data Science & Analytics: Used for querying large datasets, data
cleaning, and analysis. Analysts use SQL to generate reports and
insights that inform business decisions.
 Machine Learning & AI: Helps in preparing and managing the data
required for training machine learning models and AI algorithms. It is
used for data cleaning, transformation, and extraction.
 Web Development: Used to manage user data, e-commerce
transactions, and content management in websites and applications
built with frameworks like Django, Node.js, and Ruby on Rails.
 Cloud and Big Data: SQL is integrated into cloud-based databases
(e.g., Amazon RDS, Microsoft Azure SQL) and Big Data platforms
(e.g., Apache Hive) to enable seamless data querying and
management.
 Blockchain and Decentralized Systems: In blockchain systems, SQL
can be used to manage off-chain data, providing efficient data
storage and retrieval alongside decentralized ledger technology.
How SQL work?
When you interact with a database, you typically use SQL commands to
perform these operations. These commands are translated into actions by the
SQL Engine, the core component responsible for processing queries. The SQL
Engine parses and compiles SQL queries, optimizing and executing them to
interact with the stored data. The SQL Engine also ensures that data retrieval
and modifications are efficient and consistent.
Different DBMS tools (like MySQL, SQL Server, etc.) provide an interface and
APIs that users can use to interact with the database. These tools provide a
user-friendly way to write and execute SQL queries, but internally, they rely on
their respective SQL Engines to process these commands.
For example, MySQL uses its own SQL Engine to parse, optimize, and execute
queries, while SQL Server has a different SQL Engine for the same task. These
engines ensure that SQL queries are executed in a way that respects the
underlying database structure and the specific DBMS’s optimizations.
Example
In this detailed SQL tutorial for beginners, we'll explore practical SQL
examples for managing employee data within a database. We'll create a table
to store employee information and populate it with sample data
like Employee_Id, Name, Age, Department, and Salary.
If you want to retrieves data from the employees table where the salary is
greater than 55000.00 then we will use SELECT Statement.
Query:
SELECT * FROM employees WHERE Salary > 55000.00;
Basics
SQL or Structured Query Language is a fundamental skill for anyone who wants
to interact with databases. This standard Query Language all users to create,
manage, and retrieve data from relational databases. In this SQL tutorial PDF,
we have listed all the basics of SQL. Explore this section to sharpen your SQL
basics.
 Introduction
 Data Types
 Operators
 Commands

Create Database
The first step to storing the information electronically using SQL includes
creating database. And in this section we will learn how to Create, Select, Drop,
and Rename databases with examples.
 CREATE Database
 DROP Database
 RENAME Database
 SELECT Database

Tables
The cornerstone of any SQL database is the table. Basically, these structure
functions is very similar to spreadsheets, which store data in very organized
grid format. In this section, you will learn how to Create, Drop, Delete, and more
related to Table.
 CREATE TABLE
 DROP TABLE
 RENAME TABLE
 TRUNCATE TABLE
 COPY TABLE
 TEMP TABLE
 ALTER TABLE

CRUD Operations
In this section, you will learn about the SQL Queries like SELECT statement,
SELECT LAST, and more. Explore this section and learn how to use these
queries.
 SELECT Statement
 INSERT INTO
 INSERT Multiple Rows
 UPDATE Statement
 DELETE Statement
 DELETE Duplicate Rows

Clauses
Unlock the power of SQL Clauses with this SQL tutorial. Here in this section,
you will learn how to use SELECT, WHERE, JOIN, GROUP BY, and more to
query databases effectively.
 WHERE Clause
 WITH Clause
 HAVING Clause
 ORDER By Clause
 Group By Clause
 LIMIT Clause
 Distinct Clause
 FETCH
 Aliases

Operators
SQL Operators" refers to the fundamental symbols and keywords within the
SQL that enable users to perform various operations and SQL AND, OR, LIKE,
NOT, and more operators on databases. Here, we have discussed all the SQL
operators in a detailed manner with examples.
 AND Operator
 OR Operator
 Logical Operators
 LIKE Operator
 IN Operator
 NOT Operator
 NOT EQUAL Operator
 IS NULL Operator
 UNION Operator
 UNION ALL Operator
 EXCEPT Operator
 BETWEEN Operator
 ALL and ANY
 INTERSECT Operator
 EXISTS Operator
 CASE Operator

Aggregate Functions
Whether you are calculating the total sales revenue for a particular product,
finding the average age of customers, or determining the highest value in a
dataset, SQL Aggregate Functions make these tasks straightforward and
manageable.
 Aggregate Function
 Count() Function
 SUM() Function
 MIN() Function
 MAX() Function
 AVG() Function
Data Constraints
Constraints act as rules or conditions imposed on the data, dictating what
values are permissible and what actions can be taken. They play a crucial role
in maintaining the quality and coherence of the database by preventing errors.
So, explore this section to get a hand on SQL Data Constraints.
 NOT NULL Constraints
 Primary Key Constraints
 Foreign Key Constraints
 Composite Key
 Unique Constraints
 Alternate Key
 CHECK Constraints
 DEFAULT Constraints

Joining Data
SQL joins serve as the weaver's tool, allowing you to seamlessly merge data
from multiple tables based on common threads. So explore this section to learn
how to use JOIN command.
 JOIN
 Outer Join
 Left Join
 Right Join
 Full Join
 Cross Join
 Self Join
 UPDATE with JOIN
 DELETE JOIN
 Recursive Join

Functions
SQL functions offer an efficient and versatile approach to data analysis. By
leveraging these functions within your queries, you can enhance the depth and
accuracy of your insights, transforming raw data into actionable knowledge.
 Date Functions
 String Functions
 Numeric Functions
 Statistical Functions
 JSON Functions
 Conversion Functions
 Datatype Functions
 LTRIM Function
 UPPER Function
 RTRIM Function
Views
Views makes easier for anyone to access the information they need, without
getting bogged down in complicated queries. 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
 DELETE VIEW

Indexes
Indexes work by organizing specific columns in a particular order, allowing the
database to quickly pinpoint the information you need. And in this section, we
have listed all the points that one has to learn while learning SQL.
 Indexes
 Create Index
 Drop Index
 Show Indexes
 Unique Index
 Clustered Index vs Non-Clustered Index

Subquery
Subqueries allow you to perform nested queries within a larger query,
enabling more complex data retrieval. They help in filtering data or
performing operations on data that would otherwise require multiple queries.
 Subquery
 Correlated Subqueries
 Nested Queries

Miscellaneous Topics
In this miscellaneous section, you will encounter concepts like stored
procedures for automating repetitive tasks, triggers for automated actions
based on data changes, and window functions for complex calculations within
a single query.
 Wildcards Operators
 Comments
 Pivot and Unpivot
 Trigger
 Hosting
 Performance Tuning
 Stored Procedures
 Transactions
 Sub Queries
 Using Sequences
 Auto Increment
 Window functions
 Cursors
 Common Table Expressions
 Database Tuning
 Dynamic
 Regular Expressions
Exercises, Interview Questions & Cheat Sheet
This section provides hands-on exercises and commonly asked interview
questions to help solidify your SQL knowledge. It also includes a cheat sheet
for quick reference, making SQL concepts easier to grasp.
 Exercises
 Quiz
 Interview Questions
 Query Interview Questions
 Cheat Sheet
 30 Days of SQL – From Basic to Advanced

Advanced SQL & Databases


Advanced SQL topics explore techniques like optimization, complex joins, and
working with large-scale databases. This section also covers the use of
advanced functions and stored procedures to handle sophisticated database
operations.
Database Design and Modeling
Database design focuses on creating an efficient database structure that is
scalable and meets user requirements. Modeling involves defining
relationships, entities, and constraints to ensure data integrity and efficient
querying.
 Introduction of ER Model
 How to Draw Entity Relationship Diagrams (ERDs)
 Mapping from ER Model to Relational Model
 Introduction of Database Normalization
 Functional Dependency and Attribute Closure
 Types of Functional dependencies
 Rules of Inference
 Normal Forms in DBMS
 Denormalization in Databases
 Database Design
Database Security
Database security protects data from unauthorized access, corruption, and
breaches. It includes encryption, authentication, and user privilege
management to safeguard sensitive information stored in databases.
 Injection
 Types of SQL Injection
 Data Encryption
 Database Recovery Techniques in DBMS
 Backup
 How to Restore SQL Server Database From Backup?
Projects
SQL projects provide practical experience in applying SQL concepts to real-
world problems. These projects allow you to build and manage databases for
various domains, enhancing your hands-on skills in database design and
querying.
 Ola SQL Data Analysis
 Walmert Sales Data Analysis
 Music Store Data Analysis
 Healthcare Sysytem
 Library Management system
 Personal Blogging Platform: Mastering Database Architecture and
CRUD Operations
 To-Do List
 URL Shortening Service
 E-commerce Database
 Movie Reservation System
Database Connectivity
Database connectivity enables applications to interact with databases through
established protocols and drivers. This section covers how to establish secure
connections and manage database interactions in programming languages
like PHP, Python, and Java.
 ORM (Object-Relational Mapping)
 ODM (Object-Document Mapping)
 ODBC (Open Database Connectivity)
Applications
In data-driven industries where managing databases is very important in
regular, Here are some important SQL applications.
 To support client/server architecture, software engineers use SQL to
establish the connection between the back-end and front-end.
 SQL can also be used in the 3-tier architecture of a client, an
application server, and a database.
 SQL is used as a Data Definition Language(DDL) in which we can
independently create a database, define the structure, use it, and
discard it when its work is done.
 SQL is used as a Data Manipulation Language(DML) in which we
can enter data, modify data, and extract data.
 SQL is used as a Data Control Language(DCL) it specifies how we
can protect our database against corruption and misuse.

SQL Tutorial
Jobs and Opportunities
There are numerous companies around the globe seeking SQL professionals,
and they pay high packages. The average salary of SQL developers is
around 40,000–65,000 INR. In this section, we have listed some of the top giant
companies that hire SQL experts.
 Google
 Microsoft
 Amazon
 Meta
 Apple
 Accenture
 Deloitte
 McKinsey & Company
 Boston Consulting Group
 KPMG
 JPMorgan Chase
 Bank of America
 Citigroup
 Wells Fargo
 HSBC
 Netflix
 Airbnb
 Capgemini
 Wipro
 Infosys
 Tata Consultancy
Advantages
SQL or Structured Query Language, is one of the most popular query
languages in the field of data science. SQL is the perfect query language that
allows data professionals and developers to communicate with their
databases.
In the below section, we have listed some of the most prominent advantages
or benefits of Structured Query Language:
 Simple and Easy to Learn: Most of the commands and syntax in SQL
are like normal English, which makes SQL easy to learn. Along with
this, SQL follows a logical structure that helps promote readability
and understanding.
 Efficiency and Speed Execution: Well, SQL is optimized for RDBMS,
which means relational database, and this thing ensures fast query
execution.
 Standardization: SQL is a widely accepted standard query language
and ensures compatibility across different database systems.
 Scalable: SQL can efficiently manage massive datasets,
accommodating growth without compromising performance.
Latest Trends and Updates
The world of SQL is constantly evolving, so here are some of the hottest
trends and updates to keep you in the loop:
Big Data and SQL: Big data store vast amounts of information from various
sources. SQL queries act as a bridge, enabling users to extract specific data
subsets for further analysis.
Cloud Computing and SQL: Cloud SQL lets your database scale up or down
based on your needs. Along with that it very cost effective so you have only pay
for the resources you use, making it a cost-efficient option for businesses of all
sizes.
Machine Learning and SQL: Data scientists leverage SQL to prepare and clean
data for analysis, making it a crucial skill for this field.
Real-time Data Processing with SQL: The need for immediate insights is
driving the growth of streaming SQL. This allows you to analyze data as it's
generated, providing real-time visibility into what's happening.
SQL in Data Governance and Compliance: With stricter data privacy
regulations, SQL is playing a role in ensuring data security and compliance.
Queries can be used to control access to sensitive information and track data
usage for auditing purposes.
MySQL | Common MySQL Queries
MySQL server is a open-source relational database management system
which is a major support for web based applications. Databases and related
tables are the main component of many websites and applications as the data
is stored and exchanged over the web. Even all social networking websites
mainly Facebook, Twitter, and Google depends on MySQL data which are
designed and optimized for such purpose. For all these reasons, MySQL server
becomes the default choice for web applications.
MySQL server is used for data operations like querying, sorting, filtering,
grouping, modifying and joining the tables. Before learning the commonly
used queries, let us look into some of the advantages of MySQL.
Advantages of MySQL :
 Fast and high Performance database.
 Easy to use, maintain and administer.
 Easily available and maintain integrity of database.
 Provides scalability, usability and reliability.
 Low cost hardware.
 MySQL can read simple and complex queries and write operations.
 InnoDB is default and widely used storage engine.
 Provides strong indexing support.
 Provides SSL support for secured connections.
 Provides powerful data encryption and accuracy.
 Provides Cross-platform compatibility.
 Provides minimized code repetition.
Queries can be understood as the commands which interacts with database
tables to work around with data. Some of the commonly used MySQL queries,
operators, and functions are as follows :
1. SHOW DATABASES
This displays information of all the existing databases in the server.
Output:

Note : The
databases ‘information_schema’, ‘mysql’ and ‘performance_schema’ are
system databases which are used internally by MySQL server.
A ‘test’ database is meant for testing purpose which is provided during
installation.
2. USE database_name
database_name : name of the database
This sets the database as the current database in the MySQL server.
To display the current database name which is set, use syntax
SELECT DATABASE();
3. DESCRIBE table_name
table_name : name of the table
This describes the columns of the table_name with respect to Field, Type,
Null, Key, Default, Extra.
4. SHOW TABLES
This shows all the tables in the selected database as a information.
5. SHOW CREATE TABLE table_name
table_name : name of the table
This shows the complete CREATE TABLE statement used by MySQL for
creating the table.
6. SELECT NOW()
MySQL queries mostly starts with SELECT statement.
This query shows the current date and time.
Output :
2019-09-24 07:08:30
7. SELECT 2 + 4;
Output :
6
This executes SELECT statement without any table.
SELECT can be used for executing an expression or evaluating an in-built
function.
SELECT can also be used for more than one or many columns.
Example :
SELECT 2+4, CURDATE();
Output :
8. Comments
Comments are of two types. Multi-line comments or single-line or end-of-line
comment.
/* These are multi-line comments. */
# This is single-line comment.
-- This is also single-line comment.
9. CREATE DATABASE database_name
database_name : name of the database
This statement creates a new database.
10. DROP DATABASE database_name
database_name : name of the database
This statement deletes the database.
Note : User has to be very careful before deleting a database as it will lose all
the crucial information stored in the database.
11. CREATE TABLE table_name(column1, column2, column3..)
table_name : name of the table
column1 : name of first column
column2 : name of second column
column3 : name of third column
When the developer start building an application, he needs to create database
tables.
This statement creates a new table with the given columns.
Example :
CREATE TABLE employee(
'id' INTEGER NOT NULL AUTO_INCREMENT,
'name' VARCHAR(30) NOT NULL,
'profile' VARCHAR(40) DEFAULT 'engineer',
PRIMARY KEY ('id')
)ENGINE = InnoDB;
Note : You have ‘id’ column as AUTO_INCREMENT with a primary key
constraint which ensures that each id is incremented value, avoiding
duplication. Storage engine selected is ‘InnoDB’ allowing foreign key
constraint and related transactions.
12. AUTO_INCREMENT
It is used to generate a unique identification field for new row.
13. DROP TABLE table_name
table_name : name of the table
This statement deletes the mentioned table.
14. RENAME TABLE old_table_name TO new_table_name
old_table_name : name of the previous table.
new_table_name : name of the new table.
This statement renames the table to a new name.
15. ALTER TABLE table_name ADD(column1, column2, column3..)
table_name : name of the existing table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
This statement adds columns to the existing table.
16. ALTER TABLE table_name DROP(column1)
table_name : name of the existing table.
column1 : name of first column.
This statement deletes specified columns from the existing table.
17. INSERT INTO table_name (column1, column2, column3 . . )
VALUES(value1, value2, value3 . . )
table_name : name of the existing table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
value1 : value for first column.
value2 : value for second column.
value3 : value for third column.
This statement inserts a new record into a table with specified values.
18. UPDATE table_name SET column1 = value1, column2 = value2, column3
= value3.. WHERE condition
table_name : name of the table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
value1 : value for first column.
value2 : value for second column.
value3 : value for third column.
condition : the condition statement.
This statement update records in the table with the new given values for the
columns.
Note : WHERE clause in MySQL queries is used to filter rows for a specific
condition.
19. DELETE FROM table_name WHERE condition
table_name : name of the table.
condition : the condition statement.
This statement deletes records from the table.
20. SELECT column1, column2, column3.. FROM table_name WHERE
condition
table_name : name of the table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
condition : the condition statement.
This statement executes and gives records from specific columns from the
table which matches the condition after WHERE clause.
21. SELECT * FROM table_name
table_name: name of the table.
Instead of specifying one column or many columns, you can use an asterisk (*)
which represents all columns of table. This query retrieves all records from
the table.
22. COUNT
The COUNT function is used to return total number of records matching a
condition from any table.
It is one of the known AGGREGATE function.
Example :
SELECT COUNT(*) from student;
Note: AGGREGATE functions allow you to run calculations on data and
provide information by using
a SELECT query.
23. MAX
It is used to get the maximum numeric value of a particular column of table.
Example :
SELECT MAX(marks) FROM student_report;
Note: The MIN and MAX functions work correctly on numeric as well as
alphabetic values.
24. MIN
It is used to get the minimum numeric value of a particular column of table.
Example :
SELECT MIN(marks) FROM student_report;
Note : The above given example queries can also be nested with each other
depending on the requirement.
Example :
SELECT MIN(marks)
FROM student_report
WHERE marks > ( SELECT MIN(marks) from student_report);
25. LIMIT
It is used to set the limit of number of records in result set.
Example :
SELECT *
FROM student limit 4, 10;
This gives 10 records starting from the 5th record.
26. BETWEEN
It is used to get records from the specified lower limit to upper limit.
This verifies if a value lies within that given range.
Example :
SELECT * FROM employee
WHERE age BETWEEN 25 AND 45.
27. DISTINCT
This is used to fetch all distinct records avoiding all duplicate ones.
Example :
SELECT DISTINCT profile
FROM employee;
28. IN clause
This verifies if a row is contained in a set of given values.
It is used instead of using so many OR clause in a query.
Example :
SELECT *
FROM employee
WHERE age IN(40, 50, 55);
29. AND
This condition in MySQL queries are used to filter the result data based on
AND conditions.
Example :
SELECT NAME, AGE
FROM student
WHERE marks > 95 AND grade = 7;
30. OR
This condition in MySQL queries are used to filter the result data based on OR
conditions.
Example :
SELECT *
FROM student
WHERE address = 'Hyderabad' OR address = 'Bangalore';
31. IS NULL
This keyword is used for boolean comparison or to check if the data value of a
column is null.
Example :
SELECT *
FROM employee
WHERE contact_number IS NULL;
32. FOREIGN KEY
It is used for pointing a PRIMARY KEY of another table.
Example :
CREATE TABLE Customers
(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
)

CREATE TABLE Orders


(
order_id INT AUTO_INCREMENT PRIMARY KEY,
FOREIGN KEY (id) REFERENCES Customers(id)
);
Note: This is not used in the MYISAM storage engine of MySQL server.
InnoDB storage engines supports foreign key constraints.
33. LIKE
This is used to fetch records matching for specified string pattern.
Example :
SELECT *
FROM employee
WHERE name LIKE 'Sh%';

SELECT *
FROM employee
WHERE name LIKE '%Sh%';
Note: Percentage signs (%) in the query represent zero or more characters.
34. JOINS
Joins are the joining of two or more database tables to fetch data based on a
common field.
There are various types of joins with different names in different databases.
Commonly known joins are self join, outer join, inner join and many more.
Regular Join :
It is the join which gets all the records from both the tables which exactly
match the given condition.
Example :
SELECT student.name, department.name
FROM student JOIN department ON student.department = department.name
Left Join :
It is the join which gets all the records that match the given condition, and
also fetch all the records from
the left table.
Example :
SELECT student.name, department.name
FROM student LEFT JOIN department ON student.deptartment =
department.name
Right Join :
It is the join which gets all the records that match the given condition, and
also fetch all the records from
the right table.
Example :
SELECT student.name, department.name
FROM student RIGHT JOIN department on student.department =
department.name
35. ADD or DROP a column
A new column can be added on a database table, if required later on.
Example :
ALTER TABLE employee ADD COLUMN salary VARCHAR(25);
Similarly, any column can be deleted from a database table.
Example :
ALTER TABLE employee DROP COLUMN salary;
Conclusion :
Running MySQL queries are the most commonly-performed tasks used to get
data within the process of database management. There are many database
management tools like phpMyAdmin, that helps to perform queries and
handle transactions comfortably with visual data results. You have scrolled
the most common MySQL queries, which are used in daily coding practices.
Developer can customize or enhance the queries with respect to a particular
requirement.
Introduction to NoSQL
NoSQL, or “Not Only SQL,” is a database management system (DBMS)
designed to handle large volumes of unstructured and semi-structured data.
Unlike traditional relational databases that use tables and pre-defined
schemas, NoSQL databases provide flexible data models and
support horizontal scalability, making them ideal for modern applications that
require real-time data processing.
Why Use NoSQL?
Unlike relational databases, which uses Structured Query Language, NoSQL
databases don’t have a universal query language. Instead, each type of
NoSQL database typically has its unique query language. Traditional relational
databases follow ACID (Atomicity, Consistency, Isolation,
Durability) principles, ensuring strong consistency and structured relationships
between data.
However, as applications evolved to handle big data, real-time analytics, and
distributed environments, NoSQL emerged as a solution with:
 Scalability – Can scale horizontally by adding more nodes instead of
upgrading a single machine.
 Flexibility – Supports unstructured or semi-structured data without a
rigid schema.
 High Performance – Optimized for fast read/write operations with
large datasets.
 Distributed Architecture – Designed for high availability and
partition tolerance in distributed systems.
Types of NoSQL Databases
NoSQL databases are generally classified into four main categories based on
how they store and retrieve data
1. Document databases
Store data in JSON, BSON, or XML format.
 Data is stored as documents that can contain varying attributes.
 Examples: MongoDB, CouchDB, Cloudant
 Ideal for content management systems, user profiles, and catalogs
where flexible schemas are needed.
2. Key-value stores
 Data is stored as key-value pairs, making retrieval extremely fast.
 Optimized for caching and session storage.
 Examples: Redis, Memcached, Amazon DynamoDB
 Perfect for applications requiring session management, real-time
data caching, and leaderboards.
3. Column-family stores
 Data is stored in columns rather than rows, enabling high-speed
analytics and distributed computing.
 Efficient for handling large-scale data with high write/read
demands.
 Examples: Apache Cassandra, HBase, Google Bigtable
 Great for time-series data, IoT applications, and big data analytics.
4. Graph databases
 Data is stored as nodes and edges, enabling complex relationship
management.
 Best suited for social networks, fraud detection, and
recommendation engines.
 Examples: Neo4j, Amazon Neptune, ArangoDB
 Useful for applications requiring relationship-based queries such as
fraud detection and social network analysis.
Key Features of NoSQL Databases
1. Dynamic schema: NoSQL databases do not have a fixed schema and
can accommodate changing data structures without the need for
migrations or schema alterations.
2. Horizontal scalability: NoSQL databases are designed to scale out
by adding more nodes to a database cluster, making them well-
suited for handling large amounts of data and high levels of traffic.
3. Document-based: Some NoSQL databases, such as MongoDB, use a
document-based data model, where data is stored in a schema-less
semi-structured format, such as JSON or BSON.
4. Key-value-based: Other NoSQL databases, such as Redis, use a key-
value data model, where data is stored as a collection of key-value
pairs.
5. Column-based: Some NoSQL databases, such as Cassandra, use a
column-based data model, where data is organized into columns
instead of rows.
6. Distributed and high availability: NoSQL databases are often
designed to be highly available and to automatically handle node
failures and data replication across multiple nodes in a database
cluster.
7. Flexibility: NoSQL databases allow developers to store and retrieve
data in a flexible and dynamic manner, with support for multiple data
types and changing data structures.
8. Performance: NoSQL databases are optimized for high performance
and can handle a high volume of reads and writes, making them
suitable for big data and real-time applications.
Advantages of NoSQL
There are many advantages of working with NoSQL databases such as
MongoDB and Cassandra. The main advantages are high scalability and high
availability.
1. High scalability: NoSQL databases use sharding for horizontal
scaling. Partitioning of data and placing it on multiple machines in
such a way that the order of the data is preserved is sharding.
Vertical scaling means adding more resources to the existing
machine whereas horizontal scaling means adding more machines to
handle the data. Vertical scaling is not that easy to implement but
horizontal scaling is easy to implement. Examples of horizontal
scaling databases are MongoDB, Cassandra, etc. NoSQL can handle
a huge amount of data because of scalability, as the data grows
NoSQL scalesThe auto itself to handle that data in an efficient
manner.
2. Flexibility: NoSQL databases are designed to handle unstructured or
semi-structured data, which means that they can accommodate
dynamic changes to the data model. This makes NoSQL databases a
good fit for applications that need to handle changing data
requirements.
3. High availability: The auto, replication feature in NoSQL databases
makes it highly available because in case of any failure data
replicates itself to the previous consistent state.
4. Scalability: NoSQL databases are highly scalable, which means that
they can handle large amounts of data and traffic with ease. This
makes them a good fit for applications that need to handle large
amounts of data or traffic
5. Performance: NoSQL databases are designed to handle large
amounts of data and traffic, which means that they can offer
improved performance compared to traditional relational databases.
6. Cost-effectiveness: NoSQL databases are often more cost-effective
than traditional relational databases, as they are typically less
complex and do not require expensive hardware or software.
7. Agility: Ideal for agile development.
Disadvantages of NoSQL
1. Lack of standardization: There are many different types of NoSQL
databases, each with its own unique strengths and weaknesses. This
lack of standardization can make it difficult to choose the right
database for a specific application
2. Lack of ACID compliance: NoSQL databases are not fully ACID-
compliant, which means that they do not guarantee the consistency,
integrity, and durability of data. This can be a drawback for
applications that require strong data consistency guarantees.
3. Narrow focus: NoSQL databases have a very narrow focus as it is
mainly designed for storage but it provides very little functionality.
Relational databases are a better choice in the field of Transaction
Management than NoSQL.
4. Open-source: NoSQL is an databaseopen-source database. There is
no reliable standard for NoSQL yet. In other words, two database
systems are likely to be unequal.
5. Lack of support for complex queries: NoSQL databases are not
designed to handle complex queries, which means that they are not a
good fit for applications that require complex data analysis or
reporting.
6. Lack of maturity: NoSQL databases are relatively new and lack the
maturity of traditional relational databases. This can make them less
reliable and less secure than traditional databases.
7. Management challenge: The purpose of big data tools is to make the
management of a large amount of data as simple as possible. But it is
not so easy. Data management in NoSQL is much more complex than
in a relational database. NoSQL, in particular, has a reputation for
being challenging to install and even more hectic to manage on a
daily basis.
8. GUI is not available: GUI mode tools to access the database are not
flexibly available in the market.
9. Backup: Backup is a great weak point for some NoSQL databases like
MongoDB. MongoDB has no approach for the backup of data in a
consistent manner.
10. Large document size: Some database systems like MongoDB and
CouchDB store data in JSON format. This means that documents are
quite large (BigData, network bandwidth, speed), and having
descriptive key names actually hurts since they increase the
document size.
SQL vs. NoSQL: A Comparison
Feature SQL (Relational DB) NoSQL (Non-Relational DB)

Flexible (Documents, Key-Value,


Data Model Structured, Tabular
Graphs)

Scalability Vertical Scaling Horizontal Scaling

Schema Predefined Dynamic & Schema-less

ACID
Strong Limited or Eventual Consistency
Support

Transactional
Best For Big data, real-time analytics
applications

MySQL, PostgreSQL,
Examples MongoDB, Cassandra, Redis
Oracle

When to Use NoSQL


Use a NoSQL database when:
 Data is unstructured or semi-structured and needs a flexible schema.
 We require high scalability and must handle large datasets.
 Performance is critical for real-time applications.
 The application needs to handle distributed workloads efficiently.
 We don’t require strict ACID transactions, but prioritize availability
and speed
Popular NoSQL Databases & Their Use Cases
NoSQL
Database Type Use Cases

MongoDB Document-based Content management, product catalogs

Caching, real-time analytics, session


Redis Key-Value Store
storage

Column-Family
Cassandra Big data, high availability systems
Store
NoSQL
Database Type Use Cases

Neo4j Graph Database Fraud detection, social networks

Conclusion
NoSQL databases provide a flexible, scalable, and high-
performance alternative to traditional relational databases, making them ideal
for modern applications like real-time analytics, big data processing, and web
applications. However, they come with trade-offs, such as a lack of ACID
compliance and more complex management. When choosing a database for
your application, it’s essential to evaluate your data needs, consistency
requirements, and scalability goals to determine whether NoSQL or a relational
database is the best fit.

Introduction of NewSQL | Set 2


 The term NewSQL is not exactly as wide as NoSQL. NewSQL
systems all begin with the relational data model and the SQL query
language and they all attempt to cover portion of similar types of
scalability, flexibility or lack-of-focus that has driven the NoSQL
development. Many offer more grounded consistency guarantees.
 However, inside this group there are numerous distinctions. HANA
was made to be a business reporting system which could handle a
transactional load a perfect fit for deployment of SAP. In traditional
Microsoft SQL server in-memory processing ability is added by
Hekaton. Both the systems are designed in order to improve the
OldSQL systems directly.
 NuoDB is first cluster based SQL database, which runs on multiple
nodes over various datacenters and make underlying system manage
data consistency and locality for you This comes at a cost in
performance and consistency for arbitrary workloads. NuoDB is the
closest to being called eventually consistent of the NewSQL systems.
 MemSQL focus on the clustered analytics, MemSQL provide faster
analysis of OLAP as compared to Old SQL systems.
 VoltDB is most stable database system among these systems, which
combines analysis of streaming data, native clustering and strong
ACID guarantees. This permit VoltDB to be the system of record for
the applications which are data intensive, while providing combine
high throughput, low latency ingestion engine.
 Possibly you have huge amount of data which require high speed
transactional access You have incoming data stream and require
transactions to calculate responses and analysis in real time. The
data analysis and decision making must be computed me request in
batch processing scenario. In such case NewSQL systems become
useful.
The NewSQL Advantages
 Less complex applications, greater consistency.
 Convenient standard tooling.
 SQL influenced extensions.
 More traditional data and query models for NoSQL-style clustering.
The NewSQL Disadvantages
 Less generalized as current SQL.
 For terabytes, memory architectures are inefficient.
 Access to the rich tooling of current SQL systems is rational.

Difference between NoSQL and NewSQL


1. NoSQL :
The term NoSQL is categorizing databases as descriptive as ” No-SQL “.
NoSQL is a comprehensive category of databases that are developed to
overcome the problems generated by SQL databases. They are referred to as
schema less documents which store the data in documents, graph, key-value,
and non-ordered fashion.
Advantages of NoSQL :
 They scale better than traditional systems when there is a need for
dynamic behavior.
 These systems are better optimized for non-relational data.
 Allows performing schema-on-write operations.

Disadvantages of NoSQL :
 The system built with NoSQL is fundamentally non-transactional.
 The volume of data created is huge and does not offer any traditional
database capability.
 It does not follow consistency when multiple transactions are
performed simultaneously.
2. NewSQL :
The term NewSQL categorizes databases that are the combination of
relational model with the advancement in scalability, flexibility with types of
data. These databases focus on the features which are not present in NoSQL,
which offers a strong consistency guarantee. This covers two layers of data
one relational one and a key-value store.
Advantages of NewSQL :
 It introduces new implementation to traditional relational databases.
 It brings together the advantages of SQL and NoSQL.
 It is easy to migrate between the type and needs of the user.

Disadvantages of NewSQL :
 They offer partial access to rich traditional systems.
 It may cause a problem in-memory architecture for exceeding
volumes of data.
 The core foundation of such databases is relational systems which
make it tricky to understand.
Difference between NoSQL and NewSQL :
S.No NoSQL NewSQL

NewSQL is schema-fixed as well as a


1. NoSQL is a schema-free database.
schema-free database.

2. It is horizontally scalable. It is horizontally scalable.

It possesses automatically high-


3. It possesses built-in high availability.
availability.

It supports cloud, on-disk, and cache It fully supports cloud, on-disk, and
4.
storage. cache storage.

5. It promotes CAP properties. It promotes ACID properties.

Online Transactional Processing is not Online Transactional Processing is fully


6.
supported. supported.

7. There are low-security concerns. There are moderate security concerns.

Use Cases: Big Data, Social Network Use Cases: E-Commerce, Telecom
8.
Applications, and IOT. industry, and Gaming.

Examples : DynamoDB, MongoDB, Examples : VoltDB, CockroachDB,


9.
RaveenDB etc. NuoDB etc.
SQL INSERT INTO Statement
The SQL INSERT INTO statement is one of the most commonly used commands
for adding new data into a table in a database. Whether you’re working with
customer data, products, or user details, mastering this command is crucial for
efficient database management. Let’s break down how this command works,
how to use it, and some advanced techniques to boost your productivity when
inserting data.
What is SQL INSERT INTO Statement?
The SQL INSERT INTO statement is used to add new rows of data to a table in a
database. It’s one of the core commands in SQL and is commonly used to
populate tables with data. There are two main ways to use the INSERT
INTO statement by specifying the columns and values explicitly or by inserting
values for all columns without specifying them. The method you choose
depends on whether you want to insert data into every column or just a subset
of columns in the table.
1. Inserting Data into All Columns (Simple Method)
This method is used when you want to insert data into all columns of a table
without specifying column names. We simply provide the values for each
column, in the same order that the columns are defined in the table.
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value);
Parameters:
 table_name: The name of the table where the data will be inserted
 value1, value2: The values you want to insert into the respective
columns of the table
Example:
For better understanding, let’s look at the SQL INSERT INTO statement with
examples. Let us first create a table named ‘Student‘.
CREATE DATABASE StudentDB;
USE StudentDB;

CREATE TABLE Student (


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

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


(1, 'Ram', 'Delhi', 'XXXXXXXXXX', 18),
(2, 'Ramesh', 'Gurgaon', 'XXXXXXXXXX', 18),
(3, 'Sujit', 'Rohtak', 'XXXXXXXXXX', 20),
(4, 'Suresh', 'Rohtak', 'XXXXXXXXXX', 18);
Output
ROLL_NO NAME ADDRESS PHONE AGE

1 Ram Delhi xxxxxxxxxxxxxx 18

2 RAMESH GURGAON xxxxxxxxxxxxxx 18

3 SUJIT ROHTAK xxxxxxxxxxxxxx 20

4 SURESH ROHTAK xxxxxxxxxxxxxx 18

3 SUJIT ROHTAK xxxxxxxxxxxxxx 20

2 RAMESH GURGAON xxxxxxxxxxxxxx 18

If we don’t want to specify the column names (and you’re inserting data into all
columns), we can directly insert values in the order they appear in the table
structure. Here’s an example:
Query:
INSERT INTO Student
VALUES ('5','HARSH','WEST BENGAL', 'XXXXXXXXXX','19');
Output
ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi XXXXXXXXXX 18

2 RAMESH GURGAON XXXXXXXXXX 18

3 SUJIT ROHTAK XXXXXXXXXX 20

4 SURESH Delhi XXXXXXXXXX 18

3 SUJIT ROHTAK XXXXXXXXXX 20

2 RAMESH GURGAON XXXXXXXXXX 18


ROLL_NO NAME ADDRESS PHONE Age

5 HARSH WEST BENGAL XXXXXXXXXX 19

2. Inserting Data into Specific Columns (Flexible


Method)
In some cases, you might want to insert data into only certain columns, leaving
the others empty or with default values. In such cases, we can specify the
column names explicitly.
Syntax
INSERT INTO table_name (column1, column2, column3)
VALUES ( value1, value2, value);
Parameters:
 table_name: name of the table.
 column1, column2..: name of first column, second column.
 value1, value2, value..: the values for each specified column of the
new record.
Example :
Let’s say we only want to insert the student’s ID, name, and age into
the Students table, and leave the address and phone number as NULL (the
default value).
INSERT INTO Student (ROLL_NO, NAME, Age)
VALUES ('5', "PRATIK", 19');
Output:
ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi XXXXXXXXXX 18

2 RAMESH GURGAON XXXXXXXXXX 18

3 SUJIT ROHTAK XXXXXXXXXX 20

4 SURESH Delhi XXXXXXXXXX 18

3 SUJIT ROHTAK XXXXXXXXXX 20

2 RAMESH GURGAON XXXXXXXXXX 18


ROLL_NO NAME ADDRESS PHONE Age

5 PRATIK null null 19

Note: Columns not included in the INSERT statement are filled with default
values (typically NULL).
Inserting Multiple Rows at Once
Instead of running multiple INSERT INTO commands, you can insert multiple
rows into a table in a single query. This is more efficient and reduces the number
of database operations.
Syntax
INSERT INTO table_name (column1, column2, …)
VALUES
(value1, value2, …),
(value1, value2, …),
(value1, value2, …);

Example:
If we want to add multiple students to the Students table in one go, the query
would look like this:
INSERT INTO Student (ROLL_NO, NAME, AGE, ADDRESS, PHONE)
VALUES
(6, 'Amit Kumar', 15, 'Delhi', 'XXXXXXXXXX'),
(7, 'Gauri Rao', 18, 'Bangalore', 'XXXXXXXXXX'),
(8, 'Manav Bhatt', 17, 'New Delhi', 'XXXXXXXXXX'),
(9, 'Riya Kapoor', 10, 'Udaipur', 'XXXXXXXXXX');
Output:
ROLL_NO NAME ADDRESS PHONE AGE

1 Ram Delhi XXXXXXXXXX 18

2 Ramesh Gurgaon XXXXXXXXXX 18

3 Sujit Rohtak XXXXXXXXXX 20

4 Suresh Rohtak XXXXXXXXXX 18

5 Pratik NULL NULL 19

6 Amit Kumar Delhi XXXXXXXXXX 15


ROLL_NO NAME ADDRESS PHONE AGE

7 Gauri Rao Bangalore XXXXXXXXXX 18

8 Manav Bhatt New Delhi XXXXXXXXXX 17

9 Riya Kapoor Udaipur XXXXXXXXXX 10

Explanation:
 This method is faster than running multiple individual INSERT
INTO commands.
 If you’re inserting more than 1000 rows, consider using bulk insert or
multiple insert statements for efficiency.
Inserting Data from One Table into Another Table
We can also copy data from one table into another table using the INSERT INTO
SELECT statement. This is very useful when we want to move or replicate data
from one table to another without manually typing all the data.
Syntax 1: Insert All Columns from Another Table
INSERT INTO target_table
SELECT * FROM source_table;
Example: If you want to copy all data from the OldStudents table into
the Students table, use this query:
INSERT INTO Students
SELECT * FROM OldStudents;
Syntax 2: Insert Specific Columns from Another Table
INSERT INTO target_table (col1, col2, …)
SELECT col1, col2, …
FROM source_table;
Example: Let’s say we want to copy only the Name and Age columns
from OldStudents into Students:
INSERT INTO Students (Name, Age)
SELECT Name, Age
FROM OldStudents;
Syntax 3: Insert Specific Rows Based on Condition
You can also insert specific rows based on a condition by using
the WHERE clause with the SELECT statement.
INSERT INTO target_table
SELECT * FROM source_table
WHERE condition;
Example: If we want to copy only students older than 20 years
from OldStudents to Students, we would write:
INSERT INTO Students
SELECT * FROM OldStudents
WHERE Age > 20;
Important Points About SQL INSERT INTO Statement
 Multiple Inserts: You can insert multiple rows at once by separating
each set of values with commas. This reduces the number of queries
you need to run.
 NULL Values: If you don’t insert data into a column, it will typically
be set to NULL unless the column has a default value.
 Order of Columns: When using the simple INSERT INTO syntax
without specifying column names, the values must be in the exact
same order as the columns are defined in the table.
 Default Values: Columns not mentioned in the INSERT
INTO statement will be filled with their default values (often NULL).
 Efficiency: Inserting multiple rows at once is much more efficient
than doing it one by one.
Conclusion
Overall, INSERT INTO statement is an essential feature in SQL for adding new
data to tables. Whether you’re adding a single row or multiple rows, specifying
column names or copying data from another table, INSERT INTO provides the
necessary flexibility. Understanding its syntax and usage is crucial for efficient
database management and data manipulation.

SQL DELETE Statement


The SQL DELETE statement is one of the most commonly used commands in
SQL (Structured Query Language). It allows you to remove one or more rows
from the table depending on the situation. Unlike the DROP statement, which
removes the entire table, the DELETE statement removes data (rows) from the
table retaining only the table structure, constraints, and schema
In this article, we’ll learn the syntax and usage of the SQL DELETE statement
with detailed examples, including how to delete a single record, delete
multiple records, and delete all records from a table.
SQL DELETE Statement
The SQL DELETE statement removes one or more rows from a database table
based on a condition specified in the WHERE clause. It’s a DML (Data
Manipulation Language) operation that modifies the data within the table
without altering its structure.
Syntax:
DELETE FROM table_name
WHERE some_condition;
Parameter Explanation
 Some_condition: condition to choose a particular record.
 table_name: name of the table
Note: We can delete single as well as multiple records depending on the
condition we provide in the WHERE clause. If we omit the WHERE clause then
all of the records will be deleted and the table will be empty.
The sample table is as follows GFG_Employees:
Examples of SQL DELETE Statement
Assume we have created a table named GFG_Employee in SQL which
contains the personal details of the Employee including their id, name, email
and department etc. as shown below −
CREATE TABLE GFG_Employees (
id INT PRIMARY KEY,
name VARCHAR (20) ,
email VARCHAR (25),
department VARCHAR(20)
);
INSERT INTO GFG_Employees (id, name, email, department) VALUES
(1, 'Jessie', '[email protected]', 'Development'),
(2, 'Praveen', '[email protected]', 'HR'),
(3, 'Bisa', '[email protected]', 'Sales'),
(4, 'Rithvik', '[email protected]', 'IT'),
(5, 'Suraj', '[email protected]', 'Quality Assurance'),
(6, 'Om', '[email protected]', 'IT'),
(7, 'Naruto', '[email protected]', 'Development');
Select * From GFG_Employees
Output

GFG_Employees

Example 1: Deleting Single Record


We can use the DELETE statement with a condition to delete a specific row
from a table. The WHERE clause ensures only the intended record is removed.
We can delete the records named Rithvik by using the below query:
Query:
DELETE FROM GFG_Employees WHERE NAME = 'Rithvik';
Output:

Example 2: Deleting Multiple Records


Delete the rows from the table GFG_Employees where the department is
“Development”. This will delete 2 rows(the first row and the seventh row).
Query
DELETE FROM GFG_Employees
WHERE department = 'Development';
Output
output

Example 3: Delete All of the Records


To remove all the entries from the table, you can use the following query:
Query:
DELETE FROM GFG_EMPLOyees;
Or
DELETE * FROM GFG_EMPLOyees;
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.

output

Rolling Back DELETE Operations


Since the DELETE statement is a DML operation, it can be rolled back when
executed in a statement. If you accidentally delete records or need to repeat
the process, you can use the ROLLBACK command.
Query:
START TRANSACTION;
DELETE FROM GFG_Employees WHERE department = 'Development';
-- If needed, you can rollback the deletion
ROLLBACK;
Best Practices for Using SQL DELETE
 Use Transactions: Wrap DELETE statements in transactions to
provide an option to roll back changes if necessary.
 Always Use a WHERE Clause: Avoid deleting all rows by accident.
Always filter records using a WHERE clause to specify which rows to
delete.
 Backup Data: Before performing large deletions, ensure that you
have a backup of the data to avoid irreversible loss.
 Test on Development Server: Always test your DELETE queries on a
development or staging environment to ensure they produce the
desired result.
 Optimize Deletions: For large datasets, delete records in batches to
reduce performance impact.
Conclusion
The SQL DELETE statement is a powerful tool for removing data from a
database table based on specific conditions. By understanding the correct
syntax, how to delete individual or multiple records, and how to handle
performance issues, you can use the DELETE statement efficiently and safely.
SQL UPDATE Statement
n SQL, the UPDATE statement is used to modify existing records in a table.
Whether you are updating a single record or multiple records at once, SQL
provides the necessary functionality to make these changes. Whether you are
working with a small dataset or handling large-scale databases,
the UPDATE statement plays a crucial role in maintaining the integrity of your
data
In this article, we will cover the fundamentals of the UPDATE statement,
including its syntax, basic usage, and advanced techniques. We will also
explore common pitfalls, optimization tips, and real-world examples to ensure
you can use the UPDATE statement effectively in your SQL queries.
What is SQL UPDATE Statement?
The UPDATE statement in SQL is used to modify the data of an existing record
in a database table. We can update single or multiple columns in a single query
using the UPDATE statement as per our requirement. Whether you need to
correct data, change values based on certain conditions, or update multiple
fields simultaneously, the UPDATE statement provides a simple yet effective way
to perform these operations.
key points about UPDATE statement
1. Modify Specific Data: The UPDATE statement can be used to change
specific data in one or more columns for rows that meet a certain
condition.
2. Target Specific Rows: You can control which rows to update by
using the WHERE clause. If you omit the WHERE clause, all rows in the
table will be updated, so it’s important to use this clause carefully to
avoid unintended changes.
3. Single or Multiple Columns: The UPDATE statement allows you to
modify one or more columns at a time. This makes it versatile when
you need to update multiple pieces of information for the same
record.
4. Efficiency: Using UPDATE is more efficient than deleting and re-
inserting data because it directly modifies the existing record without
affecting other rows in the table.
5. Data Integrity: The UPDATE statement helps maintain data integrity by
allowing you to fix errors or modify data without needing to remove
and re-add records, ensuring that related data remains consistent.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,…
WHERE condition;

Parameters
 UPDATE: The SQL command used to modify the data in a table.
 SET: This clause defines which columns will be updated and what
their new values will be.
 WHERE: The condition that determines which rows will be updated.
Without it, all rows will be affected.
 table_name: name of the table in which you want to make updates
 column1, column2, …: The columns you want to update.
 value1, value2, …: The new values to assign to these columns.
 condition: Specifies which rows to update. This condition is crucial, as
omitting it will update all rows in the table.
Note: In the above query the SET statement is used to set new values to the
particular column and the WHERE clause is used to select the rows for which
the columns are needed to be updated. If we have not used the WHERE clause
then the columns in all the rows will be updated. So the WHERE clause is used
to choose the particular rows.
Examples of SQL UPDATE Statement
Let’s start by creating a table and inserting some sample data, which we will
use for the UPDATE statement examples. The Customer table stores information
about individual customers, including their unique CustomerID, personal details
like CustomerName and LastName, as well as their contact details such
as Phone and Country.
Query:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age,
Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain',
'Spain','22','xxxxxxxxxx');
Output

Example 1: Update Single Column Using UPDATE Statement


We have a Customer table, and we want to Update the CustomerName where
the Age is 22.
Query:
UPDATE Customer
SET CustomerName = 'Nitin'
WHERE Age = 22;
Output:

Explanation: Only the rows where Age is 22 will be updated, and


the CustomerName will be set to ‘Nitin’.
Example 2: Updating Multiple Columns using UPDATE Statement
We need to update both the CustomerName and Country for a
specific CustomerID.
Query:
UPDATE Customer
SET CustomerName = 'Satyam',
Country = 'USA'
WHERE CustomerID = 1;
Output:

Explanation: For the row where CustomerID is 1,


both CustomerName and Country will be updated simultaneously.
Note: For updating multiple columns we have used comma(,) to separate the
names and values of two columns.
Example 3: Omitting WHERE Clause in UPDATE Statement
If we accidentally omit the WHERE clause, all the rows in the table will be
updated, which is a common mistake. Let’s update the CustomerName for every
record in the table:
Query:
UPDATE Customer
SET CustomerName = 'Shubham';
Output

Explanation: This will set the CustomerName for every row in the Customer table
to ‘Shubham‘. Be careful while omitting the WHERE clause, as this action is
irreversible unless you have a backup.
Optimizing Your SQL UPDATE Queries
 Avoid frequent updates: Constantly updating rows can slow down
performance. Batch updates or consider using a database trigger to
handle automatic updates.
 Index relevant columns: Ensure that columns in the WHERE clause
(such as CustomerID) are indexed. This will improve the speed of the
update operation.
Important Points About SQL UPDATE Statement
1. Always use the WHERE clause: The most important point when using
the UPDATE statement is to always include a WHERE clause unless you genuinely
intend to update all rows.
2. Check your data before updating: Run a SELECT query to view the data you
want to update before executing the UPDATE statement. This helps avoid
accidental data modifications.
SELECT * FROM Customer WHERE Age = 22;
3. Use transactions for critical updates: When performing updates in a
production environment, consider using transactions. Transactions allow you to
commit or roll back changes as needed.
BEGIN TRANSACTION;
UPDATE Customer SET CustomerName = 'John' WHERE CustomerID = 3;
COMMIT; -- Use ROLLBACK to undo if necessary
4. Test on a small dataset first: If you’re uncertain about the impact of
your UPDATE, test it on a small subset of data to ensure the changes are as
expected.
Conclusion
The SQL UPDATE statement is use for modifying existing data in
your database. Whether you’re performing simple updates or handling complex
logic with subqueries, joins, and case expressions, SQL provides all the
flexibility we need. By understanding the basic syntax, advanced techniques,
and common pitfalls, we can ensure that our UPDATE queries are both
efficient and error-free. By following best practices and paying attention to
details, you can safely and effectively perform updates in your database.

SQL CREATE TABLE


In SQL, creating a table is one of the most essential tasks for structuring your
database. The CREATE TABLE statement defines the structure of the database
table, specifying column names, data types, and constraints such as PRIMARY
KEY, NOT NULL, and CHECK. Mastering this statement is fundamental to
ensuring that our data is organized and easily accessible.
What is the SQL CREATE TABLE Statement?
The CREATE TABLE command in SQL is used to define a new table within a
database. A table’s structure, including column names, data types, and
constraints like NOT NULL, PRIMARY KEY, and CHECK, are defined when it is
created in SQL.
Whether we are creating tables for storing customer information, product
catalogs, or employee records, the CREATE TABLE statement is our starting
point. The CREATE TABLE command is a crucial tool for database
administration because of these limitations, which help in ensuring data
integrity.
Syntax:
CREATE table table_name
(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);
Key Terms
 table_name: The name you assign to the new table.
 column1, column2, … : The names of the columns in the table.
 datatype(size): Defines the data type and size of each column.

Practical Example: Creating a Table in SQL


Let’s walk through a practical example where we create a Customer table that
stores customer data. We will define various columns such
as CustomerID, CustomerName, Country, Age, and Phone with appropriate
data types and constraints.
Query:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT CHECK (Age >= 0 AND Age <= 99),
Phone int(10)
);
Output:
Explanation of the Example:
 CustomerID is an integer and serves as the PRIMARY KEY, ensuring
each record is unique.
 CustomerName, LastName, and Country are VARCHAR fields to
store variable-length text.
 Age has a CHECK constraint, ensuring it’s within the range of 0 to
99.
 Phone is an integer field, although in real scenarios,
a VARCHAR would often be used for storing phone numbers to
allow for leading zeros and formatting.
Inserting Data into the Newly Created Table
After creating the table, you can use INSERT INTO command to add data into
it. Here’s how to add some sample records into the Customer table:
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age,
Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain',
'Spain','22','xxxxxxxxxx');
Output:

Note: If you’re working with a large amount of data, consider using bulk
inserts or importing data from external files to optimize performance.
Create Table From Another Table
We can also create a new table based on the structure (and optionally the data)
of an existing table. The CREATE TABLE AS SELECT command allows us to
duplicate an entire table or select specific columns to form a new one. The
following query creates a new table called SubTable that
contains CustomerID and CustomerName from the existing Customer table.
Syntax:
CREATE TABLE new_table_name AS
SELECT column1, column2,…
FROM existing_table_name
WHERE ….;
In this example, we create a new table SubTable that contains just
the CustomerID and CustomerName columns from the Customer table. This
method is useful for creating backups or performing quick data migrations.
Query:
CREATE TABLE SubTable AS
SELECT CustomerID, CustomerName
FROM customer;
Output:

Note: We can use * instead of column name to copy whole table to another
table.
Important Points About SQL CREATE TABLE Statement
To ensure the smooth creation and management of your tables, keep these
points in mind:
1. Adding Constraints: The CREATE TABLE statement can also define
constraints like NOT NULL, UNIQUE, and DEFAULT. Example: Age INT NOT
NULL
2. Handling Table Existence: If you attempt to create a table that already
exists, SQL will throw an error. To avoid this, you can use the IF NOT
EXISTS clause.
CREATE TABLE IF NOT EXISTS Customer (...);
3. Data Types and Sizes: Always define appropriate data types for each
column (e.g., VARCHAR(50) for names and INT for IDs) to optimize performance
and storage.
4. Viewing Table Structure: After creating a table, use the following command
to view the structure of your table:
DESC table_name;
5. Modifying Table Structure: If you need to change the table’s structure after
creation (e.g., renaming a column, adding a new column), use the ALTER
TABLE statement.
Conclusion
The SQL CREATE TABLE statement is essential for setting up tables and
defining data structures within a database. Knowing how to create a table
in SQL with the CREATE TABLE SQL syntax helps you establish reliable tables
with appropriate constraints. Whether you’re creating an Employee table in
SQL with primary keys or duplicating tables with CREATE TABLE AS SELECT,
mastering this command is vital for managing data effectively.
In this guide, we covered SQL CREATE TABLE syntax with various examples,
from basic to advanced usage. By applying these practices, you can confidently
build tables in SQL for effective data organization and retrieval.
DROP and TRUNCATE in SQL
The DROP and TRUNCATE commands in SQL are used to remove data from a
table, but they work differently. Understanding the difference between these
two commands is important for proper database management, especially
when dealing with large amounts of data.
This article provides an in-depth explanation of the DROP and
TRUNCATE commands in SQL, their main differences, usage, and detailed
examples. By the end of this article, We will be ready to use these commands
effectively and understand their impact on your database.
What is the SQL DROP Command?
In SQL, the DROP command is used to permanently remove an object from a
database, such as a table, database, index, or view. When we DROP a table,
both the data and the structure of the object are permanently removed from the
database leaving no trace of the object.
Syntax:
DROP object object_name ;
Key Terms
 object: The type of object you want to drop (e.g., TABLE,
DATABASE).
 object_name: The name of the object to be deleted.
DROP Command Examples
Let’s look at some examples of the DROP statement in SQL.
1. DROP Table
To delete an entire table, including its data and structure:
Syntax:
DROP TABLE table_name;

2. DROP database
To delete an entire database and all of its associated tables:
Syntax:
DROP DATABASE database_name;

What is SQL TRUNCATE Command?


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

Key Differences Between DROP and TRUNCATE


The key differences between DROP and TRUNCATE statements are explained
in the following table:
Feature DROP TRUNCATE

Effect on Table Completely removes both the Removes all rows but
Structure data and the table structure preserves the table structure

Deletes both data and table Deletes only the data, not the
Data Deletion
definition table structure

Non-recoverable; once
Can be rolled back if used in
dropped, the table cannot be
Recovery a transaction (if supported by
restored (unless you have
the DBMS)
backups)
Feature DROP TRUNCATE

Does not activate triggers Does not activate DELETE


Triggers
associated with the table triggers

Slower due to data and Faster, especially for large


Performance
structural removal datasets

Used when you want to Used to quickly remove all


Usage completely remove a table or rows from a table but keep
database the structure for future use

Examples of SQL DROP AND TRUNCATE Command


Let’s look at some examples of the DROP and TRUNCATE statements in SQL
and understand their working. Consider the given database Student_data We
will perform the examples on this particular table.

Student Table

DROP Database Example


In this example, we will drop a database called student_data:
DROP DATABASE student_data;
Running this query will completely delete the student_data database,
including all tables and data.
DROP Table Example
In this example, we will drop the student_details table;
DROP TABLE student_details;
This query will permanently remove the student_details table, along with all
its data, from the database.
TRUNCATE Table Example
In this example, we will truncate all data from a table (e.g., student_details)
while keeping the table structure intact:
TRUNCATE TABLE Student_details;
After running the above query Student_details table will be truncated, i.e, the
data will be deleted but the structure will remain in the memory for further
operations.
Important Points About SQL DROP & TRUNCATE
Command
SQL DROP Command:
 Completely removes a table or database from the database,
including the data and structure.
 Is a permanent operation and cannot be rolled back.
 Removes integrity constraints and indexes associated with the table.
 Is slower compared to the TRUNCATE statement.
SQL TRUNCATE Command:
 Removes all the rows or data from a table, but preserves the table
structure and columns.
 Is a faster operation compared to the DROP statement.
 Resets the identity column (if any) back to its seed value.
 Does not remove integrity constraints associated with the table.

SQL DROP and TRUNCATE Command Examples


Read More: Differences between DROP and TRUNCATE Commands

Conclusion
In SQL, both DROP and TRUNCATE commands are used for removing data,
but their impacts are different. DROP is used when you want to completely
remove a table or database, while TRUNCATE is more efficient for removing all
rows from a table without affecting its structure. Understanding when and how
to use these commands will help you maintain better control over your
database and optimize your database management processes.

SQL ALTER TABLE


The SQL ALTER TABLE statement is a powerful tool that allows you
to modify the structure of an existing table in a database. Whether you’re
adding new columns, modifying existing ones, deleting columns, or renaming
them, the ALTER TABLE statement enables you to make changes without
losing the data stored in the table.
In this article will learn about the ALTER TABLE statement with examples to
demonstrate how it works.
SQL ALTER TABLE STATEMENT
The ALTER TABLE statement in SQL is used to modify an existing table
structure in a database without losing any data. It allows you to add, remove,
or modify columns, change data types, or apply constraints to improve data
integrity and ensure that the table meets evolving business requirements. It
allows for structural changes like adding new columns, modifying existing
ones, deleting columns, and renaming columns within a table.
To alter/modify the table use the ALTER TABLE syntax:
Syntax:
ALTER TABLE table_name
[ADD | DROP | MODIFY] column_name datatype;
Key Terms
 table_name refers to the name of the table you want to modify.
 ADD is used to add a new column.
 DROP is used to remove an existing column.
 MODIFY is used to change the datatype or definition of an existing
column.
Common Use Cases for SQL ALTER TABLE
1. ADD – To add a new column to the table
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.
Query:
ALTER TABLE table_name
ADD column_name datatype;
2. MODIFY/ALTER – To change the data type of an existing column
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.
Query:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
3. DROP – To delete an existing column from the table
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;
4. RENAME COLUMN – To rename an existing column
We can rename an existing column using the RENAME COLUMN clause. This
allows you to change the name of a column while preserving its data type and
content.
Query:
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
5. RENAME TO – To rename the table itself
We can rename an entire table using the RENAME TO clause. This changes
the name of the table while preserving its structure and data.
ALTER TABLE table_name
RENAME TO new_table_name;
SQL ALTER TABLE Examples
Below are various examples demonstrating different use cases of the ALTER
TABLE statement in SQL. These examples showcase how to add, modify, drop,
and rename columns or tables, providing a clear understanding of the flexibility
and utility of the ALTER TABLE statement.
1. Adding a New Column to a Table
To add a new column to an existing table, you can use the ADD clause. Here’s
an example where we add a column named email to the employee table:
ALTER TABLE Students
ADD Email varchar(255);
2. Removing a Column from a Table
We can remove an existing column from a table using the DROP COLUMN clause.
Here’s an example where we remove the phone_number column from
the employee table:
ALTER TABLE Students
DROP COLUMN Email;
3. Modifying an Existing Column’s Data Type
To change the data type or size of an existing column, you can use
the MODIFY clause. For instance, if you want to change the data type of
the salary column from INT to DECIMAL, you can use:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
SQL ALTER TABLE Queries
Let’s explore the ALTER TABLE queries using a Student table with
columns ROLL_NO and NAME, and demonstrate various modifications such as
adding, modifying, and dropping columns. Here’s how you can execute these
operations:
ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

1. Add Columns (AGE and COURSE) to the Student Table


To add new columns AGE and COURSE to the Student table, you can use
the ALTER TABLE statement with the ADD clause.
Query:
ALTER TABLE Student ADD
(AGE number(3),COURSE varchar(40));
Output:
ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

Explanation: This adds the AGE column with a numeric data type and
the COURSE column with a VARCHAR(40) type. The columns are added to the
table, but the values are empty initially.
2. Modify Column COURSE to Reduce its Size
If you want to reduce the size of the COURSE column
from VARCHAR(40) to VARCHAR(20), you can modify the column’s data type using
the MODIFY clause.
Query:
ALTER TABLE Student
MODIFY COURSE varchar(20);
Explanation: After running the above query, the COURSE column’s data type
will now allow a maximum of 20 characters instead of 40. This modifies the
column’s size limit.
3. Drop the COURSE Column from the Student Table
To remove the COURSE column completely from the Student table, you can
use the DROP COLUMN clause.
Query:
ALTER TABLE Student
DROP COLUMN COURSE;
Output:
ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

Explanation: After executing this query, the COURSE column is permanently


removed from the table, leaving just the ROLL_NO, NAME, and AGE columns.
Conclusion
The SQL ALTER TABLE statement is an essential tool for modifying the
structure of an existing table. Whether you need to add, delete, or modify
columns, or even rename the table or columns, ALTER TABLE provides the
flexibility needed to manage your database schema efficiently. By following
best practices and using this command wisely, we can maintain
the integrity and performance of your database while making
necessary structural changes.
SQL Comments
SQL comments play an essential role in enhancing
the readability, maintainability, and documentation of our SQL code. By using
comments effectively, developers can provide context, clarify complex logic,
and temporarily disable parts of the code. Whether we’re working alone or
collaborating with a team, proper use of SQL comments can significantly
improve the quality and clarity of our database queries.
In this article, we will explain different types of SQL comments: single-line
comments, multi-line comments, and in-line comments. We’ll also explore
their syntax, provide examples, and discuss best practices for using SQL
comments in our queries.
What Are SQL Comments?
SQL comments are annotations in our SQL code that are not executed by
the database engine. They serve as notes or explanations for human readers,
making it easier to understand and maintain the code. Whether we’re
explaining complex logic, providing context for a query, or temporarily
disabling a part of our code, comments are indispensable tool for any
developer.
Types of SQL Comments
SQL Comments explain sections of SQL statements or prevent SQL
statements from being executed. These are the three commenting methods in
SQL, each with its unique use. Let’s discuss these SQL comments in detail
below:
There are 3 types of comments in SQL:
1. Single-line comments
2. Multi-line comments
3. In-line comments
1. SQL Single Line Comments
Single-line comments are used to annotate a single line of SQL code. They are
often employed for brief explanations or to temporarily disable lines of
code without removing them. Single-line comments begin with two
hyphens (--), and the comment continues until the end of the line.
Syntax:
— single line comment

Example
SELECT * FROM customers;
Explanation:
In this example, the comment -- query to fetch customer records explains
the purpose of the query, which is to retrieve all records from
the customers table.
2. SQL Multi-Line Comments
Multi-line comments are used when we need to comment out more than one
line of SQL code. These comments are enclosed between /* and */ and can
span multiple lines. They are typically used for longer explanations or to
disable larger sections of code temporarily.
Syntax:
/* multi line comment
another comment */

Example
SELECT *
FROM orders
WHERE YEAR(order_date) = 2022;
Explanation:
In this example, the multi-line comment explains that the query retrieves all
orders placed in the year 2022 from the orders table.
3. SQL In-Line Comments
In-line comments allow us to add comments within a query itself. They are
typically used to provide additional information or explanations for specific
parts of the query, without interrupting the flow of the SQL statement. In-line
comments start with /* and end with */.
Syntax:
SELECT * FROM /* Customers; */

Example
SELECT customer_name,
order_date
FROM orders;
Explanation:
In this example, in-line comments are used to describe the purpose of
the customer_name and order_date columns. This approach keeps the code
readable and helps future developers understand the logic quickly.
Important Points About SQL Comments
While SQL comments are crucial for code documentation, there are several best
practices to follow when using them:
1. Be Concise but Clear: Keep comments brief but descriptive. Avoid
unnecessary comments that do not add value to the code.
2. Explain Complex Queries: Use comments to explain why certain
decisions were made, especially for complex queries or business
logic.
3. Avoid Commenting Obvious Code: Do not comment on trivial or
self-explanatory code. For example, there is no need to comment
simple SELECT statements with straightforward column names.
4. Use Comments to Temporarily Disable Code: Comments are often
used to “comment out” parts of SQL code that need to be tested or
temporarily disabled.
5. Consistent Formatting: Use a consistent style for comments
throughout your SQL codebase. This helps make the code easier to
read and understand, especially when working with a team.
Conclusion
SQL comments are an essential tool for any developer working
with databases. They allow us to annotate our code, making it easier
to understand, maintain, and debug. Whether we’re using single-line
comments for quick explanations, multi-line comments for more detailed
descriptions, or in-line comments for specific parts of a query, proper
commenting practices will improve the clarity of our SQL code.
ALTER (RENAME) in SQL
In SQL, making structural changes to a database is often necessary. Whether
it’s renaming a table or a column, adding new columns, or modifying data types,
the SQL ALTER TABLE command plays a critical role. This command provides
flexibility to manage and adjust database schemas without affecting the
existing data. In this article, we will explain how to rename tables and
columns in SQL using the ALTER TABLE command, along with practical
examples.
What is ALTER Command in SQL?
The ALTER TABLE command in SQL allows us to modify the structure of an
existing table. Whether we need to rename a table, rename a column, add a
new column, or change the data type of a column, this command makes it easy
to apply changes without affecting the data already stored.
The ALTER command is fundamental for database management and is often
used by developers to keep schemas aligned with evolving application needs.
Here are some common tasks you can achieve using the ALTER command:
 Renaming a table.
 Changing a column name.
 Adding or deleting columns.
 Modifying the data type of a column.
Syntax for ALTER Command
1. Renaming a Table
ALTER TABLE table_name
RENAME TO new_table_name;
2. Renaming a Column
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
3. Adding a New Column
ALTER TABLE table_name
ADD column_name datatype;
4. Modifying a Column Data Type
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;

Examples of ALTER Command in SQL


Below are practical examples to help us understand how to use the ALTER
command effectively in various scenarios. These examples includes renaming
tables or columns, adding new columns, or changing column data types.
1. Create a Sample Table
First, let’s create a sample Student table to demonstrate the ALTER command:
CREATE TABLE Student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(50),
phone VARCHAR(20)
);
2. Insert Sample Data into the Table
Let’s insert some data and then perform ALTER operation to understand better
about alter command.
INSERT INTO Student (id, name, age, email, phone)
VALUES
(1, 'Amit', 20, '[email protected]', '9999999999'),
(2, 'Rahul', 22, '[email protected]', '8888888888'),
(3, 'Priya', 21, '[email protected]', '7777777777'),
(4, 'Sonia', 23, '[email protected]', '6666666666'),
(5, 'Kiran', 19, '[email protected]', '5555555555');
Output

Student Table

Example 1: Rename a Column


Change the name of column name to FIRST_NAME in table Student. To change
the column name of the existing table we have to use Column keyword before
writing the existing column name to change
Syntax
ALTER TABLE Student RENAME COLUMN Column_NAME TO FIRST_NAME;
Query:
ALTER TABLE Student RENAME Column name TO FIRST_NAME;
Output

Output

Example 2: Rename a Table


In this example, we want to rename the table
from Student to Student_Details using the ALTER TABLE command, making the
name more descriptive and relevant to its content.
Query:
ALTER TABLE Student RENAME TO Student_Details;
Output

Student_Details table

Example 3: Add a New Column


To add a new column to the existing table, we first need to select the table
with ALTER TABLE command table_name, and then we will write the name of
the new column and its datatype with ADD column_name datatype. Let’s have
a look below to understand better.
Syntax
ALTER TABLE table_name
ADD column_name datatype;
Query:
ALTER TABLE Student ADD marks INT;
Output
output

5. Modify a Column Data Type


In the example, the phone column is updated from VARCHAR(20) to BIGINT to
store numerical data more efficiently and ensure data integrity for phone
numbers without unnecessary characters.
Syntax
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;
Query:
ALTER TABLE Student_Details
MODIFY COLUMN phone BIGINT;
Output
id name age email phone

1 Amit 20 [email protected] 9999999999

2 Rahul 22 [email protected] 8888888888

3 Priya 21 [email protected] 7777777777

4 Sonia 23 [email protected] 6666666666

5 Kiran 19 [email protected] 5555555555

Explanation:
 The phone column now has a BIGINT data type, suitable for storing
large numeric values.
 Existing data remains unchanged but is stored as integers instead
of strings.
Additional ALTER Command Use Cases
1. Removing a Column: In some cases, we might need to remove a column.
To do that, you can use the DROP COLUMN syntax:
ALTER TABLE Student_Details
DROP COLUMN marks;
This command deletes the marks column entirely from the table
2. Changing a Column’s Default Value: We can also modify a column’s
default value using the SET DEFAULT clause:
ALTER TABLE Student_Details
ALTER COLUMN age SET DEFAULT 18;
3. Renaming a Table or Column in Different Databases: Note that SQL syntax
can vary across different database systems. Here’s how we would rename a
table or column in MySQL, MariaDB, and Oracle:
 MySQL / MariaDB: The syntax for renaming a column is similar, but
you must also use the CHANGE COLUMN command to rename a
column:
ALTER TABLE Student
CHANGE COLUMN old_column_name new_column_name datatype;
 Oracle: Oracle supports the RENAME COLUMN syntax but requires
different syntax for renaming a table:
ALTER TABLE Student RENAME COLUMN old_column_name TO
new_column_name;

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

SQL SELECT Query


The select query in SQL is one of the most commonly used SQL commands to
retrieve data from a database. With the select command in SQL, users can
access data and retrieve specific records based on various conditions, making it
an essential tool for managing and analyzing data.
In this article, we’ll learn the SQL SELECT statement syntax, show you SQL
query examples, and explore advanced techniques to help you use SELECT
queries for data manipulation and analysis.
What is the SQL SELECT Statement?
The SELECT clause is the first clause and is one of the last clauses of the select
statement that the database server evaluates. The reason for this is that before
we can determine what to include in the final result set, we need to know all of
the possible columns that could be included in the final result set.
The SELECT statement in SQL is used to fetch or retrieve data from a
database. It allows users to access the data and retrieve specific data based on
specific conditions. We can fetch either the entire table or according to some
specified rules. The data returned is stored in a result table. With the SELECT
clause of a SELECT command statement, we specify the columns that we want
to be displayed in the query result.
Syntax:
SELECT column1,column2…. FROM table_name ;

Examples of SELECT Statement


Let’s look at some examples of the SQL SELECT statement, to understand it
better. To demonstrate the examples, let’s create a table which will be used in
examples:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age,
Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain',
'Spain','22','xxxxxxxxxx');
Output:
Example 1: Select Specific Columns
In this example, we will fetch only CustomerName, LastName from the table
Customer:
Query:
SELECT CustomerName, LastName
FROM Customer;
Output

Example 2: Select All Columns


In this example, we will fetch all the fields from the table Customer:
Query:
SELECT * FROM Customer;
Output
Example 3: SELECT Statement with WHERE Clause
Suppose we want to see table values with specific conditions then WHERE
Clause is used with select statement. In this example, filter customers who are
21 years old.
Query:
SELECT CustomerName
FROM Customer
where Age = '21';
Output:

Example 4: SELECT with GROUP BY Clause


In this example, we will use SELECT statement with GROUP BY Clause to
Group rows and perform aggregation. Here, Count orders per customer.
Query:
SELECT COUNT (item), Customer_id
FROM Orders
GROUP BY order_id;
Output:
Example 5: SELECT Statement with HAVING Clause
Use HAVING to filter results after grouping. Consider the following database
for fetching departments with total salary above 50,000. Use WHERE for row-
level filtering, HAVING for group-level filtering.

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

Tips to Master SELECT


Goal Technique

Fetch unique
SELECT DISTINCT column FROM table;
values
Goal Technique

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

Aliases for clarity SELECT CustomerName AS Name FROM Customer;

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


Join tables = b.id;

Conclusion
The SQL SELECT statement is an essential tool for retrieving and analyzing
data from relational databases. Whether we’re fetching specific columns or
using advanced clauses like WHERE, GROUP BY, and ORDER BY, the SELECT
query provides flexibility for efficient data retrieval. By understanding how to
use the SELECT statement and combining it with various clauses, we can
efficiently filter, aggregate, and sort data to meet our needs.

SQL- Lock Table


SQL Server is a versatile database and it is the most used Relational Database
that is used across many software industries. In this article, let us see about
the SQL Lock table in SQL Server by taking some practical examples. As it is
meeting Atomicity(A), Consistency(C), Isolation(I), and Durability(D)
requirements it is called a relational database. In order to maintain ACID
mechanisms, in SQL Server, a lock is maintained.
By using Azure Data Studio, let us see the concepts of the Lock mechanism by
starting with creating the database, table creation, locks, etc. Azure Data
Studio works well for Windows 10, Mac, and Linux environments. It can be
installed from here.
Database creation :
Command to create the database. Here GEEKSFORGEEKS is the db name.
--CREATE DATABASE <dbname>;

Create Database GEEKSFORGEEKS:

Make the database active


USE GEEKSFORGEEKS;
Once the database is made active, at the top, the database name will be shown

Adding the tables to the database :


Creating a table with Primary Key. Here ID is a PRIMARY KEY meaning each
author will have their own ID
CREATE TABLE Authors (
ID INT NOT NULL PRIMARY KEY,
<other column name1> <datatype> <null/not null>,
..........
);

If explicitly “NOT NULL” is specified, that column should have values. If not
specified, it is by default “NULL”.
“Authors” named table is created under “GEEKSFORGEEKS” database

Inserting rows in the table :


There will be scenarios like either we can add all columns or few column
values to the table. The reason is some columns might require null values by
default.
Example 1 :
INSERT INTO <table_name> (column1, column2, column3, ...) VALUES
(value1, value2, value3, ...);

Here we are taking into consideration the mentioned columns and hence only
their required values are inserted by the above query.
Example 2 :
INSERT INTO <table_name> VALUES (value1, value2, value3, ...);

Here we are not specifying any columns means, all the values to all the
columns need to be inserted.
Violation of PRIMARY KEY constraint 'PK__Authors__3214EC277EBB8ED1'.
Cannot insert duplicate key in object 'dbo.Authors'. The duplicate key
value is (1).

The above errors occurred in the above screenshot shows that “ID” column is
unique and it should not have duplicate values
Now, let us correct that and query the table by using:
SELECT * FROM <tablename>

Clear output for the applied Example 1 and Example 2 methods

It is observed that Row 1 is having ‘Null’ values in the place of ‘Skillsets’ and
‘NumberOfPosts’ column. The reason is as we have not specified values for
those columns, it has taken default Null values.
 SQL Locks :
SQL Server is a relational database, data consistency is an important
mechanism, and it can be done by means of SQL Locks. A lock is established
in SQL Server when a transaction starts, and it is released when it is ended..
There are different types of locks are there.
 Shared (S) Locks: When the object needs to be read, this type of lock
will occur, but this is not harmful.
 Exclusive (X) Locks: It prevents other transactions like
inserting/updating/deleting etc., Hence no modifications can be done
on a locked object.
 Update (U) Locks: More or less similar to Exclusive lock but here the
operation can be viewed as “read phase” and “write phase”.
Especially during the read phase, other transactions are prevented.
 Intent Locks: When SQL Server has the shared (S) lock or exclusive
(X) lock on a row, then the intent lock is on the table.
 Regular intent locks: Intent exclusive (IX) , Intent shared (IS), and
Intent update (IU).
 Conversion locks: Shared with intent exclusive (SIX), Shared with
intent update (SIU), and Update with intent exclusive (UIX).
Lock hierarchy starts from Database, then table, then row.

The shared lock on a database level is very much important as it prevents


dropping of the database or restoring a database backup over the database in
use.
Lock occurrences when there is a “SELECT” statement is issued.
During DML statement execution i.e. either during insert/update/delete.

With our example, let us see the locking mechanisms.


--Let us create an open transaction and analyze the locked resource.
BEGIN TRAN
Let us update the Skillsets column for ID = 1
UPDATE Authors SET Skillsets='Java,Android,PHP' where ID=1
select @@SPID
select * from sys.dm_tran_locks WHERE request_session_id=<our session
id. here it is 52>

Let us insert some more records(nearly around 100 records) into the table
and then using a transaction, let us update few columns as well as parallel
apply the select query also
--Let us create an open transaction and analyze the locked resources.
BEGIN TRAN
--Let us update the Skillsets when ID < 20
UPDATE Authors SET Skillsets='Java,Android,R Programming' where ID < 20
--Let us update the Skillsets when ID >= 25
UPDATE Authors SET Skillsets='Android,IOS,R Programming' where ID >= 25
--Other DML statements like Update/Delete. This statement must be
taking a long time
--(if there are huge updates are happening) as previous statement
itself
--is either not committed or rolled back yet
SELECT * FROM Authors;
select @@SPID

Actually when the earlier command transaction are not yet complete(if there
are huge records at least 100 records) and update is happening on each and
every row and before completion of it, if we are proceeding for another set of
commands like “select”
Then there are possibilities of the status will be “Awaiting” (Queries which are
executing) and “Suspended” (Queries which are halt)
How to overcome the so far running process?
KILL <spid> -> Kill the session

(Or) Inside a transaction, after each query, apply


COMMIT -> TO COMMIT THE CHANGES
ROLLBACK -> TO ROLLBACK THE CHANGES

By doing this process, we are enforcing the operation either to get committed
or rolled back(depends upon the requirements, it has to be carried out)
But unless we know that the entire process is required or not, we cannot
either commit or rollback the transaction.
Alternative way :
By using NOLOCK with SELECT QUERY, we can overcome
SELECT * FROM Authors WITH (NOLOCK);

For SELECT statement status using the sp_who2 command. The query runs
without waiting for the UPDATE transaction to be completed successfully and
release the locking on the table,
SELECT * FROM Authors WITH (READUNCOMMITTED);
--This way also we can do

Conclusion :
SQL Locks are much important for any RDBMS. SQL Server handles them in
the mentioned ways.

Difference between Grant and Revoke


Data Controlling Language (DCL) helps users to retrieve and modify the data
stored in the database with some specified queries. Grant and Revoke belong
to these types of commands of the Data controlling Language. DCL is a
component of SQL commands.
1. Grant :
SQL Grant command is specifically used to provide privileges to database
objects for a user. This command also allows users to grant permissions to
other users too.
Syntax:
grant privilege_name on object_name
to {user_name | public | role_name}

Here privilege_name is which permission has to be granted, object_name is


the name of the database object, user_name is the user to which access
should be provided, the public is used to permit access to all the users.
2. Revoke :
Revoke command withdraw user privileges on database objects if any
granted. It does operations opposite to the Grant command. When a privilege
is revoked from a particular user U, then the privileges granted to all other
users by user U will be revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}

Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts
database object like he can query or insert into accounts.
revoke insert,
select on accounts from Ram

By the above command user ram’s permissions like query or insert on


accounts database object has been removed.

To know the exact syntax and how are they used click here.
Differences between Grant and Revoke commands:

S.NO Grant Revoke

This DCL command grants


This DCL command removes permissions if
1 permissions to the user on the
any granted to the users on database objects.
database objects.

2 It assigns access rights to users. It revokes the useraccess rights of users.


S.NO Grant Revoke

If access for one user is removed; all the


For each user you need to specify
3 particular permissions provided by that users to
the permissions.
others will be removed.

When the access is decentralized If decentralized access removing the granted


4
granting permissions will be easy. permissions is difficult.

MySQL | Grant / Revoke Privileges


Managing user access and privileges is a crucial aspect
of database administration in MySQL. After creating a user account with
the CREATE USER statement, the next step is to define what that user can do
within the database.
This is achieved through the GRANT statement, which allows administrators to
assign specific privileges to users and ensure they can perform only the actions
necessary for their roles. Also, if a user’s access needs to be restricted,
the REVOKE statement can remove previously granted privileges.
Introduction to GRANT and REVOKE in MySQL
 In MySQL, creating a user account using the CREATE USER statement is
just the first step in user management.
 While this command establishes a new user, it does not assign any
privileges.
 To control what actions a user can perform, the GRANT statement is
essential for assigning specific privileges to user accounts.
Syntax:
GRANT privileges_names ON object TO user;
Explanation:
 privileges_name: These are the access rights or privileges granted to
the user.
 object: It is the name of the database object to which permissions are
being granted. In the case of granting privileges on a table, this
would be the table name.
 user: It is the name of the user to whom the privileges would be
granted.
Types of Privileges
Privileges: The privileges that can be granted to the users are listed below
along with the description:
Grant Privileges on Table

Granting Privileges to Users


1. To grant Select Privilege to a table named “users” where User Name
is Amit, the following GRANT statement should be executed.
2. The general syntax of specifying a username
is: ‘user_name’@’address’.
3. If the user ‘Amit‘ is on the local host then we have to mention it as
‘Amit’@’localhost‘. Or suppose if the ‘Amit‘ username is
on 192.168.1.100 IP address then we have to mention it as
‘Amit’@’192.168.1.100′.
4. ‘user_name’@’address’ – When you’re granting or revoking
permissions in MySQL, you use the ‘username’ or ‘hostname’ format
to tell which users are allowed or denied. This is important for
keeping security and access control in place, so here’s why we use it:
1. Granting SELECT Privilege to a User
To grant the SELECT privilege on a table named “users” to a user named “Amit“,
use the following command:
GRANT SELECT ON Users TO 'Amit'@'localhost;'
2. Granting Multiple Privileges
To grant multiple privileges, such as SELECT, INSERT, DELETE,
and UPDATE to the user “Amit“,
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost';
3. Granting All Privileges
To grant all privileges on the “users” table to “Amit”, use:
GRANT ALL ON Users TO 'Amit'@'localhost';
4. Granting Privileges to All Users
To grant a specific privilege (e.g., SELECT) to all users on the “users” table,
execute:
GRANT SELECT ON Users TO '*'@'localhost';
In the above example the “*” symbol is used to grant select permission to all
the users of the table “users”.
5. Granting Privileges on Functions/Procedures
While using functions and procedures, the Grant statement can be used to
grant users the ability to execute the functions and procedures in MySQL.
GRANT EXECUTE ON FUNCTION function_name TO 'Amit'@'localhost';
Example for granting EXECUTE privilege on a function named
“CalculateSalary“:
GRANT EXECUTE ON FUNCTION CalculateSalary TO 'Amit'@'localhost';
Granting Execute Privilege: Execute privilege gives the ability to execute a
function or procedure.Syntax:
GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user;
Different Ways of Granting EXECUTE Privileges
1. Granting EXECUTE privileges on a function in MySQL
If there is a function named “CalculateSalary” and you want to grant EXECUTE
access to the user named Amit, then the following GRANT statement should
be executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@'localhost';
2. Granting EXECUTE privileges to all Users on a function in MySQL
If there is a function named “CalculateSalary” and you want to grant EXECUTE
access to all the users, then the following GRANT statement should be
executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@'localhost';
3. Granting EXECUTE privilege to a Users on a procedure in MySQL
If there is a procedure named “DBMSProcedure” and you want to grant
EXECUTE access to the user named Amit, then the following GRANT statement
should be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@'localhost';
4. Granting EXECUTE privileges to all Users on a procedure in
MySQL
If there is a procedure called “DBMSProcedure” and you want to grant
EXECUTE access to all the users, then the following GRANT statement should
be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@'localhost';
5. Checking the Privileges Granted to a User
To see the privileges granted to a user in a table, the SHOW GRANTS
statement is used. To check the privileges granted to a user named “Amit” and
host as “localhost“, the following SHOW GRANTS statement will be
executed:
SHOW GRANTS FOR 'Amit'@'localhost';
Output:
GRANTS FOR Amit@localhost
GRANT USAGE ON *.* TO `SUPER`@`localhost`
Revoking Privileges from Users
The Revoke statement is used to revoke some or all of the privileges which
have been granted to a user in the past.
Syntax:
REVOKE privileges ON object FROM user;
Parameters Used:
 object: It is the name of the database object from which permissions
are being revoked. In the case of revoking privileges from a table, this
would be the table name.
 user: It is the name of the user from whom the privileges are being
revoked.
Privileges can be of the following values
Revoke Privileges on Table

Various Ways of Revoking Privileges From a User


1. Revoking SELECT Privilege
To revoke Select Privilege to a table named “users” where User Name is Amit,
the following revoke statement should be executed.
REVOKE SELECT ON Users FROM 'Amit'@'localhost';
2. Revoking Multiple Privileges
To revoke multiple Privileges to a user named “Amit” in a table “users”, the
following revoke statement should be executed.
REVOKE SELECT, INSERT, DELETE, UPDATE ON Users FROM 'Amit'@'localhost';
3. Revoking All Privileges
To revoke all the privileges to a user named “Amit” in a table “users”, the
following revoke statement should be executed.
REVOKE ALL ON Users FROM 'Amit'@'localhost';
Revoking Privileges on Functions/Procedures
While using functions and procedures, the revoke statement can be used to
revoke the privileges from users which have been EXECUTE privileges in the
past.
Syntax:
REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM User;
1. Revoking EXECUTE Privileges on a Function in MySQL
If there is a function called “CalculateSalary” and you want to revoke EXECUTE
access to the user named Amit, then the following revoke statement should be
executed.
REVOKE EXECUTE ON FUNCTION Calculatesalary FROM 'Amit'@'localhost';
2. Revoking EXECUTE Privileges to All Users on a Function in
MySQL
If there is a function called “CalculateSalary” and you want to revoke EXECUTE
access to all the users, then the following revoke statement should be
executed.
REVOKE EXECUTE ON FUNCTION Calculatesalary FROM '*'@'localhost';
3. Revoking EXECUTE Privilege to a Users on a Procedure in MySQL
If there is a procedure called “DBMSProcedure” and you want to revoke
EXECUTE access to the user named Amit, then the following revoke statement
should be executed.
REVOKE EXECUTE ON PROCEDURE DBMSProcedure FROM 'Amit'@'localhost';
4. Revoking EXECUTE Privileges to all Users on a Procedure in
MySQL
If there is a procedure called “DBMSProcedure” and you want to revoke
EXECUTE access to all the users, then the following revoke statement should
be executed.
REVOKE EXECUTE ON PROCEDURE DBMSProcedure FROM '*'@'localhost';
Conclusion
Understanding how to manage user privileges in MySQL is vital for ensuring
database security and effective access control. By utilizing
the GRANT and REVOKE statements, administrators can tailor user permissions
according to specific roles and responsibilities. Regularly reviewing these
privileges is a best practice that enhances security compliance.

SQL TRANSACTIONS
SQL transactions are essential for ensuring data integrity and consistency
in relational databases. Transactions allow for a group of SQL operations to
be executed as a single unit, ensuring that either all the operations succeed or
none of them do. Transactions allow us to group SQL operations into a single,
unified unit. But what exactly is a transaction, and why is it so important in
maintaining data integrity?
What is an SQL Transaction?
A transaction in SQL is a sequence of one or more SQL statements executed as
a single unit of work. These statements could be performing operations
like INSERT, UPDATE, or DELETE. The main goal of a transaction is to ensure that
all operations within it should be either completed successful or rolled back
entirely if an error occurs.
The essence of SQL transactions lies in the concept of atomicity either all the
operations within the transaction succeed, or none of them do. This helps
maintain the integrity and consistency of the data in the database.
Key Properties of SQL Transactions: ACID
The integrity of SQL transactions is governed by the ACID properties, which
guarantee reliable database transactions. These four properties work together
to guarantee that the database remains consistent and reliable.
 Atomicity: The outcome of a transaction can either be completely
successful or completely unsuccessful. The whole transaction must
be rolled back if one part of it fails.
 Consistency: Transactions maintain integrity restrictions by moving
the database from one valid state to another.
 Isolation: Concurrent transactions are isolated from one another,
assuring the accuracy of the data.
 Durability: Once a transaction is committed, its modifications remain
in effect even in the event of a system failure.
SQL Transaction Control Commands
In SQL, transaction control commands manage the execution of SQL
operations, ensuring the integrity and reliability of database transactions.
These commands help manage the start, commit, and rollback of changes made
to the database. Below are the key transaction control commands in SQL,
explained with syntax and examples for each.
1. BEGIN TRANSACTION Command
The BEGIN TRANSACTION command marks the beginning of a new transaction. All
SQL statements that follow this command will be part of the same transaction
until a COMMIT or ROLLBACK is encountered. This command doesn’t make any
changes to the database, it just starts the transaction.
Syntax:
BEGIN TRANSACTION transaction_name ;
Example of SQL Transaction with a Bank Transfer Scenario
Let’s look at an example of a bank transfer between two accounts. This
example demonstrates the usage of multiple queries in a single transaction.
BEGIN TRANSACTION;

-- Deduct $150 from Account A


UPDATE Accounts
SET Balance = Balance - 150
WHERE AccountID = 'A';

-- Add $150 to Account B


UPDATE Accounts
SET Balance = Balance + 150
WHERE AccountID = 'B';

-- Commit the transaction if both operations succeed


COMMIT;
If any error occurs, such as an issue with the UPDATE query, you can
use ROLLBACK to undo all changes made during the transaction:
ROLLBACK;
This ensures that the system doesn’t end up in an inconsistent state, such as
deducting money from one account without adding it to another.
BEGIN TRANSACTION TransferFunds;
2. COMMIT Command
The COMMIT command is used to save all changes made during the current
transaction to the database. Once a transaction is committed, the changes are
permanent.
Syntax:
COMMIT;
Example
Here is the sample Student table that will be used to perform the operations in
this example. This table contains basic student details such as ID, name, age,
and other relevant information that will be manipulated using
various transaction control commands.

Student Table
Following is an example which would delete those records from the table
which have age = 20 and then COMMIT the changes in the database.
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output

output

3. ROLLBACK Command
The ROLLBACK command is used to undo all changes made in the current
transaction. It is used when an error occurs or when the desired changes cannot
be completed. The database will revert to the state it was in before the BEGIN
TRANSACTION was executed.
Syntax:
ROLLBACK;
Example
Delete those records from the table which have age = 20 and then ROLLBACK
the changes in the database. In this case, the DELETE operation is undone, and
the changes to the database are not saved.
DELETE FROM Student WHERE AGE = 20;
ROLLBACK;
Output

output

4. SAVEPOINT Command
A SAVEPOINT is used to create a checkpoint within a transaction. We can roll
back to a specific SAVEPOINT instead of rolling back the entire transaction. This
allows us to undo part of the transaction rather than the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Example
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
Output

output

Explanation:
From the above example Sample table1, Delete those records from the table
which have age = 20 and then ROLLBACK the changes in the database by
keeping Savepoints. Here SP1 is first SAVEPOINT created before deletion. In
this example one deletion have taken place. After deletion again SAVEPOINT
SP2 is created.
5. ROLLBACK TO SAVEPOINT
The ROLLBACK TO SAVEPOINT command allows us to roll back the transaction to
a specific savepoint, effectively undoing changes made after that point.
Syntax:
ROLLBACK TO SAVEPOINT SAVEPOINT_NAME;
Example
Deletion have been taken place, let us assume that we have changed our mind
and decided to ROLLBACK to the SAVEPOINT that we identified as SP1 which
is before deletion. So, In this case the DELETE operation is undone, and the
transaction is returned to the state it was in at the SP1 savepoint.
ROLLBACK TO SP1;
//Rollback completed
Output
output

6. RELEASE SAVEPOINT Command


This command is used to remove a SAVEPOINT that we have created. Once a
SAVEPOINT has been released, we can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT. It is used
to initiate a database transaction and used to specify characteristics of the
transaction that follows.
Syntax:
RELEASE SAVEPOINT SAVEPOINT_NAME
Example
Once the savepoint SP2 is released, we can no longer roll back to it.
RELEASE SAVEPOINT SP2; -- Release the second savepoint.
Why Use Transactions in Banking?
In this case, without a transaction, you risk scenarios where money is deducted
from one account but not added to the other, leaving the system in an
inconsistent state. Transactions ensure that such issues are avoided by
guaranteeing that both operations succeed or fail together.
Types of SQL Transactions
There are different types of transactions based on their nature and the specific
operations they perform:
 Read Transactions: Used to only read the data, typically
with SELECT queries.
 Write Transactions: These involve modifying the data in the
database with INSERT, UPDATE, or DELETE operations.
 Distributed Transactions: These transactions span multiple
databases and ensure consistency across them.
 Implicit Transactions: Automatically started by SQL Server for
certain operations.
 Explicit Transactions: Manually controlled transactions where the
user begins and ends the transaction using BEGIN
TRANSACTION, COMMIT, and ROLLBACK.
Monitoring and Optimizing SQL Transactions
To maintain performance and prevent issues, consider the following
techniques:
1. Monitor Locks: Track locking behavior and adjust queries to minimize
locking conflicts.
2. Limit Transaction Scope: Limit the number of rows or records affected by a
transaction to speed up processing.
3. Use Batch Processing: If you’re handling large amounts of data, break the
operations into smaller transactions or batches to avoid overwhelming the
system.
Best Practices for Managing SQL Transactions
While SQL transactions are powerful, they require careful management to
ensure optimal performance and avoid problems like transaction blocking and
unnecessary locks. Here are some best practices:
1. Keep Transactions Short: Avoid long-running transactions as they can lock
tables and reduce concurrency.
2. Use Proper Indexing: Proper indexing on tables involved in the transaction
can greatly improve performance.
3. Avoid Transaction Blocking: Ensure transactions don’t block others
unnecessarily, causing delays.
4. Commit Early: Try to commit as soon as the transaction is complete to
release resources.
Conclusion
SQL transactions are a fundamental part of database management, providing
a way to ensure data consistency, integrity, and isolation. Understanding how
to use BEGIN TRANSACTION, COMMIT, ROLLBACK, and SAVEPOINT is essential for
writing reliable and efficient SQL queries. With proper transaction control, we
can ensure that our database operations are robust, consistent, and optimized
for performance. By following best practices like keeping transactions short and
committing early, we can also improve the scalability and concurrency of our
database.

SQL | WHERE Clause


The SQL WHERE clause allows to filtering of records in queries. Whether
you’re retrieving data, updating records, or deleting entries from a database,
the WHERE clause plays an important role in defining which rows will be
affected by the query. Without it, SQL queries would return all rows in a table,
making it difficult to target specific data.
In this article, we will learn the WHERE clause in detail—from basic concepts
to advanced ones. We’ll cover practical examples, discuss common operators,
provide optimization tips, and address real-world use cases.
What is the SQL WHERE Clause?
The SQL WHERE clause is used to specify a condition while fetching or
modifying data in a database. It filters the rows that are affected by
the SELECT, UPDATE, DELETE, or INSERT operations. The condition can range
from simple comparisons to complex expressions, enabling precise targeting of
the data.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name
operator value;
Parameter Explanation:
1. column1,column2: fields in the table
2. table_name: name of table
3. column_name: name of field used for filtering the data
4. operator: operation to be considered for filtering
5. value: exact value or pattern to get related data in the result
Examples of WHERE Clause in SQL
We will create a basic employee table structure in SQL for performing all the
where clause operation.
Query:
CREATE TABLE Emp1(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)
VALUES (1, 'Shubham', 'India','23','738479734'),
(2, 'Aman ', 'Australia','21','436789555'),
(3, 'Naveen', 'Sri lanka','24','34873847'),
(4, 'Aditya', 'Austria','21','328440934'),
(5, 'Nishant', 'Spain','22','73248679');
Output:
EmpID Name Country Age mob

1 Shubham India 23 738479734


EmpID Name Country Age mob

2 Aman Australia 21 436789555

3 Naveen Sri lanka 24 34873847

4 Aditya Austria 21 328440934

5 Nishant Spain 22 73248679

Example 1: Where Clause with Logical Operators


To fetch records of Employee with age equal to 24.
Query:
SELECT * FROM Emp1 WHERE Age=24;
Output:

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:

Example 2: Where Clause with BETWEEN Operator


It is used to fetch filtered data in a given range inclusive of two values.
Syntax:
SELECT column1,column2 FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Parameter Explanation:
1. BETWEEN: operator name
2. value1 AND value2: exact value from value1 to value2 to get related
data in result set.
To fetch records of Employees where Age is between 22 and 24 (inclusive).
Query:
SELECT * FROM Emp1 WHERE Age BETWEEN 22 AND 24;
Output:

Example 3: Where Clause with LIKE Operator


It is used to fetch filtered data by searching for a particular pattern in the
where clause.
Syntax:
SELECT column1,column2 FROM
table_name WHERE column_name LIKE pattern;
Parameters Explanation:
1. LIKE: operator name
2. pattern: exact value extracted from the pattern to get related data in
the result set.
Note: The character(s) in the pattern is case-insensitive.
To fetch records of Employees where Name starts with the letter S.
Query:
SELECT * FROM Emp1 WHERE Name LIKE 'S%';
The ‘%'(wildcard) signifies the later characters here which can be of any
length and value.
Output:

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


Query:
SELECT * FROM Emp1 WHERE Name LIKE '%M%';
Output:
Example 4: Where Clause with IN Operator
It is used to fetch the filtered data same as fetched by ‘=’ operator just the
difference is that here we can specify multiple values for which we can get the
result set.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name IN
(value1,value2,..);
Parameters Explanation:
1. IN: operator name
2. value1,value2,..: exact value matching the values given and get
related data in the result set.
To fetch the Names of Employees where Age is 21 or 23.
Query:
SELECT Name FROM Emp1 WHERE Age IN (21,23);
Output:

List of Operators that Can be Used with WHERE Clause


Operator Description

> Greater Than

>= Greater than or Equal to

< Less Than

<= Less than or Equal to

= Equal to

<> Not Equal to

BETWEEN In an inclusive Range


Operator Description

LIKE Search for a pattern

IN To specify multiple possible values for a column

Conclusion
The WHERE clause is use for filtering and refining SQL queries. Whether you’re
working with basic conditions, using logical operators, or performing advanced
queries with subqueries and EXISTS, mastering the WHERE clause is essential
for every SQL user. Understanding how to efficiently filter data, avoid common
pitfalls, and optimize your queries will ensure you’re able to write clean, fast,
and accurate SQL queries.

SQL HAVING Clause with Examples


The HAVING clause in SQL is used to filter query results based on aggregate
functions. Unlike the WHERE clause, which filters individual rows before
grouping, the HAVING clause filters groups of data after aggregation. It is
commonly used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
In this article, we will learn the concept of the HAVING clause, and its syntax,
and provide several practical examples
What is the SQL HAVING Clause?
The HAVING clause is used to filter the result of the GROUP BY statement
based on the specified conditions. It allows filtering grouped data
using Boolean conditions (AND, OR). It was introduced because
the WHERE clause cannot be used with aggregate functions. Similar to WHERE
clause, it helps apply conditions but specifically works with grouped data.
When we need to filter aggregated results, the HAVING clause is the
appropriate choice.
Key Features of the HAVING Clause
 Used to filter grouped data based on aggregate functions.
 Works with Boolean
conditions (AND, OR
 Cannot be used without GROUP BY unless an aggregate function is
present.
 Must be placed after the GROUP BY clause and before the ORDER
BY clause (if used).
 Helps generate summary reports from large datasets.
Syntax:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Here, the function_name is the name of the function used, for example, SUM(),
and AVG().
SQL HAVING Clause Examples
Here first we create a database name as “Company”, then we will create a table
named “Employee” in the database. After creating a table we will execute the
query.
Query:
-- Create the Employee table with appropriate data types
CREATE TABLE Employee (
EmployeeId int,
Name varchar(50),
Gender varchar(10),
Salary int,
Department varchar(20),
Experience int -- Changed to int for years of experience
);

-- Insert multiple rows into the Employee table in a single query


INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department,
Experience)
VALUES
(5, 'Priya Sharma', 'Female', 45000, 'IT', 2),
(6, 'Rahul Patel', 'Male', 65000, 'Sales', 5),
(7, 'Nisha Gupta', 'Female', 55000, 'Marketing', 4),
(8, 'Vikram Singh', 'Male', 75000, 'Finance', 7),
(9, 'Aarti Desai', 'Female', 50000, 'IT', 3);

SELECT * FROM Employee;


Output:
Example 1 : Using HAVING to Filter Aggregated Results
This employee table will help us understand the HAVING Clause. It contains
employee IDs, Name, Gender, department, and salary. To Know the sum of
salaries, we will write the query:
Query:
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department;
Output:

Now if we need to display the departments where the sum of salaries is 50,000
or more. In this condition, we will use the HAVING Clause.
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Output:

Example 2: Using HAVING with Multiple Conditions


If we want to find the departments where the total salary is greater than or
equal to $50,000, and the average salary is greater than $55,000. We can use
the HAVING clause to apply both conditions.
Query
SELECT Department, SUM(Salary) AS Total_Salary, AVG(Salary) AS
Average_Salary
FROM Employee
GROUP BY Department
HAVING SUM(Salary) >= 50000 AND AVG(Salary) > 55000;
Output:
Department Total_Salary Average_Salary

Finance 75000 75000

Sales 65000 65000

Example 3: Using HAVING with COUNT()


If we want to find departments where there are more than two employees. For
this, we can use the COUNT() aggregate function along with the HAVING
clause.
Query:
SELECT Department, COUNT(EmployeeId) AS Employee_Count
FROM Employee
GROUP BY Department
HAVING COUNT(EmployeeId) >= 2;
Output:
Department Employee_Count

IT 2

This query counts the number of employees in each department and uses the
HAVING clause to filter for departments with more than two employees.
Example 4: Using HAVING with AVG()
In this example, let’s find out the average salary for each department and use
the HAVING clause to display only those departments where the average
salary is greater than $50,000.
Query:
SELECT Department, AVG(Salary) AS Average_Salary
FROM Employee
GROUP BY Department
HAVING AVG(Salary) > 50000;
Output:
Department Average_Salary

Finance 75000

Marketing 55000
Department Average_Salary

Sales 65000

Having vs WHERE
Having Where

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

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

Priority Wise HAVING Clause is Priority Wise WHERE is executed


executed after Group By. before Group By.

Conclusion
The HAVING clause is an essential tool in SQL for filtering results based
on aggregated data. Unlike the WHERE clause, which applies conditions to
individual rows, HAVING works on groups of data that have been aggregated
using functions like SUM(), AVG(), and COUNT(). Understanding how and
when to use the HAVING clause allows you to perform more complex data
analysis and generate meaningful insights from your datasets.
SQL | GROUP BY
The SQL GROUP BY clause is a powerful tool used to organize data into groups
based on shared values in one or more columns. It’s most often used with
aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform summary
operations on each group helping us extract meaningful insights from large
datasets.
Whether we’re analyzing sales by region, users by age group, or orders by
product category, the GROUP BY clause helps transform raw data into
structured reports.
What is GROUP BY Clause in SQL?
The GROUP BY statement in SQL is used to arrange identical data into groups
based on specified columns. If a particular column has the same values in
multiple rows, the GROUP BY clause will group these rows together. It’s
commonly used with aggregate functions to calculate totals or averages per
group. Key Points About GROUP BY:
 GROUP BY clause is used with the SELECT statement.
 In the query, the GROUP BY clause is placed after
the WHERE clause.
 In the query, the GROUP BY clause is placed before the ORDER BY
clause if used.
 In the query, the GROUP BY clause is placed before the Having
clause.
 Place condition in the having clause.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() ,
AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Examples of GROUP BY in SQL
Let’s assume that we have two tables Employee and Student Sample Table is
as follows after adding two tables we will do some specific operations to learn
about GROUP BY. Insert some random data into a table and then we will
perform some operations in GROUP BY.
Employee Table
CREATE TABLE emp (
emp_no INT PRIMARY KEY,
name VARCHAR(50),
sal DECIMAL(10,2),
age INT
);

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


(1, 'Aarav', 50000.00, 25),
(2, 'Aditi', 60000.50, 30),
(3, 'Aarav', 75000.75, 35),
(4, 'Anjali', 45000.25, 28),
(5, 'Chetan', 80000.00, 32),
(6, 'Divya', 65000.00, 27),
(7, 'Gaurav', 55000.50, 29),
(8, 'Divya', 72000.75, 31),
(9, 'Gaurav', 48000.25, 26),
(10, 'Divya', 83000.00, 33);
SELECT * from emp;
Output:
Emp TABLE

Student Table
CREATE TABLE student (
name VARCHAR(50),
year INT,
subject VARCHAR(50)
);

INSERT INTO student (name, year, subject) VALUES


('Alice', 1, 'Mathematics'),
('Bob', 2, 'English'),
('Charlie', 3, 'Science'),
('David', 1, 'Mathematics'),
('Emily', 2, 'English'),
('Frank', 3, 'Science');
Output:
Student TABLE

Example 1 : Group By Single Column


Group By single column means, placing all the rows with the same value of
only that particular column in one group. Consider the query for Calculating the
Total Salary of each Employee by their name in the emp table.
Query:
SELECT name, SUM(sal) FROM emp
GROUP BY name;
Output:

Output

Explanations:
As you can see in the above output, the rows with duplicate NAMEs are
grouped under the same NAME and their corresponding SALARY is the sum of
the SALARY of duplicate rows. The SUM() function of SQL is used here to
calculate the sum. The NAMES that are added are Aarav, Divya and Gaurav.
Example 2 : Group By Multiple Columns
Group by multiple columns is say, for example, GROUP BY column1, column2.
This means placing all the rows with the same values of columns column
1 and column 2 in one group. This SQL query groups student records by
both SUBJECT and YEAR and then counts the number of records (i.e., students)
in each of those groups.
Query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
Output:

Output

Explantions:
As we can see in the above output the students with both the same SUBJECT
and YEAR are placed in the same group. And those whose only SUBJECT is the
same but not YEAR belong to different groups. So here we have grouped the
table according to two columns or more than one column. The Grouped subject
and years are (English,2) , (Mathematics,1) and (Science,3). The above
mentioned all groups and years are repeated twice.
HAVING Clause in GROUP BY Clause
We know that the WHERE clause is used to place conditions on columns but
what if we want to place conditions on groups? This is where the HAVING
clause comes into use. We can use the HAVING clause to place conditions to
decide which group will be part of the final result set. Also, we can not use
aggregate functions like SUM(), COUNT(), etc. with the WHERE clause. So we
have to use the HAVING clause if we want to use any of these functions in the
conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Key Terms
 function_name: Name of the function used for example, SUM() ,
AVG().
 table_name: Name of the table.
 condition: Condition used.
Example:
SELECT NAME, SUM(sal) FROM Emp
GROUP BY name
HAVING SUM(sal)>50000;
Output:

Output

Explanation:
In the result, only employees whose total salary (SUM(sal)) exceeds 50,000 are
displayed. For example, if Anjali has a total salary less than 50,000, she will be
excluded from the output.
Conclusion
The GROUP BY function in SQL organizes identical data into groups, enabling
aggregate analysis on each group. It is commonly used with aggregate
functions like SUM(), COUNT(), AVG(), etc., to summarize data efficiently.
The HAVING clause further refines the results by applying conditions to these
grouped records. GROUP BY can operate on single or multiple columns,
making it a versatile tool for data retrieval and reporting.

You might also like