DB_LO4_v3
DB_LO4_v3
”LANGUAGE SQL
Learning Outcome
Team G2 4
Structured Query
●
Language
structured Query Language “SQL” is a relational data language that
provides a consistent,English keyword-oriented set of facilities for query,
data definition, data manipulation and data control.
:the syntax is
CREATE DATABASE
; database_name
❑ The DROP DATABASE statement is used to drop the existing SQL database .
❖If you create a new table using an existing table, the new table will be
▪ The following query will drop the column miniStudentsNo that was just
added to the Subjects table
Let’s design the Subjects table:
● The SELECT statement requires the name of the table and either * (retrieve all
columns) or specific column names.
● To limit the number of rows returned you can include the WHERE clause in the
SELECT statement.
Activity time
!
i eve FN , LN
Retr
Activity time
e al l
Retriev rs
e
custom
Activity time
ve
that ha
me
last na
DOE
LET’S
CODE
IT
Customers (custid, customerName,
LastName, FirstName, phone, city,
country,salesRepEmployeeNumber)
Neamat El Taz
What is the last name and first name of the customer with ID
Task time
141?
Answer
Also run the following query on the Subjects table
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN
value1 AND value2;
LET’S
CODE
IT
For instance, run SELECTsubjectID,subjectName,
subjectCreditHours, subjectGrade,subjectSemester
the following query: FROM Subjects
WHERE subjectCreditHours BETWEEN 3 AND 4
Answer
Data Manipulation Language DML
SELECT INSERT INTO Multiple LIKE Operator DISTINCT
Statement WHERE Statement
Clause
SELECT TOP BETWEEN IN Operator SQL Aliases ORDER BY
Clause Clause
NOT Clause UNION Clause EXCEPT INTERSECT JOIN Clause
Clause Clause
Aggregate GROUP BY HAVING ISNULL() &
Functions Clause COALESCE()
Functions
INSERT INTO UPDATE DELETE
SELECT Statement Statement
Statement
IN OPERATOR
● The IN operator allows you to specify multiple values in a
WHERE clause.
● The IN operator is a shorthand for multiple OR conditions.
SELECT subjectID,
subjectName, subjectGrade,
subjectSemester
FROM Subjects
WHERE NOT subjectGrade = 1
UNION
CLAUSE
● The UNION clause is used to
combine rows that are returned
from multiple SELECT statements
into a single result set.
Activity Activity
What is difference???
SELECT subjectID, subjectName, subjectGrade, subjectSemester
FROM Subjects
WHERE subjectGrade = 1
UNION
1
SELECT subjectID, subjectName,subjectGrade, subjectSemester
FROM Subjects
WHERE subjectGrade = 2
SELECT column_name
AS alias_name
FROM table_name
For instance, let us the below query:
❏ To sort the data retrieved using a certain order, the ORDER BY clause is used as
per the following query.
❏ Note that you can sort it in descending order using the DESC clause as per the
below query. The default for sorting when using ORDER BY is ASC.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name =
table2.column_name;
SELECT Orders.OrderID,
Customers.CustomerName,
Orders.OrderDate
FROM Orders
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name =
table2.column_name;
SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
LEFT JOIN Orders ON
Customers.CustomerID =
Orders.CustomerID
ORDER BY
Customers.CustomerName
RESULT OF
QUERY:
RIGHT JOIN
❑ To try the RIGHT JOIN,sometimes called RIGHT OUTER JOIN, which returns all rows
from the right table, and the matching records from the left table
❖ 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.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name =
table2.column_name;
SELECT Orders.OrderID,
Employees.EmployeeName
FROM Orders
RIGHT JOIN Employees ON
Orders.EmployeeID =
Employees.EmployeeID
ORDER BY Orders.OrderID
RESULT
OF
QUERY:
SELF JOIN FULL JOIN
● A self join is a regular join, but the ● To try the FULL JOIN, sometimes called
table is joined with itself. FULL OUTER JOIN, which returns all rows
when there is a match in the left or right .
SELECT column_name(s)
FROM table1 T1, table1 T2 ● The FULL OUTER JOIN keyword returns
WHERE condition; all records when there is a match in left
(table1) or right (table2) table records.
T1 and T2 are different table aliases for the
same table.
SELECT
Customers.CustomerName,
Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.C
ustomerID
ORDER BY
Customers.CustomerName
RESULT
OF
QUERY:
Data Manipulation Language DML
SELECT INSERT INTO Multiple LIKE Operator DISTINCT
Statement WHERE Statement
Clause
SELECT TOP BETWEEN IN Operator SQL Aliases ORDER BY
Clause Clause
NOT Clause UNION Clause EXCEPT INTERSECT JOIN Clause
Clause Clause
Aggregate GROUP BY HAVING ISNULL() &
Functions Clause COALESCE()
Functions
INSERT INTO UPDATE DELETE
SELECT Statement Statement
Statement
Aggregate Functions
)(COUNT
❑ function returns the number of rows that matches a specific
criteria. Its syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition
)(COUNT
❖ EXAMPLE 1 • Write sql query that return number of product id
❖ SOLUTION
SELECT COUNT(ProductID)
FROM Products
The result will be 5
)(AVG
❑ function returns the average value of a numeric
column.
❑ Its syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition
)(AVG
❑ EXAMPLE 1
❖ SOLUTION
SELECT AVG(Price)
FROM Products
The result will be 51.8
)(AVG
❑ EXAMPLE 2
Write sql query to return the Avarage price of product when Supplierid Equal 1
❖ SOLUTION
SELECT AVG(Price)
FROM Products
WHERE supplierID =1;
HOMEWORK
❑ Write sql query to return the
Avarage price of product when
price is more than 50 .
)(SUM
❖ function returns the total sum of a numeric
column.
❖ Its syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition
)(SUM
EXAMPLE 1:
❑Consider to
this table
Write a sql
query to the ❖ SOLUTION
sum of
quantity. SELECT SUM(Quantity)
FROM Products
The result will be 88
)(SUM
❑ EXAMPLE:2
❖ From this table Write sql query to returns the sum of
'total_cost' from purchase table for the category ('cate_id‘=
CA001)
)(SUM
❑ SOLUTION > EXAMPLE2
SELECT SUM(total_cost)
FROM purchase
WHERE cate_id='CA001’;
HOMEWORK
SELECT MIN(column_name)
FROM table_name
WHERE condition
)(MIN
EXAMPLE 1
❑ Write sql
query to
finds the
price of SOLUTIO
the
cheapest N
product . SELECT MIN(Price) AS SmallestPrice
FROM Products
The result will be 24
HOMEWORK
SELECT MAX(column_name)
FROM table_name
WHERE condition
)(MAX
EXAMPLE :1 Write sql query to finds the expensive price
product .
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s)
❑ GROUP BY
SELECT DeptId,
COUNT(EmpId) as 'Number of
Employees'
FROM Employee GROUP BY DeptId;
❑HAVING CLAUSE
❖ It was added to SQL because the WHERE keyword cannot
be used with
aggregate functions. The HAVING syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s)
Data Manipulation Language DML
SELECT INSERT INTO Multiple LIKE Operator DISTINCT
Statement WHERE Statement
Clause
SELECT TOP BETWEEN IN Operator SQL Aliases ORDER BY
Clause Clause
NOT Clause UNION Clause EXCEPT INTERSECT JOIN Clause
Clause Clause
Aggregate GROUP HAVING ISNULL() &
Functions COALESCE()
BY Clause Functions
INSERT INTO UPDATE DELETE
SELECT Statement Statement
Statement
INTERSECT
❑ The INTERSECT operator in SQL is used to retrieve the records that
are identical/common between the result sets of two or more
tables.
EXAMPLE :1
❑ WRITE SQL QUERY TO INSERT INTO
CUSTOMER TABLE WHERE SUPPLIER ID =101
❑ INSERT INTO SELECT STATEMENT
Solution
INSERT INTO Customers (CustomerID, CustomerName, Address, City)
SELECT SupplierID, SupplierName, Address, City
FROM Suppliers
WHERE SupplierID = 101;
Data Manipulation Language DML
SELECT INSERT INTO Multiple LIKE Operator DISTINCT
Statement WHERE Statement
Clause
SELECT TOP BETWEEN IN Operator SQL Aliases ORDER BY
Clause Clause
NOT Clause UNION Clause EXCEPT INTERSECT JOIN Clause
Clause Clause
Aggregate GROUP HAVING ISNULL() &
Functions COALESCE()
BY Clause Functions
INSERT INTO UPDATE DELETE
SELECT Statement Statement
Statement
ISNULL() FUNCTIONS
❑ The ISNULL() function returns a specified value if the expression is NULL.
❑ If the expression is NOT NULL, this function returns the expression.
ISNULL() FUNCTIONS
COALESCE()
FUNCTION
Definition and Usage
The COALESCE() function returns the first non-null value in a list.
Syntax
COALESCE(val1, val2, ...., val_n)
COALESCE()
FUNCTION
Resu
lt
❑ UPDATE STATEMENT
o is used to modify specific rows in a table.
o The UPDATE syntax is:
UPDATE table_name
SET column1 = value1 , column2 = value2, ...
WHERE condition
❖ Example 1
solution
❑ UPDATE STATEMENT
❑ EXAMPLE 2
❑ write a query to modify the subjectCreditHours column in the Subjects
table to be 5 for all the subjects in grade = 3.
solution
UPDATE Subjects
SET subjectCreditHours = 5
WHERE subjectGrade = 3 ;
❑ DELETE STATEMENT
❖ is used to delete existing rows in a table.
❖ The DELETE syntax is
❑ EXAMPLE:1
values. where EXISTS is the operator to return the Boolean value that is
true or false. Generally, if EXISTS checks that one or more rows are
// Good practise
4)Use “Where” Instead of “Having” A
Clause
5) Apply Index on Necessary Columns:
Thinking how SQL Queries work:
.
FOR USER-DEFINED STORED PROCEDURES AVOID PREFIXES )6
:”_LIKE “SP
// Bad practise
UNION , WHY?
❑ BECAUSE first apply sort and then find the distinct record and then
return a result , to compare to UNION ALL
❑ can use UNION since only distinct records are required at that time
BEST STUDENTS
TILL NOW…
Student
1
Name
Student
2
Name
Student 3
Name
SQL Stored Procedures
An SQL stored procedure :
❑ is a prepared SQL code that you can save, so that it can be reused repeatedly. So, if you have an SQL
query that you write over and over again, save it as a stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the
parameter value(s) that is passed.
❑ SQL stored procedures have several benefits, such as.
❑ ➡ Reusable, database users can benefit from the already created stored procedures and use them
❑ ➡ easily modify the stored procedures created and all users calling these stored procedures will benefit
❑ ➡ Increased performance, after the first execution for the stored procedure, an execution plan for the
stored procedure created. This execution plan has significant impact on the execution performance.