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

Lec07 - SQL (Cont.)

Lecture 7 by Dr. Marwa Hussien covers SQL Data Manipulation Language (DML) commands, including INSERT, UPDATE, and DELETE, which are used to manipulate data in databases. It explains how to insert data directly or through SELECT statements, update records based on conditions, and delete records with specified criteria. Additionally, the lecture discusses basic retrieval queries, logical operators, aggregate functions, and the use of clauses like ORDER BY, GROUP BY, and HAVING in SQL queries.

Uploaded by

Amira Gohar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lec07 - SQL (Cont.)

Lecture 7 by Dr. Marwa Hussien covers SQL Data Manipulation Language (DML) commands, including INSERT, UPDATE, and DELETE, which are used to manipulate data in databases. It explains how to insert data directly or through SELECT statements, update records based on conditions, and delete records with specified criteria. Additionally, the lecture discusses basic retrieval queries, logical operators, aggregate functions, and the use of clauses like ORDER BY, GROUP BY, and HAVING in SQL queries.

Uploaded by

Amira Gohar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

SQL (Cont.

)
Lecture 7

Dr. Marwa Hussien

1
Data Manipulation Language (DML)
• The SQL commands that deal with the manipulation of data
present in the database.
• It is the component of the SQL statement that controls access to
data in the database.

2
DML Statments
• Three commands used to modify the database:
• INSERT typically inserts a tuple (row) in a relation (table)
• UPDATE may update a number of tuples (rows) in a relation (table) that
satisfy the condition
• DELETE may also update a number of tuples (rows) in a relation (table)
that satisfy the condition

3
The INSERT command
• It is used to add one or more tuples to a relation.
• There are two ways to insert data in a table:
1. By SQL insert into statement
• By specifying column names
• Without specifying column names
2. By SQL insert into select statement
• Constraints on data types are observed automatically.
• Any integrity constraints as a part of the DDL specification are
enforced.

4
1. Inserting Data Directly Into a Table
• You can insert a row in the table by using SQL INSERT INTO command.
1. There is no need to specify the column name where the data will be
inserted, you need only their values.
• INSERT INTO table_name VALUES (value1, value2, value3....);
• INSERT INTO CUSTOMERS VALUES (6, Ayman, 24, Cairo);
2. Specifies both the column name and values which you want to insert.
• INSERT INTO table_name (column1, column2, column3....) VALUES (value1, value2,
value3....);
• INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY) VALUES (1, Ahmed, 22, Cairo);
• INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY) VALUES (2, Ali, 20, Cairo);

5
2. Inserting Data Through SELECT Statement
• We use the SELECT statement to copy the data from one table and
the INSERT INTO statement to insert from a different table.
• SQL INSERT INTO SELECT Syntax
• INSERT INTO first_table SELECT * FROM second_table;
• INSERT INTO first_table(names_of_columns) SELECT names_of_columns
FROM second_table;
• INSERT INTO table1 SELECT * FROM table2 WHERE condition;

• Note: when you add a new row, you should make sure that data
type of the value and the column should be matched.
• If any integrity constraints are defined for the table, you must
follow them.
6
2. Inserting Data Through SELECT Statement
• Examples:
• INSERT INTO GraduateStudent SELECT * FROM Student;
• This query will insert all the data of the table Student in the table GraduateStudent.
• INSERT INTO GraduateStudent(ROLL_NO,NAME,Age) SELECT ROLL_NO,
NAME, Age FROM Student;
• This query will insert the data in the columns ROLL_NO, NAME, and Age of the table
Student in the table GraduateStudent and the remaining columns in the
GraduateStudent table will be filled by null which is the default value of the remaining
columns.
• INSERT INTO GraduateStudent SELECT * FROM Student WHERE Age = 18;
• This query will select only rows that has Age value = 18 from table Student to insert into
the table GraduateStudent.

7
The UPDATE command
• Used to change the data of the records in the tables.
• To determine rows to be updated, specify a condition using
WHERE clause. A WHERE-clause selects the tuples to be
modified.
• An additional SET-clause specifies the attributes to be modified
and their new values.
• Each command modifies tuples in the same relation.
• Referential integrity specified as part of DDL specification is
enforced.

8
The UPDATE command
• The UPDATE statement can be written in following form:
• UPDATE table_name SET [column_name1= value1,... column_nameN =
valueN] [WHERE condition]
• UPDATE students SET User_Name =‘Kareem’ WHERE Student_Id = ‘3’;
• UPDATE students SET User_Name = ‘Kareem’, Age=‘19’ WHERE Student_Id
= ‘3’;
• Note: If we omit the WHERE clause from the update query then all
of the rows will get updated.
• UPDATE students SET Age=‘19’;

9
The DELETE command
• The SQL DELETE statement is used to delete rows from a table.
• Generally, DELETE statement removes one or more records from a
table.
• Notes:
• Includes a WHERE-clause to select the tuples to be deleted.
• Referential integrity should be enforced.
• Tuples are deleted from only one table at a time (unless CASCADE is specified
on a referential integrity constraint).
• A missing WHERE-clause specifies that all tuples in the relation are to be
deleted; the table then becomes an empty table.
• The number of tuples deleted depends on the number of tuples in the relation
that satisfy the WHERE-clause.

10
The DELETE command
• The Syntax for the SQL DELETE statement:
• DELETE FROM table_name [WHERE condition];

• DELETE FROM EMPLOYEE WHERE ID=101;


• DELETE FROM EMPLOYEE; // similar to TRUNCATE command.

11
The RENAME Command
• The RENAME TABLE and ALTER TABLE syntax help in changing the
name of the table.
• Syntax of RENAME statement in SQL
• RENAME old_table _name To new_table_name ;
• RENAME Cars To Car_Details ;

• Syntax of ALTER TABLE statement in SQL


• ALTER TABLE old_table_name RENAME TO new_table_name;
• ALTER TABLE Cars RENAME TO Car_Details ;

12
Basic Retrieval Queries in SQL
• SELECT statement: one basic statement for retrieving
information(tuples) from a database.

• To fetch the entire table or all the fields in the table:


• SELECT * FROM table_name;
• SELECT * FROM Student;

• Query to fetch some fields from a table:


• SELECT columnName1, columnName2 FROM table_name;
• SELECT CustomerName, LastName FROM Customer;

13
Basic Retrieval Queries in SQL
• To select some values with specific conditions then Where Clause
is used with select statement.
• SELECT column1, column2 FROM table_name WHERE condition;
• SELECT CustomerName FROM Customer WHERE Age = '21';

14
The SELECT-FROM-WHERE Structure of
Basic SQL Queries
• Logical comparison operators:
• =, <=, >, >=, and <> .
• Projection attributes:
• Attributes whose values are to be retrieved
• Selection condition:
• Boolean condition that must be true for any retrieved tuple.
• Selection conditions include join conditions when multiple relations are
involved.

15
SELECT Statement Example

16
SELECT Statement Example

17
SELECT Statement Example

18
SELECT Statement Example

19
SQL AND Operator
• Used in the WHERE clause. The SQL AND operator selects data if
all conditions are TRUE.

20
SQL OR Operator
• Used in the WHERE clause. The SQL OR operator selects data if
any one condition is TRUE.

21
SQL NOT Operator
• Used in the WHERE clause. The SQL NOT operator selects data if
the given condition is FALSE.

22
Combining Multiple Operators

23
Combining Multiple Operators

24
SQL SELECT DISTINCT
• The SELECT DISTINCT statement
retrieves distinct values (set) from a
database table.

25
SQL DISTINCT on
Multiple Columns

• Here, the command


selects rows if
combinations of
country and
first_name are
unique.

26
DISTINCT With COUNT

• We can use SQL DISTINCT with


the COUNT() function to count
the number of unique rows.

27
SQL SELECT AS Alias

• The AS keyword is used to give


columns or tables a temporary
name that can be used to
identify that column or table
later.

28
SQL AS With
More Than One
Column
• Here, the SQL command
will concatenate the
first_name and last_name
columns in the result set as
full_name.
• Notice that we have also
concatenated an empty
space ' ' between
first_name and last_name.
• This ensures that the data
from these columns are
separated by a space in the
result set.

29
SQL SELECT LIMIT
• The SQL LIMIT keyword allows
us to specify the number of
records in the result set.

30
SQL IN Operators
• We use the IN operator with
the WHERE clause to match
values in a list.

31
SQL NOT IN Operator
• The NOT IN operator excludes
the rows that match values in
the list. It returns all the rows
except the excluded rows.

32
SQL BETWEEN Operator
• In SQL, the BETWEEN operator
with the WHERE clause selects
values within a given range.
• Here, we selected item and
amount columns from Orders
that have amounts between
300 and 500 (including 300 and
500).

33
SQL NOT BETWEEN Operator
• The NOT BETWEEN operator is
used to exclude the rows that
match the values in the range.
It returns all the rows except
the excluded rows.

34
SQL BETWEEN Operator with Text and Dates
• The BETWEEN operator also
works with text data.
• In SQL, we can also use
BETWEEN to filter data
between two dates.
• Example: SELECT *FROM Teams
WHERE registered BETWEEN
'2021-01-01' AND '2022-11-01';

35
SQL IS NULL Syntax
• In SQL, the IS NULL condition
is used to select rows if the
specified field is NULL.

36
SQL IS NOT NULL Syntax
• In SQL, the IS NOT NULL
condition is used to select
rows if the specified field is
NOT NULL.

37
IS NULL With COUNT()
• We can use the COUNT()
function with IS NULL to count
the number of rows with an
empty field.

38
SQL MAX() Function
• The MAX() function returns the
maximum value of a column.

39
SQL MIN() Function
• The MIN() function returns the
minimum value of a column.

40
Aliases With MAX() and MIN()
• It is also possible to give
custom names to these fields
using the AS keyword.

41
MAX() and MIN() With Strings
• The MAX() and MIN()
functions also work with
texts.

42
MAX() and MIN() in Nested SELECT
• If we want to select the
whole row containing max
or min value, we can use
the nested SELECT
statement like this.

43
SQL COUNT()
• The SQL COUNT() function
returns the number of records
returned by a query.

44
Specify Column to Count
• We can also specify a
column name in COUNT()
to only count the rows in
that particular column.
• Note, it returns the count
of non-null values in that
particular column.

45
COUNT() With WHERE
• We can use COUNT() with
WHERE to count rows that
match the given value.

46
COUNT() With DISTINCT
• If we need to count the number
of unique rows, we can use the
COUNT() function with the
DISTINCT clause.

47
SQL SUM() Function
• The SQL SUM() function is
used to calculate the
cumulative sum of numeric
values in a column.

48
SQL SUM() Function
• The SQL SUM() function is
used to calculate the
cumulative sum of numeric
values in a column.

49
SQL AVG() Function
• The SQL AVG() function is used
to calculate the average of
numeric values in a column.

50
SQL AVG() Function
• The SQL AVG() function is used
to calculate the average of
numeric values in a column.

51
SQL ORDER BY Clause
• The ORDER BY clause in SQL is
used to sort the result set in
ascending or descending
order.

52
ORDER BY ASC (Ascending Order)
• We can use the ASC keyword
to explicitly sort selected
records in ascending order.

53
ORDER BY DESC (Descending Order)
• We use the DESC keyword to
sort the selected records in
descending order.

54
ORDER BY With Multiple Columns
• We can also use ORDER BY
with multiple columns.
• The SQL command selects
all the records and then
sorts them by first_name. If
the first_name repeats
more than once, it sorts
those records by age.

55
ORDER BY With WHERE
• We can also use ORDER BY
with the SELECT WHERE
clause.

56
SQL GROUP BY
• In SQL, we use the GROUP BY
clause to group rows based on
the value of columns.
• Note: The GROUP BY clause is
used in conjunction with
aggregate functions such as
MIN() and MAX(), SUM() and
AVG(), COUNT(), etc.

57
SQL GROUP BY
• GROUP BY Amount Spent By
Each Customer

58
SQL HAVING Clause
• The SQL HAVING clause is
used if we need to filter the
result set based on aggregate
functions such as MIN() and
MAX(), SUM() and AVG(), and
COUNT().

59
SQL HAVING vs. WHERE
• We can write a WHERE clause to filter out rows where the
value of amount in the Orders table is less than 500:
• Example: SELECT customer_id, amount FROM Orders WHERE
amount < 500;

• But with the HAVING clause, we can use an aggregate


function like SUM to calculate the sum of amounts in the
order table and get the total order value of less than 500 for
each customer:
• Example: SELECT customer_id, SUM(amount) AS total FROM Orders
GROUP BY customer_id HAVING SUM(amount) < 500;

60
SQL HAVING vs. WHERE

HAVING Clause WHERE Clause

The WHERE clause checks the


The HAVING clause checks the
condition on each individual
condition on a group of rows.
row.

HAVING is used with aggregate The WHERE clause cannot be


functions. used with aggregate functions.

The HAVING clause is executed The WHERE clause is executed


after the GROUP BY clause. before the GROUP BY clause.

61
SQL LIKE
• We use the SQL LIKE operator
with the WHERE clause to get a
result set that matches the
given string pattern.

62
SQL LIKE
• The SQL LIKE query is often
used with the % wildcard to
match a pattern of a string.
• Here, the SQL command
selects customers whose
last_name starts with R
followed by zero or more
characters after it.

63
SQL LIKE
• The SQL LIKE query is often used
with the % wildcard to match a
pattern of a string.
• Here, the SQL command selects
customers whose last_name starts
with R followed by zero or more
characters after it.
• Another Example: SELECT * FROM
Customers WHERE country LIKE
'U_’;
• Here, we select customers whose
country name starts with U followed
by exactly one character.
64
SQL NOT LIKE Operator
• We can also invert the working of the LIKE operator by using the
NOT operator with it. This returns a result set that doesn't match
the given string pattern.
• Example: SELECT * FROM Customers WHERE country NOT LIKE 'USA';
• Here, the SQL command selects all customers except those whose
country is USA.
• We can use SQL LIKE With Multiple Values:
• Example: SELECT * FROM Customers WHERE last_name LIKE 'R%t' OR
last_name LIKE '%e’;
• Here, the SQL command selects customers whose last_name starts with
R and ends with t or customers whose last_name ends with e.
65
SQL UNION
• To use UNION in SQL, we must
always remember:
• The column count in all tables
must be the same.
• For example, both the Teachers
and Students tables have three
columns.
• The data type of columns must
be the same.
• For example, the age column in
both the Teachers and Students
table is integer.

66
SQL UNION All
• To use UNION in SQL, we must
always remember:
• The column count in all tables must
be the same.
• For example, both the Teachers and
Students tables have three columns.
• The data type of columns must be
the same.
• For example, the age column in both
the Teachers and Students table is
integer.
• The columns must be in the same
order in each table.
• For example, the order of columns is
id-name-age in both Teachers and
Students tables.

67
SQL UNION vs. UNION ALL

SQL UNION SQL UNION ALL

It returns the duplicate values from the


It only returns unique values from the result
result set of two queries.
set of two queries.

Slower in comparison to the UNION ALL Executes faster as there is no need of filtering
operator. the result sets for removing duplicate values.

68
The SQL INTERSECT Operator
STUDENTS_HOBBY STUDENTS
• Used to retrieve the
common records
between the result sets of
two or more tables.
• SELECT NAME, AGE,
HOBBY FROM
STUDENTS_HOBBY
INTERSECT
SELECT NAME, AGE,
HOBBY FROM STUDENTS;
69
The SQL EXCEPT Operator
• The SQL EXCEPT Operator compares the distinct values of the left
query with the result set of the right query. If a value from the left
query is found in the result set of the right query, it is excluded from
the final result.

• SELECT NAME, AGE, HOBBY FROM STUDENTS


EXCEPT
SELECT NAME, AGE, HOBBY FROM STUDENTS _HOBBY;

70
The SQL EXCEPT Operator
STUDENTS STUDENTS_HOBBY

71
SQL CASE
• The SQL CASE
statement evaluates a
list of conditions and
adds a column with
values based on the
condition.

72
SQL CASE With ELSE
• A CASE statement can
have an optional ELSE
clause.
• The ELSE clause is
executed if none of the
conditions in the CASE
statement is matched.

73
SQL Subquery (Nested query)
• In SQL, a SELECT statement may contain another SQL
statement.
• Suppose we want to select Customers with Minimum Age:
• Example: SELECT first_name FROM Customers WHERE age= (SELECT
MIN(age) FROM CUSTOMERS );
• Suppose we want the details of customers who have placed an
order:
• Example: SELECT customer_id, first_name FROM Customers WHERE
customer_id IN (SELECT customer_id FROM Orders );

74
SQL ANY Operator
• SQL ANY compares a value of
the first table with all values of
the second table and returns
the row if there is a match with
any value.
• Suppose we want to find
teachers whose age is similar
to any of the student's age.

75
SQL ANY With the < Operator
• Suppose we want to
get teachers whose
age is less than any
student.

76
SQL ALL Operator
• SQL ALL compares a value of
the first table with all values of
the second table and returns
the row if there is a match with
all values.

77
SQL EXISTS Operator
• The SQL EXISTS operator tests the existence of any value in a
subquery i.e. it executes the outer SQL query only if the subquery is
not NULL (empty result-set).
• Example: select customer id and first name of customers whose
order amount is less than 12000.
• SELECT customer_id, first_name FROM Customers WHERE EXISTS (
SELECT order_id FROM Orders WHERE Orders.customer_id =
Customers.customer_id AND amount < 12000);
• Example: Select orders from the Orders table for customers who are
older than 23 years.
• SELECT * FROM Orders WHERE EXISTS (
SELECT customer_id FROM Customers WHERE Orders.customer_id =
Customers.customer_id AND Customers.age > 23 );

78
SQL NOT EXISTS
• We can also use the NOT operator to inverse the working of
the EXISTS clause.
• The SQL command executes if the subquery returns an empty
result-set.
• Example: Select customer id and first name from Customers
table if the customer id doesn't exist in the Orders table
• SELECT customer_id, first_name FROM Customers WHERE
NOT EXISTS (
SELECT order_id FROM Orders WHERE
Orders.customer_id = Customers.customer_id);

79

You might also like