Advanced Structured Query Language
Advanced Structured Query Language
• 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.
• Following are the important points about ORDER BY Clause
• To sort the data in ascending order, we use the keyword ASC.
• To sort the data in descending order, we use the keyword DESC.
• 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.
• Example: by using the previous product table
• Sort the products from highest to lowest price
SELECT * FROM Products ORDER BY Price DESC;
• Sort the products from lowest to highest price
SELECT * FROM Products ORDER BY Price ASC;
• Sort the products alphabetically by using Product name
SELECT * FROM Products ORDER BY Product_Name;
• Sort the products by Product Name in reverse order
SELECT * FROM Products ORDER BY Product_Name 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
• 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.
• ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
2 K ebe de 25 A rada 150 0
3 C h e m d e sa 23 L e m ik ura 200 0
4 F ule a 25 K ality 650 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000
• SQL ALL Operator The ALL operator:
Returns a Boolean value as a result
Returns TRUE if ALL of the sub query values meet the condition
It is used with SELECT, WHERE and HAVING statements
• ALL means that the condition will be true only if the operation is true
for all values in the range.
• ALL operator syntax
SELECT ALL column_name(s) FROM table_name WHERE condition;
• 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 and the OR operator will filter records that
satisfy any one of the specified conditions.
• However, this is only used when specifying one condition is not
enough to filter all the required rows.
• Following is the syntax for using the AND and OR operators in a
WHERE clause
WHERE (condition1 OR condition2) AND condition3;
• Example: by using the previous customers table, we are retrieving all
rows from the CUSTOMERS table based on some conditions.
• The parentheses control the order of evaluation so that the OR
operator is applied first, followed by the AND operator.
Select * from customers where (age = 25 OR salary < 4500) AND
(name = 'Chemdesa' OR name = 'Momona');
• SQL ANY Operator The ANY operator:
• Returns a Boolean value as a result
• Returns TRUE if ANY of the sub query values meet the condition 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 (=, <>, !=, >,
>=, <=).
• 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
• 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.
• You can use the BETWEEN operator to replace a combination of "greater than
equal AND less than equal" conditions.
• 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.
• Select * from customers where age between 20 and 30;
ID Name A ge Address Salary
2 K ebe de 25 A rada 150 0
3 C h e m d e sa 23 L e m ik ura 200 0
4 F ule a 25 K ality 650 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000
• WHERE clause with NOT IN operator 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
• Whereas, if you use WHERE with the NOT IN operator, the DML operation is
performed on the values (of a column) that are not there in the specified list
• 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);
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
5 K em al 27 Y e ka 850 0
7 T ible tse 24 B o le 10000
• SQL LIKE Operator
• The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
• There are two wildcards often used in conjunction with the LIKE
operator:
• The percent sign % represents zero, one, or multiple characters
• The underscore sign _ represents one, single character LIKE operator
syntax
• SELECT column1, column2, ... FROM table_name WHERE columnN LIKE
pattern;
• Example: by using the previous customers table, we can write a query
which would display all the records where the name starts with K and
is at least 3 characters in length
• Select * from customers where name LIKE 'K__%';
ID Name A ge Address Salary
2 K ebe de 25 A rada 150 0
5 K em al 27 Y e ka 850 0
• 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;
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.
• 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:
• 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;
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.
• 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.
• INNER JOIN operator syntax
• 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).
• select Employee.Empname,Job_position.jop_title,
• Job_position.salary,Department.DepName from
• Employee inner join Job_position on
Job_position.job_id=Employee.job_id
• inner join Department on Job_position.DepId=Department.DepId
• Insert data to all tables
• Write a Query that displays employee name, job title, salary and department name of
female employee
• Display employees whose date of birth is less than 1995 and greater than 1987 and who
works in systemadmin
• Update the salary of employee by adding 1000 which salary is below 4000
• Display employees id ,name,department name and salary and display the result in
descending order of salary
• Retrieve the list of department with job position where salary is greater than or equal to
5000?
• write a query which would display all the employee records where the name starts with M
and is at least 7 characters in length
• solution
• 4 select Employee.Empname,Job_position.jop_title,
• Job_position.salary,Department.DepName from
• Employee inner join Job_position on Job_position.job_id=Employee.job_id
• inner join Department on Job_position.DepId=Department.DepId where sex='F'
• 5 SELECT * FROM Employee WHERE BDate BETWEEN '1987/07/16' and'1995/08/20';
• 6 update Job_position set salary=salary+1000 where salary<4000
• 7 select Employee.empId,Department.DepName,
• Job_position.salary from Employee inner join Job_position
• on Job_position.job_id= Employee.job_id inner join Department
• on Department.DepId=Job_position.DepId order by salary desc
• 8 SELECT DepName FROM Department WHERE DepId = ANY(SELECT DepId FROM Job_position
WHERE salary>=5000);
• 9 Select * from Employee where Empname LIKE ‘m______%';
• 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.
•t
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
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.
• The privileges (Right to access the data) are required for performing
all the database operations like creating tables, views, or sequences.
• 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.
• 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:
• GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER,
ANOTHER_USER;
• REVOKE 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:
• 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. So, in order to be at the
safer side COMMIT command is used. Syntax: commit;
• 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;
• 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;
• Example: Consider the following student table
• If commit was not performed then the changes made by the update
command can be rollback. Now if no COMMIT is performed.
• UPDATE STUDENT SET NAME = ‘Sherlock’ WHERE STUDENT_NAME = ‘Jolly’;
• After update command the table will be: