Advance SQL 2
Advance SQL 2
Administration Level IV
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!
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;
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;
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
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
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!
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;
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
Used with single row operations such Applicable with multiple row functions
as Upper, Lower and so on such as Sum, count and so on