TM03 Use Advanced Structured Query Language
TM03 Use Advanced Structured Query Language
Administration
Level IV
Based on November, 2023 Version-II Curriculum
November, 2023
For effective use this modules trainees are expected to follow the following module instructions
This unit is developed to provide you the necessary information regarding the following content
coverage and topics
• DBMS fundamentals
• Information-based 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
This unit will also assist you to attain the learning outcomes stated in the cover page.
Specifically, upon completion of this learning guide, you will be able to:
• Understand fundamentals of DBMS and identify database tools and equipment
• Retrieve specific columns and sort query output
• Use Boolean operators
• Eliminate duplicated and null values
• Retrieve data from two or more tables
• Combine the result-set of two or more SELECT statements
• Grant and revoke a database
• Understand TCL
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. In addition, the database system must ensure the safety of the
information stored, despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous results. So Understanding
the fundamentals of DBMS is crucial for anyone working with databases, whether as a database
administrator, data analyst, or software developer.
1. Data Organization: One of the primary functions of a DBMS is to organize data in a structured
manner. It provides a logical framework, known as a schema, which defines the structure and
relationships of the data. The schema includes tables, which consist of rows (records) and
columns (attributes). By organizing data into tables, DBMS ensures data integrity, consistency,
and easy access.
2. Data Retrieval: DBMS allows users to retrieve data from databases using queries. Queries are
written in a language called Structured Query Language (SQL), which is a standard language
for interacting with relational databases. With SQL, users can specify the desired data, apply
To begin with, it is essential to assess the data volume and complexity of your project. If you are
dealing with large datasets or complex data structures, you may need a robust database
Security is another critical aspect to consider when selecting database tools and equipment. If your
organization deals with sensitive or confidential data, you should prioritize tools that offer robust
security features such as encryption, access controls, and auditing capabilities. Database systems
like PostgreSQL and Microsoft SQL Server provide advanced security features to protect your
data from unauthorized access or breaches.
Performance requirements play a significant role in determining the appropriate database tools and
equipment. If your application or project demands high-speed data processing and retrieval, you
might consider in-memory databases like Redis or Apache Ignite. These databases store data in
memory, enabling faster access and query execution compared to traditional disk-based databases.
Scalability is also a crucial factor to consider, especially if your project is expected to grow in
terms of data volume or user base. Tools like Apache Cassandra or MongoDB are known for their
ability to handle massive amounts of data and provide horizontal scalability, allowing you to add
more servers to accommodate increasing demands.
In this module, we will be using Microsoft SQL Server as the database management system for
learning and practicing advanced SQL concepts. SQL Server is a popular and widely-used open-
source relational database management system that provides a robust and scalable platform for
storing, managing, and retrieving data.
SQL Server offers a comprehensive set of features and functionalities that make it an ideal choice
for learning advanced SQL. It supports a wide range of SQL commands and syntax, allowing us
to explore and practice various advanced techniques effectively. Additionally, SQL Server has
excellent performance and reliability, making it suitable for handling large datasets and complex
You can use SQL to retrieve the columns of a database table with the SELECT statement. You
can retrieve all columns, a single column, or several specific columns. It is then up to your
programming language to display that data.
You can write a query to retrieve all the elements in a database table by using the SELECT
statement and wildcard (*) indicator.
Note: It is standard practice to add ";" at the end of your SQL query.
The most common query from a database is to collect or retrieve all the elements in a specific
column of the database table.
You can also retrieve data from several columns by separating the column names with a comma.
Note: Do not place a comma after the last item in the list, because it will result in an error
message.
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.
In the following query, we are fetching the ID, NAME and SALARY fields from the
CUSTOMERS table for the records where the SALARY is greater than 2000
➢ Select ID, Name, Salary from customers where salary > 2000;
ID Name Salary
4 Fulea 6500
5 Kemal 8500
6 Momona 4500
7 Tibletse 10000
• WHERE clause with UPDATE statement
The UPDATE statement is used to modify the existing records in a table. Using the SQL WHERE
clause with the UPDATE statement, we can update particular records. If the WHERE clause is not
used, the UPDATE statement would affect all the records of a table. Following is the syntax.
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
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
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.
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. Sorting by multiple columns can be helpful when you need to sort data hierarchically,
such as sorting by state, city, and then by the person's name.
ORDER BY is used with the SQL SELECT statement and is usually specified after the WHERE,
HAVING, and GROUP BY clauses.
In addition to sorting records in ascending order or descending order, the ORDER BY clause can
also sort the data in a database table in a preferred order.
Operator Description
ALL TRUE if all of the sub query values meet the condition
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.
ALL means that the condition will be true only if the operation is true for all values in the range.
➢ Select * from customers where (age = 25 OR salary < 4500) AND (name =
'Chemdesa' OR name = 'Momona');
ID Name Age Address Salary
ANY means that the condition will be true if the operation is true for any of the values in the
range.
✓ SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Example: in the following example if we want to retrieve name of the customers whose salary is
2000, we can write this query
✓ SELECT Name
FROM customers
WHERE ID = ANY
(SELECT ID
FROM customers
WHERE salary=2000;
Name
Tilahun
Chemdesa
➢ SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example: by using the previous customers table, we can write a query that will display all
customers whose age is between 20 and 30.
Example: by using the previous customers table, we can write a query that will display all
customers whose name starts between the a and g.
Example: Select * from customers where age not between 20 and 30;
➢ SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
• WHERE clause with IN operator
Using the IN operator you can specify the list of values or sub query in the where clause. If you
use WHERE and IN with the SELECT statement, it allows us to retrieve the rows in a table that
match any of the values in the specified list. Following is the syntax for it
Example: by using the previous customers table, suppose you want to display records with
NAME values Khilan, Hardik and Muffy from the CUSTOMERS table, you can use the
following query
The WHERE clause with NOT IN operator is the negation of WHERE clause with the IN
operator.
✓ If you use WHERE with the IN operator, the DML statement will act on the list of values
(of a column) specified
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.
When the result set from a SELECT statement contains duplicate rows, you may want to remove
them and keep every row data to be unique for a column or combination of columns. You can use
the DISTINCT identifier to eliminate duplicate records from the result set.
Consider the following facts when using DISTINCT identifier in a SELECT statement:
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.
➢ SELECT column_names
FROM table_name WHERE column_name IS NOT NULL;
The INNER JOIN keyword selects records that have matching values in both tables. It is the
most common type of join. Inner joins combine records from two tables whenever there are
matching values in a field common to both tables.
Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have
matching values in two or more tables. This join is based on a logical relationship (or a common
field) between the tables and is used to retrieve data that appears in both tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
• 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.
➢ 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.
➢ 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.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
➢ SELECT column_name(s)
FROM table1 FULL OUTER JOIN table2
ON table1.column_name = table2.column_name WHERE condition;
Every SELECT statement within UNION must have the same number of columns
The columns in every SELECT statement must also be in the same order
• 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.
GRANT
This command is used to grant permission to the user to perform a particular operation on a
particular object. If you are a database administrator and you want to restrict user accessibility
such as one who only views the data or may only update the data. You can give the privilege
permission to the users according to your wish.
Syntax:
This command is used to take permission/access back from the user. If you want to return
permission from the database that you have granted to the users at that time you need to run
REVOKE command.
Syntax:
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
If commit was not performed then the changes made by the update command can be rollback.
• UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE STUDENT_NAME = ‘Jolly’;
After update command the table will be:
rollback;
After Rollback:
Rollback to B;
Rollback to A;
1. The inner join technique is useful when data from several relations are to be retrieved and
displayed and the relationships are not necessarily nested.
2. The UNION clause is used to combine the output from multiple queries together into a
single result table.
3. With the UNION clause, each query involved must output the same number of columns,
and they must be UNION compatible.
4. Difference between WHERE and HAVING clause is that the WHERE clause allows
you to filter data from a group of rows.
5. You can’t use aggregate functions with order by clause.
6. Both group by and order by clauses serve similar function with similar purpose.
Part II: Choose the best answer
Purpose: To create a merchant database with customer, supplier, customer_order, orderItem and
product table their respective relationships
In order to create customer table, we will write the following SQL statement
Step 7: To retrieve the supplier table, we can write the following SQL statement
Step 10: To retrieve the Customer_order table, we can write the following SQL statement
➢ Select * from Customer_order
Quality Criteria: your output should look like this
Step 16: To retrieve the Product table, we can write the following SQL statement
Step 2: here we want to retrieve customers whose country is Mexico, so we can write the
following query
Step 3: here we want retrieve orders whose unit price is greater than 30, so we can write the
following SQL statement
Step 4: here we want retrieve to list products with order quantities greater than or equal to 15, so
we can write the following SQL statement
Step 1: Use the above merchant database from operation sheet 1.1
Step 2: here we want to retrieve 50% of the customers record, so we can write the following
SQL statement
Step 3: here we want to list all suppliers with the number of products they offer, so we can write
the following SQL statement
➢ SELECT CompanyName,
ProductCount = (SELECT COUNT(P.id)
FROM [Product] P
WHERE P.SupplierId = S.Id)
FROM Supplier S order by companyname DESC
Step 4: here we want to list all French customer cities (without duplicates)
Step 5: here we want to list all suppliers that have no fax, we can write the following query
Step 1: Use the above merchant database from operation sheet 1.1
Step 2: Here we want to list all products that are packaged in jars, we can write the following
query
➢ SELECT *
FROM Product
WHERE Package LIKE '%jars%'
Quality Criteria: your output should look like this
Step 3: here we want to list customers with orders over $2000, we can write the following query
➢ SELECT *
FROM Customers
WHERE EXISTS
(SELECT Id
FROM [customer_Order]
WHERE CustomerId = Customers.Id
AND TotalAmount > 2000)
Step 4: here we want to list customers who are from London or Paris, we can write the following
query
➢ SELECT firstname
FROM Customers
WHERE City IN ('Paris','London')
Quality Criteria: your output should look like this
Purpose: To show functionalities of Join, left join, right join and full join
Step 1: Use the above merchant database from operation sheet 1.1
Step 2: To List all suppliers with their products we can write the following query
Step 3: To list all suppliers and their products, including suppliers with no products we can write
the following query
Step 4: To list customers that have not placed orders we can write the following query
Step 5: To match all customers and suppliers by country we can write the following query
➢ SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry,
S.Country AS SupplierCountry, S.CompanyName
FROM Customers C
FULL JOIN Supplier S ON C.Country = S.Country
ORDER BY C.Country, S.Country
Purpose: To show functionalities of Join, left join, right join and full join
Step 1: Use the above merchant database from operation sheet 1.1
Task 1
Step 1: To list all unique countries for customers and suppliers we can write the following
statement
➢ SELECT Country
FROM Customers
UNION
SELECT Country
FROM Supplier
Quality Criteria: your output should look like this
Step 1: Use the above merchant database from operation sheet 1.1
Step 2: Imagine we have two database administrators ababe and kebede and we want them to
create a table, insert and delete a data from the tables from the merchant database. So, we can
write the following query (suppose that kebede will grant permission for ababe)
Task 1: Create a database called ABC and create the following tables with their respective
relation.
Customer Table
Orders Table
Task 2: Retrieve the names of customers who have placed orders with an order amount greater
than the average order amount.
Task 4: Retrieve the orders where the order amount is either greater than $5000 or the advance
amount is less than $1000.
Task 5: Retrieve the distinct agent codes from the AGENTS table and the distinct agent codes
from the ORDERS table.
Task 6: Retrieve the customer names and their corresponding working areas.
This unit is developed to provide you the necessary information regarding the following
content coverage and topics
• Arithmetic operations
• Mathematical functions
• Date functions
This unit will also assist you to attain the learning outcomes stated in the cover page.
Specifically, upon completion of this learning guide, you will be able to:
• Understand and use arithmetic operations
• Use string functions and operators
• Understand and use mathematical functions
• Understand and use date functions
Operator Meaning
+(Add) Addition
-(Subtract) Subtraction
*(Multiply) Multiplication
/(Divide) Division
%(Modulo) Returns the integer reminder of a division
Arithmetic operations syntax:
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
➢ ASCII (character)
Character parameter returns the ASCII value. If more than one character is entered, it will only
return the value for the first character
• The CHAR () function returns the character based on the ASCII code.
CHAR syntax
➢ CHAR (code)
Code parameter returns the ASCII number code for the character
• The CHARINDEX () function searches for a substring in a string, and returns the position.
If the substring is not found, this function returns 0.
CHARINDEX syntax
➢ DATALENGTH (expression)
Expression parameter is the one that return data type length
• The DIFFERENCE () function compares two SOUNDEX values, and returns an integer.
The integer value indicates the match for the two SOUNDEX values, from 0 to 4.
0 indicates weak or no similarity between the SOUNDEX values. 4 indicate strong similarity or
identically SOUNDEX values.
DIFFERENCE syntax
• The LEFT () function extracts a number of characters from a string (starting from left).
LEFT syntax
Number_of_chars operator, it is the number of characters to extract If the number exceeds the
number of characters in string, it returns string
➢ UPPER (text)
Text parameter is the string to be converted
➢ LTRIM (string)
String parameter is the one to remove leading spaces from.
Function Description
COUNT Returns the number of records returned by a select query
AVG Returns the average value of an expression
DEGREES Converts a value in radians to degrees
MAX Returns the maximum value in a set of values
SQUARE Returns the square of a number
SUM Calculates the sum of a set of values
POWER Calculates the sum of a set of values
TAN Returns the tangent of a number
COS Returns cosine of a number
CEILING Returns the smallest integer value that is >= a number
• The COUNT () function returns the number of records returned by a select query.
Note: NULL values are not counted.
COUNT () Syntax
➢ COUNT (expression)
Expression parameter is a field or a string value
AVG () syntax
➢ DEGREES (number)
Number parameter is a numeric value
MAX () syntax
➢ MAX (expression)
Expression parameter is a numeric value
➢ SQUARE (number)
Number parameter is a positive number to calculate the square
SUM () syntax
➢ SUM (expression)
Expression parameter is a field or a formula
• The POWER () function returns the value of a number raised to the power of another
number.
POWER () syntax
➢ POWER (a, b)
A parameter is a number (the base) and B parameter is a number (the exponent)
➢ TAN (number)
Number parameter is a numeric value
➢ COS (number)
Number parameter is a numeric value
• The CEILING () function returns the smallest integer value that is larger than or equal to a
number.
CEILING () syntax
➢ CEILING (number)
Number parameter is a numeric value
Function Description
DATEADD Adds a time/date interval to a date and then returns the date
➢ CURRENT_TIMESTAMP
• The DATEADD () function adds or subtracts a time/date interval to a date and then returns
the date.
DATEADD () syntax
✓ yyyy, yy = Year
✓ qq, q = Quarter
✓ mm, m = month
✓ dy, y = Day of the year
✓ day, dd, d = Day
✓ ww, wk = Week
✓ dw, w = Weekday
✓ hh = hour
✓ mi, n = Minute
✓ ss, s = Second
✓ ms = Millisecond
➢ Number parameter is the number of intervals to add to date. Can be positive (to get
dates in the future) or negative (to get dates in the past)
➢ Date parameter is the date that will be modified.
✓ yyyy, yy = Year
✓ qq, q = Quarter
✓ mm, m = month
✓ dy, y = Day of the year
✓ dd, d = Day
✓ ww, wk = Week
✓ dw, w = Weekday
✓ hh = hour
✓ mi, n = Minute
✓ ss, s = Second
✓ ms = Millisecond
➢ start date and end date parameters are the two dates to calculate the difference
between.
• 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)
Where date is a valid date expression and datepart can be one of the following:
✓ yyyy, yy = Year
✓ qq, q = Quarter
CONVERT () syntax
➢ CONVERT (data_type(length),expression,style)
✓ data_type(length) Specifies the target data type (with an optional length)
✓ expression Specifies the value to be converted
✓ style Specifies the output format for the date/time
• The GETDATE () function returns the current date and time from the SQL Server.
GETDATE () syntax
➢ GETDATE ()
Step 2: Calculate the total amount (UnitPrice * Quantity) for each order item and display the
result with the order item ID and the total amount.
Step 3: To retrieve the product names that start with the letter "A" and display them in uppercase.
Step 2: let us create a table called orders which stores orders of customers with their order id,
product name and the date, which the order is placed. We can write the table as shown below
Step 3: to insert order data in the orders table we can write the following statement
Step 4: From the previous table, if we want to retrieve the date in year, month, date format, we
can write the following query
Step 5: If we want to add 30 days to the "OrderDate", to find the payment date. We can write the
following query
Task 2: Calculate the total amount (ORD_AMOUNT + ADVANCE_AMOUNT) for each order
and display the result with the order number and the total amount.
Task 3: Calculate the average commission for all agents and display the result rounded to two
decimal places.
This unit is developed to provide you the necessary information regarding the following content
coverage and topics
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 Syntax
➢ SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
If we want to retrieve the number of orders sent by each shipper, we can write the following
SQL statement
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
Used with single row operations such as Applicable with multiple row functions such
Upper, Lower and so on as Sum, count and so on
FROM tablename
WHERE condition
3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
If we want to lists the number of customers in each country. And only include countries with
more than 5 customers: the SQL statement will be
Syntax
The following SQL statement creates a differential back up of the database "testDB":
Purpose: To sort aggregated data using group by, order by and having clause. And to be able to
back up the database.
Step 2: To retrieve the total order amount for each customer and sort the result in descending
order of the sum.
Step 3: To list the number of products for each supplier, sorted high to low.
Step 5: To perform full back up the merchant database we can write the following query (but
first we have to create backups folder in the specified location)
Task 1: Retrieve the total order amount for each customer and display the result with the
customer code and their total order amount.
Task 2: Retrieve the agents who have a commission greater than 5,000 and display their agent
code and commission.
Task 3: Create a full backup of the database ABC and specify the backup file path as
"C:\Backup\ABC.bak".
SQL Server Transaction Log Management by Tony Davis and Gail Shaw 1st edition
The 45 Database Performance Tips for Developers by Phil Factor, Grant Fritchey 3rd edition
The 119 SQL Code Smells by Tony Davis and Gail Shaw 3rd edition
URL
https://www.freebookcentre.net/Database/Sql-Server-Books-Download.html
https://www.w3schools.com/sql/default.asp
https://www.geeksforgeeks.org/sql-ddl-dql-dml-dcl-tcl-commands/
https://www.geeksforgeeks.org/sql-where-clause/
https://www.geeksforgeeks.org/sql-order-by/
https://www.geeksforgeeks.org/sql-group-by/
https://www.geeksforgeeks.org/sql-having-clause-with-examples/
https://www.sqlshack.com/sql-queries-in-sql-server-a-beginners-guide/
https://www.w3schools.in/mysql/ddl-dml-
dcl#:~:text=TCL%20stands%20for%20Transaction%20Control,treated%20as%20a%20single%
20unit.
1 Frew Atkilt M-Tech Network & Information Bishoftu Polytechnic 0911787374 [email protected]
Security College
5 Tewodros Girma MSc Information system Sheno Polytechnic 0912068479 girmatewodiros @gmail.com
College