SQL
SQL
System (DBMS)
UNIT 2
Structured Query Language (SQL)
SYLLABUS
Structured Query Language (SQL)
SQL is Structured Query Language that is used for storing and
managing data in RDMS.
Structured means only related to relational data.
It allows users to communicate with relational database and
retrieve data from the tables.
All RDBMS like MySQL, Oracle, DB2, MS Access, Informix
uses SQL as an standard database language.
SQL allows users to query the database in a number of ways,
using English-like statements.
SQL is mostly used by engineers in software development for
data storage.
Relational Model and SQL: Key Highlights
Dr. E.F. Codd introduced the Relational Model (based on Relational
Algebra and Tuple Relational Calculus) in his paper published in the
ACM journal in 1970.
IBM implemented the SQL language, originally called SEQUEL
(Structured English Query Language) as part of the System R
project in the early 1970s.
SEQUEL is renamed/ shortened to SQL.
1986/87: SQL became a standard:
• American National Standards Institute, ANSI (1986)
• International Organization for Standardization, ISO (1987)
SQL Versions: SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003,
SQL:2006, SQL:2008, SQL:2011, SQL:2016, SQL:2023.
Commercial Vendors (Oracle, SQL Server, etc.) implement standard
features with proprietary extensions.
SQL: Introduction
SQL is Non-Procedural, Domain-Specific Language, which allows
to declare what we want to do, but not how to do.
SQL lets you access and manipulate databases.
SQL is NOT case sensitive. For Example, select is the same as
SELECT.
But names of the database, tables and columns are case sensitive.
• For Example, In the given SQL query, table named as STUDENT is
different from student
SELECT * from STUDENT;
SELECT * from student;
SQL statements can use multiple lines.
SQL: Rules
Structure query language is not case sensitive. Generally, keywords
of SQL are written in uppercase.
Every SQL statements should ends with a semicolon.
Statements of SQL are dependent on text lines. We can use a single
SQL statement on one or multiple text line.
Using the SQL statements, you can perform most of the actions in a
database.
SQL depends on tuple relational calculus and relational algebra.
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
What Can SQL do?
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
SQL Datatypes
Data types are used to represent the nature of the data that can be
stored in the database table.
For example, in a particular column of a table, if we want to store a
string type of data then we will have to declare a string data type of
this column.
Data types mainly classified into three categories for every database.
1. String Data types
2. Numeric Data types
3. Date and time Data types
MySQL String Data Types
Data Type Description
It is used to specify a fixed length string that can contain
CHAR(Size) numbers, letters, and special characters. Its size can be 0 to
255 characters.
It is used to specify a variable length string that can contain
VARCHAR(Size) numbers, letters, and special characters. Its size can be from 0
to 65535 characters.
It is equal to CHAR() but stores binary byte strings. Its size
BINARY(Size)
parameter specifies the column length in the bytes.
It is equal to VARCHAR() but stores binary byte strings. Its size
VARBINARY(Size)
parameter specifies the maximum column length in bytes.
It holds a string that can contain a maximum length of 255
TEXT(Size)
characters.
TINYTEXT It holds a string with a maximum length of 255 characters.
MEDIUMTEXT It holds a string with a maximum length of 16,777,215.
MySQL String Data Types
Data Type Description
It holds a string with a maximum length of 4,294,967,295
LONGTEXT
characters.
It is used when a string object having only one value, chosen
ENUM(val1, from a list of possible values. It contains 65535 values in an
val2, val3,...) ENUM list. If you insert a value that is not in the list, a blank
value will be inserted.
It is used to specify a string that can have 0 or more values,
SET( val1,val2,v
chosen from a list of possible values. You can list up to 64
al3,....)
values at one time in a SET list.
It is used for BLOBs (Binary Large Objects). It can hold up to
BLOB(size)
65,535 bytes.
MySQL Numeric Data Types
Data Type Description
It is used for a bit-value type. The number of bits per value is
BIT(Size)
specified in size. Its size can be 1 to 64. The default value is 1.
It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0
INT(size)
to 4294967295. The size parameter specifies the max display
width that is 255.
INTEGER(siz
It is equal to INT(size).
e)
It is used to specify a floating point number. Its size parameter
FLOAT(size,
specifies the total number of digits. The number of digits after
d)
the decimal point is specified by d parameter.
Note: TCL Commands are used for only DML commands while DDL
and DCL commands are committed.
Data Definition Language (DDL)
DDL is used for creating and modifying the database objects such
as tables, views and users.
It changes the structure of the table like creating a table, deleting
a table, altering a table, etc.
All the command of DDL are auto-committed that means it
permanently save all the changes in the database.
DDL Commands are:
1. CREATE - to create new table or database
2. ALTER - to alter the structure of table
3. DROP - to delete a table from database
4. TRUNCATE - to delete all records from table
5. RENAME - to rename a table
Create Command
CREATE statement is used to create database schema and to define
the datatype and structure of the data to be stored in the database.
CREATE statement can be used to create database and tables.
Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;
Removes all rows from a table, leaving the structure Deletes the entire table, including its
Operation
intact. structure.
Generally faster than DELETE since it deallocates Fast operation since it removes both data
Speed
data pages. and structure.
Minimal logging; typically logs page deallocations Fully logged; the entire table drop is
Transaction Log
only. recorded.
Used when you need to remove all data from a table Used when you want to completely remove
Usage
but keep the table itself. the table from the database.
Data cannot be recovered unless a backup is The table and its data cannot be recovered
Recovery
available (depends on the database system). unless a backup is available.
Permissions Required Requires ALTER permission on the table. Requires DROP permission on the table.
SQL TRUNCATE vs DELETE
Feature TRUNCATE TABLE DELETE
Transaction Logging Minimal logging (usually faster) Fully logged (can be slower)
Cannot truncate a table referenced by a foreign Can delete rows in a table referenced
Foreign Key Constraints
key (without disabling the constraint) by a foreign key
Retains the table structure, constraints, and Retains the table structure,
Table Structure
indexes constraints, and indexes
DELETE v/s DROP v/s TRUNCATE
Paramete
DELETE Command DROP Command
rs TRUNCATE Command
The DELETE command is Data The DROP command is Data The TRUNCATE command is
Language Manipulation Language Definition Language a Data Definition Language
Command. Command. Command.
We can restore any deleted We cannot get the complete We cannot restore all the
row or multiple rows from the table deleted from the deleted rows from the
Transition
database using the ROLLBACK database using the database using the
command. ROLLBACK command. ROLLBACK command.
Performanc The DELETE command The DROP Command has faster The TRUNCATE command
e Speed performs slower than the DROP performance than DELETE works faster than the DROP
command and TRUNCATE Command but not as compared command and DELETE
command as it deletes one or to the Truncate Command command because it deletes
more rows based on a specific because the DROP command all the records from the table
condition. deletes the table from the without any condition.
database after deleting the rows.
Integrity The Integrity Constraints The Integrity Constraints get The Integrity Constraints will
Constraints remain the same in the DELETE removed for the DROP not get removed from the
command. command. TRUNCATE command.
Permission DELETE permission is required We need ALTER permission on We need table ALTER
to delete the rows of the table. the schema to which the table permission to use the
belongs and CONTROL TRUNCATE command.
permission on the table to use
the DROP command.
DELETE Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice
the WHERE clause in the DELETE statement. The WHERE clause
specifies which record(s) should be deleted. If you omit
the WHERE clause, all records in the table will be deleted!
SQL DELETE Statement
The following SQL statement
deletes the customer "Alfreds
Futterkiste" from the
"Customers" table:
DELETE FROM Customers WHER
E CustomerName='Alfreds
Futterkiste';
SQL DELETE Statement
Delete All Records
It is possible to delete all rows in a table without deleting the table.
This means that the table structure, attributes, and indexes will be
intact:
Delete a Table
To delete the table completely, use the DROP TABLE statement:
DROP TABLE Customers;
SQL DELETE Statement
Delete All Records
It is possible to delete all rows in a table without deleting the table.
This means that the table structure, attributes, and indexes will be
intact:
Delete a Table
To delete the table completely, use the DROP TABLE statement:
DROP TABLE Customers;
Data Control Language (DCL)
DCL commands are primarily used to implement access control
on the data stored in the database. It is implemented along
the DML (Data Manipulation Language) and DDL (Data Definition
Language) commands.
It has a simple syntax and is easiest to implement in a database.
The administrator can implement DCL commands to add or
remove database permissions on a specific user that uses
the database when required.
DCL commands are implemented to grant, revoke and deny
permission to retrieve or modify the data in the database.
The two types of DCL commands are as follows:
1. GRANT
2. REVOKE
GRANT Command
GRANT, as the name itself suggests, allows the administrator to
provide particular privileges or permissions over a database object,
such as a table, view, or procedure.
It can provide user access to perform certain database or
component operations.
In simple language, the GRANT command allows the user to
implement other SQL commands on the database or its objects.
The primary function of the GRANT command is to provide
administrators the ability to ensure the security and integrity of the
data is maintained in the database.
Syntax:
GRANT privileges_names ON object TO user;
Implementing GRANT Statement
Consider a scenario where you are the database administrator, and a
student table is in the database. Suppose you want a specific user
Aman to only SELECT (read)/ retrieve the data from the student table.
Then you can use GRANT in the below GRANT statement.
GRANT SELECT ON student TO Aman;
Syntax:
REVOKE privileges_names ON object TO user;
Implementing REVOKE Statement
Consider a scenario where the user is the database administrator. In
the above implementation of the GRANT command, the user Aman
was provided permission to implement a SELECT query on the
student table that allowed Aman to read or retrieve the data from the
table. Due to certain circumstances, the administrator wants to
revoke the abovementioned permission.
To do so, the administrator can implement the below REVOKE
statement:
REVOKE SELECT ON student TO Aman;
This will stop the user Aman from implementing the SELECT query on
the student table. The user may be able to implement other queries
in the database.
Transaction Control Language
TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
These operations are automatically committed in the database
that's why they cannot be used while creating tables or dropping
them.
Here are some commands that come under TCL:
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
Transaction Control Language
1. COMMIT: Commit command is used to save all the transactions to the
database.
Syntax: COMMIT;
Example: DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
2. ROLLBACK: Rollback command is used to undo transactions that have
not already been saved to the database.
Syntax: ROLLBACK;
Example: DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
3. SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;
Transaction Control Language
1. ROLLBACK: Rollback command is used to undo transactions that have
not already been saved to the database.
Syntax: ROLLBACK;
Example: DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
2. SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;
INSERT INTO employees VALUES (1, 'John Doe’);
SAVEPOINT sp1;
INSERT INTO employees VALUES (2, 'Jane Smith’); Rollback
and Savepoint
ROLLBACK TO sp1;
Example
Clause in SQL
A clause in SQL is a built-in function that helps to fetch the required records
from a database table.
WHERE Clause
The SQL WHERE clause is used to specify a condition while fetching the
data from a single table or by joining with multiple tables.
If the given condition is satisfied, then only it returns a specific value from
the table. You should use the WHERE clause to filter the records and
fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also
used in the UPDATE, DELETE statement, etc., which we would examine in
the subsequent chapters.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
WHERE Clause in SQL
The following code is an example which would fetch the ID, Name and Salary
fields from the CUSTOMERS table, where the salary is greater than 2000 −
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >
2000;
WHERE Clause with AND and OR Conjunctive Operators
The SQL AND & OR operators are used to combine multiple conditions to
narrow data in an SQL statement
The basic syntax of the AND operator with a WHERE clause is as follows −
SELECT column1, column2, column FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
INPUT
QUERY OUTPUT
WHERE Clause with AND and OR Conjunctive Operators
The following code block has an example, which would sort the result in an
ascending order by the NAME and the SALARY −
SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;
ORDER BY Clause in SQL: Example 2
The following code block has an example, which would sort the result in the descending order
by NAME.
SELECT * FROM CUSTOMERS ORDER BY NAME DESC;
IN Operator in SQL
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax:
1. SELECT column_name(s) FROM table_name WHERE column_name IN
(value1, value2, ...);
2. SELECT column_name(s) FROM table_name WHERE column_name IN
(SELECT STATEMENT);
Example:
3. SELECT * FROM Customers WHERE Country IN ('Germany', 'France',
'UK');
4. SELECT * FROM Customers WHERE Country IN (SELECT Country FROM
Suppliers);
BETWEEN Operator in SQL
The BETWEEN operator selects values within a given range. The values can
be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Syntax:
SELECT column_name(s) FROM table_name WHERE column_name
BETWEEN value1 AND value2;
Example:
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
Aggregate functions in SQL
An aggregate function is a function that performs a calculation on a set
of values, and returns a single value.
The GROUP BY clause splits the result-set into groups of values and the
aggregate function can be used to return a single value for each group.
MAX(): The MAX() function returns the largest value of the selected
column.
Syntax: SELECT MAX(column_name) FROM table_name WHERE condition;
Example: SELECT MAX(Price) AS LargestPrice FROM Products;
COUNT(): The COUNT() function returns the number of rows that matches
a specified criterion.
Syntax: SELECT COUNT(column_name) FROM table_name WHERE
condition;
Example: SELECT COUNT(ProductID) FROM Products;
Aggregate functions in SQL
AVG(): The AVG() function returns the average value of a numeric column.
Syntax: SELECT AVG(column_name) FROM table_name WHERE condition;
Example: SELECT AVG(Price) FROM Products;
SUM(): The SUM() function returns the total sum of a numeric column.
Syntax: SELECT SUM(column_name) FROM table_name WHERE condition;
Example: SELECT SUM(Quantity) FROM OrderDetails;
GROUP BY Clause in SQL
The SQL GROUP BY clause is used in collaboration with the SELECT
statement to arrange identical data into groups.
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by
one or more columns.
This GROUP BY clause follows the WHERE clause in a SELECT statement
and precedes the ORDER BY clause.
SYNTAX:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
GROUP BY Clause in SQL
Consider the given table named as “Emp”
Write a query to find the department for which the sum of salaries
of employees is more than 10000.
Dept_ID SumSalary
SELECT Dept_ID, SUM(Salary)
501 15000.00
FROM Emp 502 14500.00
GROUP BY Dept_id
HAVING SUM(Salary)>10000;
GROUP BY Clause in SQL
Consider the given table named as “Emp”
HAVING COUNT(Address)>=2;
HAVING Clause V/S WHERE Clause in SQL
HAVING WHERE
1. The HAVING clause is used in database systems to 1. The WHERE clause is used in database systems
fetch the data/values from the groups according to the to fetch the data/values from the tables according
given condition. to the given condition.
2. The HAVING clause is always executed with the 2. The WHERE clause can be executed without the
GROUP BY clause. GROUP BY clause.
3. The HAVING clause can include SQL aggregate 3. We cannot use the SQL aggregate function with
functions in a query or statement. WHERE clause in statements.
4. We can only use SELECT statement with HAVING 4. Whereas, we can easily use WHERE clause with
clause for filtering the records. UPDATE, DELETE, and SELECT statements.
5. The HAVING clause is used in SQL queries after the 5. The WHERE clause is always used before the
GROUP BY clause. GROUP BY clause in SQL queries.
6. We can implements this SQL clause in column 6. We can implements this SQL clause in row
operations. operations.
7. It is a post-filter. 7. It is a pre-filter.
8. It is used to filter groups. 8. It is used to filter the single record of the table.
JOINS in SQL
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Customers.CustomerID;
JOINS in SQL
Table 1: Order
Table 2: Customer