0% found this document useful (0 votes)
40 views61 pages

Advance SQL 2

The document outlines a Level IV module on Advanced Structured Query Language (SQL) with a nominal duration of 100 hours, prepared by Dereje Gerlu in December 2024. It covers various topics including DBMS fundamentals, database tools and equipment, SQL statements with functions, and techniques for data retrieval and manipulation. Key concepts include the use of WHERE and ORDER BY clauses, Boolean operators, and methods for eliminating duplicates and null values in databases.

Uploaded by

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

Advance SQL 2

The document outlines a Level IV module on Advanced Structured Query Language (SQL) with a nominal duration of 100 hours, prepared by Dereje Gerlu in December 2024. It covers various topics including DBMS fundamentals, database tools and equipment, SQL statements with functions, and techniques for data retrieval and manipulation. Key concepts include the use of WHERE and ORDER BY clauses, Boolean operators, and methods for eliminating duplicates and null values in databases.

Uploaded by

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

Web Development and Database

Administration Level IV

Module Title: Advanced Structured Query Language


Module code: EIS WDDBA4 M03 1123
Nominal duration: 100 Hours
Prepared by: Dereje Gerlu
December , 2024
Addis Ababa, Ethiopia
Chapter one : Advanced SQL statements
 DBMS fundamentals
 Database tools and equipment
 Functions of where clause
 Functions of order by clause
 Boolean operators
 Elimination of duplicated and null values
 Functions of join operator
 Functions of union operator
 Data control language
 Transaction control language
Chapter Two: SQL statements with functions
 Arithmetic operations
 String functions and operators
 Mathematical functions
 Date functions
Unit Three: SQL statements with aggregation and filtering
 Function of group by statement
 Function of having clause
 Backup database
Chapter one : Advanced SQL statements
1.1 DBMS fundamentals
 A database-management system (DBMS) is a collection of interrelated data
and a set of programs to access those data.
 The primary goal of a DBMS is to provide a way to store and retrieve database
information that is both convenient and efficient
 Database systems are designed to manage large bodies of information.
Management of data involves both defining structures for storage of
information and providing mechanisms for the manipulation of information.
 Fundamentals of DBMS is crucial for anyone working with databases, whether
as a database administrator, data analyst, or software developer.
 Fundamental concepts in (DBMS) that are essential for the proper
functioning and maintenance of databases are:-
1. Data Organization
2. Data Retrieval
3. Data Manipulation: update, delete, insert and so on
4. Data Security
5. Data Backup and Recovery
6. Data Integrity and Consistency
1.2 Database tools and equipment
1.2.1 Database tools
 Database tools are essential for managing, maintaining, and optimizing databases.
They help with various tasks such as querying, reporting, designing schemas, and
ensuring database security and performance. Here are some common types of
database tools across different categories:
1. Database Management Systems (DBMS)
These are systems that allow you to create, manage, and query databases.
MySQL, PostgreSQL, Oracle Database, Microsoft SQL Server, MongoDB, ACassandra:
2. Database Design Tools
These tools help in creating and visualizing database structures and schemas.
MySQL Workbench, DbSchema, ER/Studio:Toad Data Modeler
3. Database Query Tools
These help users write and execute queries against databases.
Dbeaver, SQL Developer, HeidiSQL, RazorSQL
4. Database Backup and Recovery Tools
These tools ensure that data can be backed up securely and restored in case of failure.
Veeam,pgBackRest,RMAN (Oracle Recovery Manager): Percona XtraBackup:
5. Database Performance Monitoring Tools
These tools help monitor the performance of databases, including query execution time,
server load, etc.
SolarWinds Database Performance Analyzer: For SQL Server, Oracle, and MySQL
performance monitoring.
New Relic: Provides database performance monitoring along with overall application
performance insights.
Nagios: Monitors database performance as well as system and network performance.
pgAdmin: A popular tool for PostgreSQL that also includes performance and query
optimization features.
6. Database Migration Tools
These tools assist in migrating databases between environments or from one DBMS to
another.
AWS Database Migration Service (DMS), Flyway, Liquibase, Oracle SQL Developer
Migration Tool
7. Database Security Tools
These tools help in securing databases against unauthorized access and threats.
SQL Secure by IDERA, DbDefence, IBM Guardium
1.2.2 Database equipment
Database equipment refers to the hardware components and infrastructure required to
support a database system. This equipment is critical to ensure the database operates
efficiently, securely, and with high availability. Here’s a breakdown of the essential types of
database equipment:
1. Servers
Database servers are the machines that host and run the DBMS software and handle
database queries and transactions.
Database Servers: High-performance servers such as Dell PowerEdge, HP ProLiant, IBM
Power Systems, and Oracle SPARC servers. These often feature multiple processors, large
amounts of RAM, and fast storage to handle large databases and high transaction volumes.
Cloud Servers: Cloud infrastructure services like AWS EC2, Google Cloud Compute Engine,
Microsoft Azure, or Oracle Cloud provide virtualized hardware resources for hosting
databases, offering scalability and flexibility.
2. Storage Equipment
Databases require reliable, high-speed storage solutions to store vast amounts of data.
Hard Disk Drives (HDDs): Traditional storage, typically used in large-scale databases due to
its cost-effectiveness. use mechanical spinning disk
Solid State Drives (SSDs): High-speed, low-latency storage options are ideal for databases
that require fast access to data, often used in performance-critical systems. SSDs use
memory chips
Storage Area Networks (SAN): A dedicated high-speed network that
connects storage devices (like HDDs and SSDs) to servers, often used for
enterprise-level databases for improved redundancy and scalability.
Network-Attached Storage (NAS): A file-level storage solution that
provides data access over a network and can be useful for backup or data
archival purposes.
3. Networking Equipment
Databases often interact with client applications, other databases, or external
systems. High-performance and reliable networking equipment ensures smooth
communication.
Routers: Directs traffic between different networks, enabling communication
between the database server and external networks (e.g., Cisco, Juniper).
Switches: Ensure efficient communication within a local network, used to
connect the database server to storage devices, backup systems, or other
infrastructure (e.g., Cisco Catalyst, Aruba, HPE).
Network Interface Cards (NICs): Provide servers with the ability to
connect to a network and communicate with other devices. High-performance
NICs are often used in database servers to handle large data transfers.
4. Backup Equipment
Reliable backup hardware is essential for ensuring data can be
recovered in case of failure or disaster.
Tape Drives: Often used in large organizations for long-term, low-cost
data archival. Examples include LTO (Linear Tape-Open) drives.
Backup Appliances: Dedicated devices that store backup copies of
databases, such as Dell EMC Data Domain, IBM Spectrum Protect, or
Veritas NetBackup appliances.
External Hard Drives or NAS: Commonly used for smaller-scale
databases or for offsite backups.
5. Redundant Power Supply and UPS
Database uptime is crucial for most organizations, so backup power
equipment ensures databases stay online during power outages.
Uninterruptible Power Supply (UPS): Provides short-term power during
outages, allowing time for safe database shutdowns or failover to backup power
systems. Brands like APC and Eaton offer reliable UPS solutions.
Redundant Power Supplies: Servers hosting mission-critical databases often
have redundant power supplies to ensure continued operation even if one power
source fails.
6. Cooling Systems
Databases and servers generate heat, so adequate cooling systems are required to maintain
optimal operating conditions.
Data Center Cooling: Large-scale systems such as CRAC (Computer Room Air Conditioning)
units, in-row cooling, or liquid cooling systems are common in data centers where database
servers are housed.
Rack Cooling Units: These are used to cool individual racks of servers hosting databases.
7. RAID Controllers
RAID (Redundant Array of Independent Disks) controllers allow data to be spread across
multiple drives for redundancy, performance improvement, or both.
Hardware RAID Controllers: These are physical cards installed in database servers to
manage RAID configurations and improve data redundancy and performance (e.g., LSI Logic,
Broadcom, Intel RAID controllers).
RAID Arrays: Dedicated storage arrays that offer hardware-based RAID for higher reliability
and performance.
8. Firewall and Security Appliances
Protecting a database from unauthorized access and attacks is critical.
Firewalls: Hardware-based firewalls, such as those from Cisco ASA, Palo Alto Networks, or
Fortinet, are commonly used to protect database servers from external threats.
Intrusion Detection/Prevention Systems (IDS/IPS): These monitor network traffic and
database activity for malicious behavior (e.g., Cisco Firepower, Snort, IBM QRadar).
9. Data Center Racks
Servers, storage, and networking equipment that support a database are often housed in
specialized racks.
Server Racks: These standardized enclosures (42U racks, for instance) house servers,
switches, and other equipment to keep everything organized and cool (e.g., APC NetShelter,
Panduit).
Rack Accessories: Includes cable management systems, rack-mounted cooling units, and
power distribution units (PDU) to ensure proper organization and efficiency within a data
center.
10. Database Load Balancers
Load balancers distribute database queries and traffic across multiple database servers,
ensuring that no single server is overwhelmed.
Hardware Load Balancers: Devices like F5 Networks BIG-IP, Citrix ADC, or A10 Networks help
balance the traffic load for large database systems.
11. High-Availability and Failover Equipment
To minimize downtime and ensure high availability, databases often rely on equipment that
supports redundancy and failover.
Clustering Solutions: Servers can be configured in clusters to take over the workload if one
fails. Solutions like Microsoft SQL Server AlwaysOn or Oracle Real Application Clusters (RAC)
ensure database high availability.
Failover Servers: Standby servers that automatically or manually take over if the primary
database server fails.
1.3 Functions of where clause
Retrieving data from a table
The SQL WHERE clause is used to filter the results obtained by the DML statements such as
SELECT, UPDATE and DELETE etc.
A. WHERE clause with SELECT statement
Typically, the SELECT statement is used to retrieve data from a table. If we use the WHERE
clause with the SELECT statement, we can filter the rows to be retrieved based on a specific
condition (or expression)
Example: Assume we have created a table named CUSTOMERS in SQL database using
CREATE TABLE statement and inserted some values. The table created is as shown below.
Select ID, Name, Salary from customers where salary > 2000;
ID Name Age Address Salary

1 Tilahun 32 Gulele 2000


2 Kebede 25 Arada 1500
3 Chemdesa 23 Lemikura 2000
4 Fulea 25 Kality 6500
5 Kemal 27 Yeka 8500
6 Momona 22 Lafto 4500
7 Tibletse 24 Bole 10000
B. WHERE clause with UPDATE statement
The UPDATE statement is used to modify the existing records in a table.
Example: by using the previous customers table, we are incrementing the salary of the
customer named Ramesh by 10000 by using the WHERE clause along with the UPDATE
statement
Update customer set salary= salary + 1000 where Name= ‘Tilahun’;
C. Comparison operators in the WHERE clause
 SQL Comparison Operators test whether two given expressions are the same or
not.
 These operators are used in SQL conditional statements while comparing one
expression with another and they return a Boolean value which can be either TRUE
or FALSE.
 The result of an SQL comparison operation can be UNKNOWN when one or another
operand has its value as NULL.
Operator Description
= Equal to
!= Not equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!< Not less than
!> Not greater than

Example: by using the previous customers table, we can write a query with a
comparison operator
•Select * from customers where age != 25;
D. CREATE INDEX Statement
 The CREATE INDEX statement is used to create indexes in tables. They are used
to retrieve data from the database more quickly than otherwise. The users
cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name ON table_name (column1, column2, ...);
CREATE INDEX index_name ON table_name (column1, column2, ...) ASC or DES;
CREATE INDEX idx_customer_name ON Customers (Name);
SELECT ID, Name FROM Customers WHERE Name = 'Tilahun';

With the index in place, the database engine can quickly locate the row with 'John
Smith' without scanning the entire table.
CREATE INDEX idx_customer_name_country ON Customers (CustomerName,
Country);
SELECT ID, Name, Age FROM Customers WHERE Name = ' Tilahun‘ AND Age = 23;
1.4 Functions of order by clause
 The SQL ORDER BY clause is used to sort the data in either ascending or descending
order, based on one or more columns. This clause can sort data by a single column or
by multiple columns.
 ORDER BY is used with the SQL SELECT statement and is usually specified after the
WHERE, HAVING, and GROUP BY clauses.
 To sort the data in ascending order, we use the keyword ASC.
 To sort the data in descending order, we use the keyword DESC.
1.5 Boolean operators
Boolean operators in SQL are logical operators used to combine or
manipulate conditions in a query.
Operator Description
ALL TRUE if all of the sub query values meet the condition
AND TRUE if all the condition separated by AND is true
ANY TRUE if any of the sub query values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the sub query returns one or more records
IN TRUE if the operand is equal to one of a list of
expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is true
A. WHERE clause with AND, OR operators
We can use AND and OR operators together in SQL to combine multiple conditions in a
WHERE clause to filter rows that meets the specified criteria.
 The AND operator will make sure only those rows are filtered that satisfy all the
conditions.
 The OR operator will filter records that satisfy any one of the specified conditions.
Syntax:- WHERE (condition1 OR condition2) AND condition3;
Example:- Select * from customers where (age = 25 OR salary < 4500) AND (name =
'Chemdesa' OR name = 'Momona');
B. SQL ANY Operator
ANY means that the condition will be true if the operation is true for any of
the values in the range.
ANY operator syntax
SELECT column_name(s) FROM table_name WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Eampe SELECT Name FROM customers WHERE ID = ANY (SELECT ID
FROM customers WHERE salary=2000);
C. SQL BETWEEN Operator
The BETWEEN operator is a logical operator in SQL, that is used to retrieve the data within a
specified range. The retrieved values can be integers, characters, or dates.
Syntax SELECT column_name(s) FROM table_name WHERE column_name BETWEEN
value1 AND value2;
Example:- Select * from customers where age between 20 and 30;
D. NOT BETWEEN Operator
The NOT BETWEEN operator in SQL works in exactly opposite to the BETWEEN operator. This
is used to retrieve the data which is not present in the specified range.
Example: Select * from customers where age not between 20 and 30;
E. WHERE clause with IN operator
Using the IN operator you can specify the list of values or sub query in the where clause.
Select * from customers where name in (‘Tilahun', 'Chemdesa', 'momona');
F. WHERE clause with NOT IN operator
The WHERE clause with NOT IN operator is the negation of WHERE clause with the IN
operator.
Example: by using the previous customers table, we are displaying the records from
CUSTOMERS table, where AGE is NOT equal to 25, 23 and 22.
Select * from customers where age NOT IN (25, 23, 22);
G. SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
Select * from customers where name LIKE 'K%'; name start by ‘k’
H. SQL NOT Operator
The NOT operator is used in combination with other operators to give the
opposite result, also called the negative result.
NOT operator syntax SELECT column1, column2, ... FROM table_name
WHERE NOT condition;
Example :- SELECT CustomerName, Country FROM Customers WHERE Country
NOT = 'USA';
1.6 Elimination of duplicated and null values
Duplicated values
 Duplicates can be a big problem in SQL databases as they can slow down query
performance and waste valuable storage space.
Consider the following facts when using DISTINCT identifier in a SELECT statement:
 In a SELECT statement, include DISTINCT keyword after the SELECT clause.
 Multiple columns can be specified after DISTINCT keyword. In this case, the result set
contains distinct combination of data from these columns.
DISTINCT keyword syntax
SELECT DISTINCT column1, column2, ...FROM table_name;
Null Value
A null value indicates no value. It means that the column value is absent in a row. A null value
is not the same as a blank space or a zero value. A zero value is an integer and a blank space
is a character while a null value is the one that has been left blank.
To exclude the null values from a table we need to use IS NOT NULL operator with the WHERE
clause. IS NOT NULL Operator is used to test for non-empty values.
IS NOT NULL operator syntax:
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
Example Join operator
Let's use two tables again:

Customers Table:
CustomerID CustomerName
1 John Smith
2 Maria Garcia
3 Liu Wei
4 Emma Jones

Orders Table:
OrderID CustomerID OrderDate
101 1 2024-01-10
102 2 2024-02-12
103 1 2024-03-15
104 5 2024-05-19
1.7 Functions of join operator
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. Types of join operator
A. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN operator syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example SELECT Customers.CustomerName, Orders.OrderID, Orders.OrderDate FROM
Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result table:
CustomerName OrderID OrderDate
John Smith 101 2024-01-10
John Smith 103 2024-03-15
Maria Garcia 102 2024-02-12
B. SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the matching
records from the right table (table2). The result is 0 records from the right side, if there
is no match.
LEFT JOIN keyword syntax
SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
Example SELECT Customers.CustomerName, Orders.OrderID, Orders.OrderDate
FROM Customers LEFT JOIN Orders ON Customers.CustomerID =
Orders.CustomerID;
Result table:
Customer Name Order ID Order Date
John Smith 101 2024-01-10
John Smith 103 2024-03-15
Maria Garcia 102 2024-02-12
Liu Wei NULL NULL
Emma Jones NULL NULL
C. SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and
the matching records from the left table (table1). The result is 0 records from the
left side, if there is no match.
RIGHT JOIN Syntax
•SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SELECT Customers.CustomerName, Orders.OrderID, Orders.OrderDate
FROM Customers RIGHT JOIN Orders ON Customers.CustomerID =
Orders.CustomerID;
Result table:
Customer Name OrderID Order Date
John Smith 101 2024-01-10
John Smith 103 2024-03-15
Maria Garcia 102 2024-02-12
NULL 104 2024-05-19
D. SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1)
or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
•SELECT column_name(s)
FROM table1 FULL OUTER JOIN table2
ON table1.column_name = table2.column_name WHERE condition;
•SELECT Customers.CustomerName, Orders.OrderID, Orders.OrderDate FROM
Customers FULL OUTER JOIN Orders ON Customers.CustomerID =
Orders.CustomerID;
Note: FULL OUTER JOIN can potentially return very large result-sets!

CustomerName OrderID OrderDate


John Smith 101 2024-01-10
John Smith 103 2024-03-15
Maria Garcia 102 2024-02-12
Liu Wei NULL NULL
Emma Jones NULL NULL
NULL 104 2024-05-19
1.8 Functions of union operator
 The UNION operator is used to combine the result-set of two or
more SELECT statements.
 Every SELECT statement within UNION must have the same number of
columns
 The columns must also have similar data types
 The columns in every SELECT statement must also be in the same order
UNION operator syntax SELECT column_name(s) FROM table1 UNION
SELECT column_name(s) FROM table2;
UNION operator with where clause syntax
 SELECT column_name(s) FROM table1 WHERE condition1 UNION
SELECT column_name(s) FROM table2 WHERE condition2
Example
Suppose we have two tables:
Customers_2023 Table:
CustomerID CustomerName
1 John Smith
2 Maria Garcia
3 Liu Wei
Customers_2024 Table:
Customer ID Customer Name
2 Maria Garcia
4 Emma Jones
5 Michael Brown

If we want to get a list of unique customers from both 2023 and 2024, we can use
the UNION operator:
SELECT CustomerID, CustomerName FROM Customers_2023 UNION
SELECT CustomerID, CustomerName FROM Customers_2024;

Result:
Customer ID Customer Name
1 John Smith
2 Maria Garcia
3 Liu Wei
4 Emma Jones
5 Michael Brown

NB:- The UNION removes the duplicate customer (Maria Garcia) and
returns a combined list of unique customers from both tables.
Using UNION ALL
If we want to include duplicates (i.e., show all entries even if they exist in both
tables), we can use UNION ALL: example
SELECT CustomerID, CustomerName FROM Customers_2023 UNION ALL
SELECT CustomerID, CustomerName FROM Customers_2024;

Result with UNION ALL:


Customer ID Customer Name
1 John Smith
2 Maria Garcia
3 Liu Wei
2 Maria Garcia
4 Emma Jones
5 Michael Brown

NB:- With UNION ALL, the duplicate entry for Maria Garcia
appears twice because it exists in both tables.
1.9 Data control language
 DCL stands for Data Control Language in Structured Query Language (SQL). As the name
suggests these commands are used to control privilege in the database.
 DCL command is a statement that is used to perform the work related to the rights,
permissions, and other control of the database system.
Need Of DCL commands
 Unauthorized access to the data should be prevented in order to achieve security in our
database
 DCL commands maintain the database effectively than anyone else other than database
administrator is not allowed to access the data without permission.
 These commands provide flexibility to the data administrator to set and remove
database permissions in granular fashion. Type of DCL commands
A. GRANT
This command is used to grant permission to the user to perform a particular operation on
a particular object.
Syntax: GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
B. REVOKE
This command is used to take permission/access back from the user.
Syntax: REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
1.10 Transaction control language
 Transactions group a set of tasks into a single execution unit. Each transaction begins
with a specific job and ends when all the tasks in the group successfully completed. If
any of the tasks fail, the transaction fails. Therefore, a transaction has only two
results: success or failure. BEGIN:
 Incomplete steps result in the failure of the transaction. A database transaction, by
definition, must be atomic, consistent, isolated, and durable.
These are popularly known as ACID properties. These properties can ensure the
concurrent execution of multiple transactions without conflict.
Properties of Transaction
 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.
1. COMMIT
This command is used to save the data permanently.
Whenever we perform any of the DML command like -INSERT, DELETE or UPDATE, these can be
rollback if the data is not stored permanently.
Syntax: commit;
Example : UPDATE STUDENT SET NAME = ‘Sherlock’ WHERE NAME = ‘Jolly’;
COMMIT;
ROLLBACK;
By using the above command, you can update the record and save it permanently by
using COMMIT command.
2. ROLLBACK
This command is used to get the data or restore the data to the last savepoint or last
committed state. If due to some reasons the data inserted, deleted or updated is not correct,
you can roll back the data to a particular savepoint or if savepoint is not done, then to the last
committed state.
Syntax: rollback;
UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE NAME = ‘Jolly’;
COMMIT;
ROLLBACK;
By using the above command, you can update the record and save it permanently by
using COMMIT command.
3. SAVEPOINT
This command is used to save the data at a particular point temporarily, so that
whenever needed can be rollback to that particular point.
Syntax: Savepoint A;
INSERT into STUDENT VALUES ('Jack', 95);
Commit;
UPDATE NAME SET NAME= ‘Rossie’ WHERE marks= 70;
SAVEPOINT A;
INSERT INTO STUDENT VALUES (‘Zack’, 76);
SAVEPOINT B;
INSERT INTO STUDENT VALUES (‘Bruno’, 85);
SAVEPOINT C;
SELECT * FROM STUDENT;

Key Differences between DML and TCL


Functionality: DML changes or retrieves data within tables, while TCL manages
transactions to ensure data consistency.
Usage: DML is used for operations on data (like inserting or updating rows),
whereas TCL is used to commit or rollback these changes to maintain data
integrity.
Data Integrity: TCL controls the atomicity and consistency of multiple DML
operations as a single unit of work.
BEGIN TRANSACTION; -- Subtract $200 from John Smith's account
UPDATE Accounts SET Balance = Balance – 200 WHERE AccountID = 1;
SAVEPOINT sp1; -- Set a savepoint after the first operation
-- Add $200 to Maria Garcia's account
UPDATE Accounts SET Balance = Balance + 200 WHERE AccountID = 2;
-- Rollback to savepoint sp1 if something goes wrong in the second operation
IF (SELECT Balance FROM Accounts WHERE AccountID = 2) < 0
BEGIN
ROLLBACK TO sp1; -- Undo the second operation only
PRINT 'Transaction failed at second step';
END; -- Commit the transaction if no errors occur
COMMIT; -- The other example
BEGIN TRANSACTION; -- Subtract $200 from John Smith's account
UPDATE Accounts SET Balance = Balance – 200 WHERE AccountID = 1;
-- Simulate an error (e.g., trying to debit more than available)
IF (SELECT Balance FROM Accounts WHERE AccountID = 2) < 0
BEGIN
ROLLBACK; -- Undo all changes
PRINT 'Transaction failed: Insufficient funds';
RETURN;
END; -- Add $200 to Maria Garcia's account
UPDATE Accounts SET Balance = Balance + 200 WHERE AccountID = 2; -- Commit the
transaction if no errors occur
COMMIT;
Chapter Two: SQL statements with functions

This unit is developed to provide you the necessary


information regarding the following content coverage
and topics

 Arithmetic operations
 String functions and operators
 Mathematical functions
 Date functions
2.1 Arithmetic operations
 Arithmetic operators can perform arithmetical operations on numeric operands
involved. Arithmetic operators are addition (+), subtraction (-),
multiplication (*) and division (/).
 Arithmetic operations syntax:
 SELECT column_name arithmetic operator FROM [table_name]
WHERE [expression];

Operator Meaning
+(Add) Addition
-(Subtract) Subtraction
*(Multiply) Multiplication
/(Divide) Division
%(Modulo) Returns the integer reminder of a division
Example Table: employee
id name salary bonus
1 Temesgen 5000 500
2 Blin 6000 700
3 Chernet 5500 650
4 kebede 6001 803

 SELECT name, salary + bonus AS total_Amount FROM employee;


 SELECT name, salary - bonus AS Net_Amount FROM employee;
 SELECT name, (salary + bonus)*2 AS Amount FROM employee;
 SELECT name, (salary + bonus)/2 AS Average FROM employee;
 SELECT name, salary + bonus AS total_Amount FROM employee
where salary%2=0;
2.2. String functions and operators
The following table shows some string functions. All string functions
works with the select statement.

Function Description
ASCII Returns the ASCII for the specified character
CHAR Returns the character based on ASCII
CHARINDEX Returns the position of a substring in a string
DATALENGTH Returns the number of bytes used to represent an expression
DIFFERENCE Compare two SOUNDEX values and returns integer value
LEFT Extract a number of characters by starting from the left
UPPER Convert a string in to upper case
LTRIM Remove leading spaces from a string
SUBSTRING Extract some characters from a string
REPLICATE Replicates a string a specified number of times
Example Table: customer
id name email

1 John Abera [email protected]

2 Adenekush Brhanu Adenekush @yahoo.com

3 Abiel John [email protected]


The ASCII () ASCII syntax ASCII (character)
1. SELECT name, ASCII(name) AS ascii_value FROM customer;
2. SELECT name FROM customer WHERE ASCII(name) = 66;
3. SELECT name, ASCII(name) AS ascii_value FROM customer ORDER BY ascii_value;
4. SELECT ASCII('Z') AS ascii_value;
The CHAR () CHAR syntax CHAR (code)
Ascii table example

id ascii_code
1 65
2 66
3 67
 SELECT CHAR(72) + CHAR(69) + CHAR(76) + CHAR(76) + CHAR(79) AS greeting;
 SELECT ascii_code, CHAR(ascii_code) AS character FROM codes;
The CHARINDEX () CHARINDEX syntax CHARINDEX (substring, string, start)
Example Table: documents
id content
1 SQL is a powerful language.
2 CHARINDEX is very useful.
3 Learning SQL is fun!

SELECT content, CHARINDEX('SQL', content) AS position FROM documents;


Output:
content position
SQL is a powerful language. 1
CHARINDEX is very useful. 0
Learning SQL is fun! 10

SELECT content, CHARINDEX('is', content) AS position FROM documents;


The DATALENGTH () DATALENGTH syntax DATALENGTH (expression)
 SELECTname, DATALENGTH(name) AS byte_length FROM customer;
 SELECT content, LEN(content) AS length_without_spaces,
DATALENGTH(content) AS length_with_spaces FROM documents;
The DIFFERENCE () DIFFERENCE syntax DIFFERENCE (expression, expression)
The two expressions are to be compared. Can be contrast, variable or column
The LEFT () LEFT syntax LEFT (string, number_of_chars)

Example Table: products


product_id product_name
1 Laptop Pro 15
2 Smartwatch Series 5
3 Wireless Mouse
4 Bluetooth Speaker

SELECT product_name, LEFT(product_name, 7) AS prefixFROM products;


Output:
product_name prefix
Laptop Pro 15 Laptop
Smartwatch Series 5 Smartwa
Wireless Mouse Wireles
Bluetooth Speaker Bluetoo

SELECT product_name, LEFT(product_name, 4) AS short_name FROM products;


SELECT * FROM products WHERE LEFT(product_name, 5) = 'Smar'; it have 5 letter
smar
SELECT product_name, UPPER(LEFT(product_name, 3)) AS initials
FROM products;
output
product_name initials
Laptop Pro 15 LAP
Smartwatch Series 5 SMA
Wireless Mouse WIR
Bluetooth Speaker BLU
The UPPER () UPPER syntax UPPER (text)
SELECT UPPER(name) AS name_uppercase FROM customers;
The LTRIM () LTRIM syntax LTRIM (string)
 SELECT lname, LTRIM(RTRIM(lname)) AS trimmed_name FROM customer; both remove
right and left space
 SELECT lname, LTRIM(lname) AS trimmed_name FROM customer; remove left space
 SELECT lname, RTRIM(lname) AS trimmed_name FROM customer; remove right space
The SUBSTRING () SUBSTRING syntax SUBSTRING (string, start, length)
SELECT SUBSTRING('Hello, World!', 1, 5) AS ExtractedSubstring; output: Hello
SELECT SUBSTRING('SQL Server', 5, 6) AS ExtractedSubstring; output: Server
The REPLICATE () REPLICATE syntax REPLICATE (string, integer)
SELECT REPLICATE('SQL', 3) AS RepeatedString; output: SQLSQLSQL
SELECT REPLICATE('*', 5) AS StarPattern; output: *****

Length :- SELECT name, LENGTH(name) AS name_length FROM customers;


2.3 Mathematical functions
The following table shows some mathematical functions. All string functions works
with the SELECT statement.
Function Description
COUNT Returns the number of records returned by a select query.
Syntax:- COUNT (expression)
AVG Returns the average value of an expression. Syntax:- AVG(expression)
DEGREES Converts a value in radians to degrees. Syntax:- DEGREES (number)
MAX Returns the maximum value in a set of values. Syntax:- MAX(expression)
SQUARE Returns the square of a number. Syntax:- SQUARE(number)
SUM Calculates the sum of a set of values. Syntax:- MAX(expression)
POWER Calculates the sum of a set of values. Syntax:- POWER (a, b)
A parameter is a number (the base) and B parameter is a number (the
exponent)
TAN Returns the tangent of a number. Syntax:- TAN(number)
COS Returns cosine of a number. Syntax:- COS (number)
CEILING Returns the smallest integer value that is >= a number.
Syntax:- CEILING (number)
1. CEILING FUNCTION
SELECT CEILING(123.456) AS Result; -- Returns 124
SELECT CEILING(-123.456) AS Result; -- Returns -123
2. FLOOR FUNCTION
SELECT FLOOR(123.456) AS Result; -- Returns 123
SELECT FLOOR(-123.456) AS Result; -- Returns -124

3. ROUND FUNCTION
SELECT ROUND(123.456, 2) AS Result; -- Returns 123.46
SELECT ROUND(123.456, 0) AS Result; -- Returns 123
SELECT ROUND(123.456, -1) AS Result; -- Returns 120
4. TRUNCATE FUNCTION
SELECT TRUNCATE(123.456, 2) AS Result; -- Returns
123.45 (truncated) = ‘ORACLE DATABASE KEY WORD’
The advantage of truncate remove the data after
assign
2.4 Date functions
1.The following table shows some date functions

Function Description
CURRENT_TIMESTAMP Returns the current date and time
DATEADD Adds a time/date interval to a date and then returns the date
DATEDIFF Returns the difference between two dates
DATEPART Returns a single part of a date/time
CONVERT Displays date/time data in different formats
GETDATE Returns the current database system date and time
The CURRENT_TIMESTAMP function returns the current date and time, in a 'YYYY-MM-DD
hh:mm:ss.mmm' format.
CURRENT_TIMESTAMP syntax CURRENT_TIMESTAMP /
The DATEADD () function adds or subtracts a time/date interval to a date and then returns the
date.
DATEADD () syntax DATEADD (datepart, number, date)
Interval parameter is to add time/date interval. Can be one of the following values:
yyyy, yy = Year
qq, q = Quarter
Common Date Parts (datepart):
mm, m = month
•year or yy or yyyy: Adds years.
dy, y = Day of the year
day, dd, d = Day
•month or mm or m: Adds months.
ww, wk = Week •day or dd or d: Adds days.
dw, w = Weekday •hour or hh: Adds hours.
hh = hour •minute or mi or n: Adds minutes.
mi, n = Minute •second or ss or s: Adds seconds.
ss, s = Second
ms = Millisecond
 SELECT DATEADD(day, 5, '2024-11-27') AS NewDate;
 SELECT DATEADD(month, -2, '2024-11-27') AS NewDate;
 SELECT DATEADD(year, 1, GETDATE()) AS NextYearDate;
 SELECT DATEADD(hour, 3, '2024-11-27 10:00:00') AS NewDateTime;
 SELECT DATEADD(second, -30, '2024-11-27 10:00:00') AS NewDateTime;
The DATEDIFF () function returns the difference between two dates.
DATEDIFF () syntax
DATEDIFF (date_part, start_date, end_date)
 SELECT DATEDIFF(day, '2024-11-01', '2024-11-27') AS DaysDifference;
 SELECT DATEDIFF(month, '2024-11-01', '2024-11-27') AS monthDifference;
 SELECT DATEDIFF(year, '2024-11-01', '2024-11-27') AS yearsDifference;
 SELECT DATEDIFF(hour, '2024-11-01', '2024-11-27') AS hoursDifference;
SELECT ROUND(CAST(DATEDIFF(DAY, DOB, GETDATE()) AS FLOAT) / 365.25, 2)
AS Age FROM mereja;

CAST(... AS FLOAT): Ensures that the division yields a decimal result.


/ 365.25: Divides by 365.25 to estimate the age in years, considering leap years.
Example:
If DOB is 2020-01-01 and today’s date is 2023-11-29, the calculation would be:
Days between 2020-01-01 and 2023-11-29: 1427 days.
Age calculation: 1427 / 365.25 ≈ 3.91
The DATEPART () function is used to return a single part of a date/time, such as year,
month, day, hour, minute, etc.
DATEPART () syntax DATEPART (datepart,date)
 year or yy or yyyy: Extracts the year.
 month or mm or m: Extracts the month.
 day or dd or d: Extracts the day of the month.
 hour or hh: Extracts the hour.
 minute or mi or n: Extracts the minute.
 second or ss: Extracts the second.
Example:- SELECT DATEPART(year, '2024-11-29') AS YearPart;
-- Output: 2024
SELECT DATEPART(second, '2024-11-29 14:45:30') AS SecondPart;
-- Output: 30
SELECT * FROM Sales WHERE DATEPART(year, SaleDate) = 2024;

SELECT DATEPART(month, SaleDate) AS SaleMonth, COUNT(id)


FROM Sales GROUP BY DATEPART(month, SaleDate);
The CONVERT () function is a general function that converts an expression of one data type to
another. The CONVERT () function can be used to display date/time data in different formats.
CONVERT () syntaxCONVERT (data_type(length),expression,style)
Example:- SELECT CONVERT(datetime, '2024-11-29', 120) AS DateValue;
-- Output: 2024-11-29 00:00:00.000 (YYYY-MM-DD format)
The 120 style is used for the YYYY-MM-DD HH:MI:SS format.
Style Codes for Date/Time Formatting
Style Code Format SELECT CONVERT(varchar, GETDATE(), 105) AS
100 mon dd, yyyy DateFormatted;
101 mm/dd/yyyy -- Output: 29-11-2024
102 yyyy.mm.dd SELECT CONVERT(varchar, GETDATE(), 120) AS
103 dd/mm/yyyy
DateTimeFormatted;
104 dd.mm.yyyy
-- Output: 2024-11-29 15:30:45
105 dd-mm-yyyy SELECT CONVERT(datetime, '11/29/2024', 101)
106 dd mon yyyy AS DateValue;
107 Mon dd, yyyy -- Output: 2024-11-29 00:00:00.000
108 hh:mm:ss SELECT CONVERT(datetime, '2024.11.29', 102)
109 mon dd, yyyy hh:mm:ss:nn AS DateValue;
110 mm-dd-yyyy -- Output: 2024-11-29 00:00:00.000
111 yyyy/mm/dd
112 yyyymmdd
SELECT CAST(GETDATE() AS varchar) AS CastDate;
113 dd mon yyyy hh:mm:ss:nn
-- Output: 2024-11-29 15:30:45.123
120 yyyy-mm-dd hh:mi:ss
The GETDATE () function returns the current date and time from the SQL Server.
GETDATE () syntax GETDATE ()

SELECT GETDATE() OR
select CURRENT_TIMESTAMP;
-- Both will return the same result
Comparison with CURRENT_TIMESTAMP
•GETDATE() and CURRENT_TIMESTAMP are functionally equivalent in SQL
Server; both return the current date and time.
SELECT * FROM Orders
WHERE OrderDate > DATEADD(day, -30, GETDATE()); -- Orders from the last 30 days

SELECT DATEPART(year, GETDATE()) AS CurrentYear;


-- Output: 2024 (year part)

SELECT DATEPART(month, GETDATE()) AS CurrentMonth;


-- Output: 11 (month part)

SELECT DATEPART(day, GETDATE()) AS CurrentDay;


-- Output: 29 (day part)
Chapter Three: SQL statements with aggregation and
filtering

This unit is developed to provide you the


necessary information regarding the following
content coverage and topics
 Function of group by statement
 Function of having clause
 Backup database
3.1. Function of group by statement
 The GROUP BY statement groups rows that have the same values into summary rows. It
is often used with aggregate functions (COUNT (), MAX (), MIN (), SUM (), AVG ()) to
group the result-set by one or more columns.
 The GROUP BY Statement in SQL is used to arrange identical data into groups with the
help of some functions. i.e., if a particular column has the same values in different
rows, then it will arrange these rows in a group.
Features
 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.
GROUP BY Syntax
SELECT column_name(s) Where clause Example :- SELECT COUNT(eid),
FROM table_name departmentFROM employee where age >=
WHERE condition 20GROUP BY departmentORDER BY COUNT
GROUP BY column_name(s) (eid) DESC;
ORDER BY column_name(s);
SELECT COUNT(eid), department FROM employee
Example :-
GROUP BY department ORDER BY COUNT (eid) DESC;
GROUP BY With JOIN
SELECT Shippers.ShipperName, COUNT
(Orders.OrderID) AS NumberOfOrders from Orders
LEFT JOIN Shippers ON Orders.ShipperID =
Shippers.ShipperID GROUP BY ShipperName;Sorting
aggregated data

GROUP BY With ORDER BY CLAUSE


you can sort aggregate data using the ORDER BY clause in
combination with the aggregate functions. Sorting aggregate
data in SQL Server involves using aggregate functions to
calculate summary values and then sorting the result set
based on those calculations
3.2. Function of having clause
 The HAVING clause was introduced in SQL to allow the
filtering of query results based on aggregate functions and
groupings, which cannot be achieved using the WHERE
clause that is used to filter individual rows.
 In simpler terms MYSQL, the HAVING clause is used to apply
a filter on the result of GROUP BY based on the specified
condition. The conditions are Boolean type i.e. use of logical
operators (AND, OR). This clause was included in SQL as the
WHERE keyword failed when we use it with aggregate
expressions. Having is a very generally used clause in SQL.
Similar to WHERE it helps to apply conditions, but HAVING
works with groups. If you wish to filter a group, the HAVING
clause comes into action.
Some important points:
 Having clause is used to filter data according to the
conditions provided.
 Having a clause is generally used in reports of large data.
 Having clause is only used with the SELECT clause.
 The expression in the syntax can only have constants.
 In the query, ORDER BY is to be placed after the HAVING
clause, if any.
 HAVING Clause is implemented in column operation.
 Having clause is generally used after GROUPBY.
The main difference between where and having clause
Where Clause in SQL Having Clause in SQL

Applied before GROUP BY clause Used after GROUP BY clause

Used with single row operations such Applicable with multiple row functions
as Upper, Lower and so on such as Sum, count and so on

Where clause Example:- SELECT COUNT(eid), departmentFROM employee


where age >= 20 GROUP BY departmentORDER BY COUNT (eid) DESC;
HAVING clause syntax
SELECT col_1, Example SELECT COUNT
function_name(col_2) (CustomerID), Country
FROM tablename FROM Customers
WHERE condition GROUP BY Country
GROUP BY column1, column2 HAVING COUNT (CustomerID) > 5
HAVING Condition ORDER BY COUNT
ORDER BY column1, column2 (CustomerID) DESC;
3.4. Backup database
The BACKUP DATABASE statement is used in SQL Server to create a full back up of
an existing SQL database.
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
Backup with differential
A differential backup reduces the backup time (since only the changes are backed
up).
The following SQL statement creates a differential back up of the database
"testDB":
Example: BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;

You might also like