0% found this document useful (0 votes)
27 views

DB_LO4_v3

Uploaded by

marwanelgammal55
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)
27 views

DB_LO4_v3

Uploaded by

marwanelgammal55
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/ 154

STRUCTURED QUERY“

”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.

● It is effectively used to create, insert, search,


update, delete,modify database records.

● It is a programmed interface to relational


database management systems (RDBMSs).
The Structured Query Language can be
divided into the following:

• DDL: Data Definition Language

• DML : Data Manipulation Language

• DCL: Data Control Language

We will focus during our study on both DML and DDL


Data Definition Language( DDL)
DATA DEFINITION LANGUAGE( DDL)

❑The Data Definition Language (DDL):

⮚ is a subset of SQL. It is a language for describing data and its


relationships in a database.
❑ CREATE
DATABASE
STATEMENT

:the syntax is
CREATE DATABASE
; database_name

❑ once the database is created, it can be


checked in the list of existing databases.
DROP DATABASE

❑ The DROP DATABASE statement is used to drop the existing SQL database .

the syntax is : DROP DATABASE database _ name ;


CREATE TABLE
❖ The CREATE TABLE statement is used to create a new table in a specificexisting database.
❖ the syntax is:

CREATE TABLE table_name


( column1 datatype,
column2 datatype,
column3 datatype, .... );
❑ CREATE TABLE USING
ANOTHER TABLE

❖A copy of an existing table can also be created using CREATE TABLE.

❖The new table gets the same column definitions.

❖All columns or specific columns can be selected.

❖If you create a new table using an existing table, the new table will be

filled with the existing values from the old table.


❑ CREATE TABLE USING
ANOTHER TABLE
example

SELECT (columns name)


INTO new_table_name
FROM old_table
WHERE (condition)…;
DROP TABLE

❑ The DROP TABLE statement is used to drop an existing table in a


database,

❑ the syntax is: DROP TABLE table_name;

DROP TABLE TestSubjects ;


TRUNCATE
❖ Use the TRUNCATE TABLE statement to delete the data
inside an existing table in a database without dropping the
table,
the syntax is : TRUNCATE TABLE table_name ;

TRUNCATE TABLE Subjects ;


❑ What is the difference
Between

DROP TABLE AND


TRUNCATE TABLE
ALTER TABLE
❑ The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
❑ Also, the ALTER TABLE statement is used to add and drop
various constraints on an existing table.
ALTER TABLE
o ADD Column:

▪ The following query will add the column miniStudentsNo to the


Subjects table .
ALTER TABLE
o DROP Column:

▪ The following query will drop the column miniStudentsNo that was just
added to the Subjects table
Let’s design the Subjects table:

CREATE TABLE Subjects


(
subjectID NVARCHAR(5) NOT NULL PRIMARY KEY,
subjectName NVARCHAR(50) NULL NOT NULL,
subjectCreditHours SMALLINT NOT NULL,
subjectGrade SMALLINT NULL,
subjectSemester SMALLINT NULL
)
Data Manipulation
Language
DATA MANIPULATION
LANGUAGE
The Data Manipulation Language is a subset of SQL and it refers to a
computer programming language that allows you to add (insert) , delete
(delete), and alter (update) , select ( select) data in a database.

▪ INSERT: is used to insert new instances


inside a database.
SELECT: is used to retrieve data from a
database.
▪UPDATE: is used to update existing
instances inside a database.
▪DELETE: is used to delete existing
instances inside a database.
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
SELECT
● The SELECT statement used to retrieve rows and columns from a 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.

SELECT column1, column2, ...


SELECT column1,
FROM table_name; column2, ...
SELECT CustomerName, City FROM Customers; FROM table;
SELECT * FROM Customers;
For Example : Let us consider the Students table let us write simple SELECT
statement to retrieve the student’s data.

SELECT studentID, studentName, studentBD


FROM Students ;
To retrieve certain rows, using the WHERE clause. GUESS!!

● Retrieve student data which studentID =’10115’


● Note that the retrieved columns are driven by the SELECT clause while the retrieved rows are
driven by the WHERE clause.

SELECT studentID, studentName, studentBD


FROM Students
WHERE studentID = '10115'
LET’S
CODE
IT
i eve all the
Retr s!
column

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?

Write a query to return all information of customers with last


name “Patterson”.

Write a query to return all information of the


Customer whose name is “Mary Patterson”

Write a query to return all customers who live in France and


specifically in Paris city.
INSERT
INSERT INTO table_name (column1, column2, column3, ...)
;VALUES (value1, value2, value3, ...)

INSERT INTO table_name


;VALUES (value1, value2, value3, ...)

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1 0AA', 'UK');
YOUR TIME TO CODE
Insert all data in this table (table name = subject)
Multiple WHERE Clause
● We can combine several WHERE clauses in one query
statement to create more specific queries using both AND and
OR.
● You can use the AND condition in the WHERE clause to
specify more than 1 condition that must be met for the
record to be selected.

● You can use the OR condition in the WHERE clause to test


multiple conditions where the record is returned if any one of
the conditions are met.
LET’S
CODE
IT
Let‘s try
SELECT subjectID , subjectName, subjectCreditHours and subjectGrade from table subject
WHERE subjectCreditHours more than 2 AND subjectGrade equal 1
SELECTsubjectID,subjectName,subjectCreditHours,subjectGrade
FROM Subjects
WHERE subjectCreditHours >2 AND subjectGrade = 1
SELECT subjectID, subjectName, subjectCreditHours, subjectGrade
FROM Subjects
WHERE subjectGrade = 1 OR subjectSemester = 2
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
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 a LIKE
operator:
➡ The percentage sign (%) which represents zero,
one, or multiple characters.
➡ The underscore sign (_) which represents one
single character.

the LIKE syntax:

SELECT column1, column2,


FROM table_name
WHERE column LIKE pattern
Run the following query on the Subjects table

SELECT * from Subjects


WHERE subjectName
LIKE ‘%App%’

Answer
Also run the following query on the Subjects table

SELECT * from Subjects


WHERE subjectName
LIKE ‘B_%’
Answer
Activity time
SELECT DISTINCT
The SELECT DISTINCT statement is used to return only distinct
(different) values. Inside a table, a column often contains many
duplicate values ,and sometimes you only want to list the different
(distinct) values.

SELECT DISTINCT column1, column2, ...


FROM table_name

● If the following query runs on


the Subjects table:

SELECT DISTINCT subjectCreditHours from Subjects


Activity time
Activity time
But if there is
another john in
USA
IT will not
duplicated
SELECT TOP
● The SELECT TOP clause is used to specify the number of records to return.
● It is particularly useful with large tables with thousands of records. Returning a
large number of records can impact performance.

The SELECT TOP syntax:


SELECT TOP number | percent
column_name(s)
FROM table_name
WHERE condition

Run the following query on the


Subjects table:
SELECT TOP 5 *
from Subjects
Activity time
BETWEE
N
❏ Use the BETWEEN clause to retrieve rows within a certain data range.
❏ The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
❏ The BETWEEN operator is inclusive: begin and end values are included.

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 column_name(s) SELECT column_name(s)


FROM table_name FROM table_name
WHERE column_name WHERE column_name
IN (value1, value2, ...) IN(SELECTSTATEMENT)
SELECT * from Subjects
WHERE subjectCreditHours Answer
IN (3,4)
Activity time
NOT
CLAUSE
❑ The NOT clause is used to retrieve data that specifies
what you don’t want to be returned.
⮚ For instance, when running the following query:

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.

● The columns returned from the


multiple SELECTs should be the
same.
SELECT
subjectID subjectID, subjectName, subjectGrade, subjectSemester
SubjectName
FROM Subjects
WHERE subjectGrade = 1
UNION
SELECT subjectID, subjectName,subjectGrade, subjectSemester
FROM Subjects
WHERE subjectGrade = 2
Activity

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 subjectID, subjectName, subjectGrade,


subjectSemester 2
FROM Subjects
WHERE subjectGrade = 1 AND subjectGrade = 2
EXCEPT
● CLAUSE
The EXCEPT clause is used to return distinct values from the left
query that are not present in the right query.

● This operator acts as the opposite of the SQL UNION operator.


● For instance, to retrieve the subjects for grade = 1 and subject semester = 1

SELECT subjectID, subjectName,


subjectCreditHours,subjectGrade,subjectSeme The left part of the query will retrieve
ster all the subjects in the first grade for
FROM Subjects both first and second semesters, and
WHERE subjectGrade = 1 the right query will retrieve all the
EXCEPT
subjects in the first grade in the
SELECT subjectID,
subjectName,subjectCreditHours, second semester only. Therefore the
subjectGrade, two queries will retrieve subjects for
subjectSemester the first grade and the first semester
FROM Subjects as follows:
WHERE subjectSemester = 2
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
SQL
ALIASES
● SQL aliases are used to give a table, or a column in a
table, a temporary name.
● Aliases are often used to make column names more
readable.
● An alias only exists for the duration of a certain query.
● It is created with the AS keyword.

SELECT column_name
AS alias_name
FROM table_name
For instance, let us the below query:

SELECT subjectName AS Subject_Name from Subjects


Activity time
ORDER BY
CLAUSE
The ORDER BY keyword is used to sort the result-set in ascending or descending order .

❏ 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 column1, column2, ...


FROM table_name
ORDER BYcolumn1,column2,ASC|DESC;
SELECT subjectID, subjectName, subjectCreditHours, subjectGrade,
subjectSemester
FROM Subjects
WHERE subjectCreditHours BETWEEN 3 AND 4
ORDER BY subjectSemester
SELECT subjectID, subjectName, subjectCreditHours,
subjectGrade, subjectSemester
FROM Subjects
WHERE subjectCreditHours BETWEEN 2 AND 4
ORDER BY subjectSemester DESC
Activity time
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
JOIN CLAUSE

❑The JOIN clause


allows you to
combine related
data from multiple
tables into one
result set.
INNER JOINS

➡ It uses a comparison operator to match rows from two tables based


on values in common column that exists in both tables .

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

INNER JOIN Customers ON


Orders.CustomerID=Customers
.CustomerID
LEFT JOIN
❑ To try the LEFT JOIN sometimes called LEFT OUTER JOIN- which
returns all rows from the left table, and the matching records from the right
table .
⮚ 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;
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

Write sql query to return the Avarage price of product

❖ 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

❖ Write sql query to get sum of values in


salary .
)(MIN
❑function returns the smallest value of
the selected column.
❑ its syntax

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

• Write sql query to


return lowest salary
where are less
than 30 .
)(MAX
❑function returns the largest value of the
selected column.
❑its syntax

SELECT MAX(column_name)
FROM table_name
WHERE condition
)(MAX
EXAMPLE :1 Write sql query to finds the expensive price
product .

SOLUTION SELECT MAX(Price) AS


LargestPrice
FROM Products
The result will be 90
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
❑ GROUP BY
▪ The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

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.

SELECT column1, column2,..., column


FROM table1, table2,..., tableN
INTERSECT
SELECT column1, column2,..., column
FROM table1, table2,..., tableN
INTERSECT
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
❑ INSERT INTO SELECT STATEMENT
❑ copies data from one table and insert it into another table. Note that both
source and target tables columns’ data types should be similar. Also, note
that the target table existing rows are not affected with the
INSERT INTO SELECT statement.
❖ The syntax for the INSERT INTO SELECT if all rows are to be copied

INSERT INTO table2

SELECT * FROM table1


WHERE condition
❑ INSERT INTO SELECT STATEMENT

▪ To copy some columns from one source table into


the target table the syntax will be as follows
INSERT INTO table2 (column1, column2, column3, …)
SELECT column1, column2, column3, …
FROM table1
WHERE condition

Table2 is the target table while table1 is the source table


❑ INSERT INTO SELECT STATEMENT

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

❖ It’s important to be cautious when updating rows in a table, and


the inclusion of the WHERE clause in the UPDATE statement is
crucial to specify which rows should be updated. If you omit the
WHERE clause, all rows in the table will indeed be updated.
❑ UPDATE STATEMENT

❖ Example 1

❑ write an UPDATE statement to modify the subjectGrade and


subjectSemester columns that contain NULL values .

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

DELETE FROM table_name WHERE condition

⮚ The WHERE clause specifies which row(s) should be


deleted. If the WHERE clause is omitted, all rows in the
table will be deleted.
❑ DELETE STATEMENT

❑ EXAMPLE:1

❑ Write a sql query to delete the subject that has the


subjectID equals =104
solution

DELETE FROM Subjects


WHERE subjectID = ‘104’ ;
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
SQL Query Performance
❑ SQL QUERY PERFORMANCE

1)Do Not Use * In Select Statment :


SELECT * FROM Employee // Bad practice
SELECT EmpID , EmpName FROM Employee // Good practice
What Difference between IN operator and EXISTS

The IN operator in SQL allows you to match an expression against a list of

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

available in the sub query, it will return true otherwise false.


2) Use EXIST Instead of Sub Query :
SELECT ID, Name FROM Employee
WHERE DeptID IN
(SELECT ID FROM Department WHERE Name LIKE ‘%Management%’)
// Bad practice

SELECT ID, Name FROM Employee


WHERE DeptID EXIST
(SELECT ID FROM Department WHERE Name LIKE ‘%Management%’)
// Good practice
3) Use Proper JOIN Instead of Subqueries:
SELECT ID, Name FROM Employee
WHERE DeptID IN
(SELECT ID FROM Department WHERE Name LIKE ‘%Management%’)
// Bad practise

SELECT Employee.ID, Employee.Name, Department.Name


FROM Employee RIGHT JOIN Department ON
Employee.DeptID = Department.ID
WHERE Department.Name LIKE ‘%Management%’

// 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

• As in SQL databases, the master database has some


inbuild stored procedures which start with “sp_”
❑ so whenever to create a user-defined stored
procedure at that time, avoid prefixes like “sp_”
because when using that stored procedure in the code
at that time, SQL first finds from the master database
which takes extra time. Therefore if another name is
given instead of “sp_” then it will take less time
:AVOID NEGATIVE SEARCH )7
• Negative search is the elimination of information which
is not relevant from a mass of content in order to
present to a user a range of relevant conten
• Negative searches decrease the query execution speed
that’s why it should be avoided.
• That type of search should be avoided because if the
exact search criteria was given while query executing if
that type of data is got then immediately query returns the
result.
:APPLY VALID DATATYPE ON THE COLUMN )8

• users may not know the actual use of datatype so they


might apply varchar datatype for all columns but it’s not
the right way
• According to client requirements, which type of data is
required should be identified first and based on that the
proper datatypecan be applied.
:AVOID QUERY IN A LOOP )9

For (int i = 0; i<= 5; i++) {


INSERT INTO Table1(ID, Name) VALUES(i, ‘Name’ + i); }

// Bad practise

INSERT INTO Table1(ID, Name) VALUES (1, Name1),


(2,Name2), (3,Name3)
// Good practise
APPLY UNION ALL INSTEAD OF UNION IF POSSIBLE )10

❑ The major difference between UNION and UNION ALL is


that UNION returns distinct records
while UNION ALL returns all records including duplicates.
While UNION is applied on that time function,

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

repeatedly by calling them .

❑ ➡ easily modify the stored procedures created and all users calling these stored procedures will benefit

from these modifications .

❑ ➡ 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.

❑ ➡ Security, only allowed users can call the stored procedures


Stored Procedure
oCreation
Creating SQL stored procedure is simple,
the syntax for the stored procedure
CREATE or REPLACE PROCEDURE name(parameters)
To make sure that
the stored
procedure created,
under the
Programmability,
click the stored
procedure,
then right click and
click Refresh,
To execute the stored procedure:
There is no
parameter
As you not
assign any
value
To create a stored procedure that accepts parameters, the parameters should be
defined first as follows:
❑ to view the stored procedure script, use system stored procedure called
sp_helptext as follows sp_helptext ‘spGradeSubjectsByGrade’
To modify an already created stored procedure,
use ALTER PROCEDURE
To delete an existing stored procedure

DROP PROCEDURE spGradeSubjectsByGrade


To encrypt a stored procedure,
Using sp_helptext to view the stored procedure script
THANK
YOU
Team G2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy