Module 3 (1)
Module 3 (1)
https://smitha-jacob.github.io/smithajac20
Modul
e3
► SQL DML (Data Manipulation Language) - SQL queries on single and
multiple tables, Nested queries (correlated and non-correlated),
Aggregation and grouping, Views, assertions, Triggers,
► SQL data types.
► Physical Data Organization - Review of terms: physical and logical
records, blocking factor, pinned and unpinned organization. Heap
files, Indexing, Single level indices, numerical examples, Multi-
level-indices, numerical examples, B-Trees & B+-Trees (structure
only, algorithms notrequired), Extendible Hashing, Indexing on
multiple keys – grid files.
Page
3
SQL DML (Data Manipulation Language)
Data Manipulation
Language
► DML stands for Data Manipulation Language.
► It is a language used for selecting, inserting, deleting and
updating data in a database.
► It is used to retrieve and manipulate data in a relational database.
► There are three basic constructs which allow database program
and user to
enter data and information are:
► INSERT
► UPDATE
► DELETE
Page 5
SQL |
INSERT
► The INSERT INTO statement is used to insert new records
in a table.
► It is possible to write the INSERT INTO statement in two
ways:
► Specify both the column names and the values to be inserted:
► Syntax :
► INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
► If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query.
► Make sure that the order of the values is in the same order as the columns
in the table.
► Syntax
► INSERT INTO table_name VALUES (value1, value2, value3, ...);
Page 6
SQL | INSERT |
Example
CustomerI CustomerName ContactName Address City PostalCode Country
D
305 - 14th Ave. S.
89 White Clover Karl Jablonski Seattle 98128 USA
Suite 3B
Markets
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
► INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country) VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
CustomerI CustomerName ContactName Address City PostalCode Country
D
305 - 14th Ave. S.
89 White Clover Karl Jablonski Seattle 98128 USA
Suite 3B
Markets
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway
Page 7
SQL |
INSERT
► Insert Data Only in Specified Columns
► It is also possible to only insert data in specific columns.
► Syntax
► INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal',
'Stavanger', 'Norway');
► The selection from the "Customers" table will now look like this:
Page 8
SQL |
INSERT
► To insert multiple rows in a table using Single SQL
Statement
INSERT INTO
table_name(Column1,Column2,Column3,.......)
VALUES (Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
............................. ;
► Example
INSERT INTO STUDENT(ID, NAME,AGE,GRADE,CITY)
VALUES(1,"AMIT KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI"),
Page 9 (4,"RIYA KAPOOR",10,5,"UDAIPUR");
SQL |
UPDATE
► The UPDATE statement in SQL is used to update the data of an
existing table in
database.
► We can update single columns as well as multiple columns
using UPDATE statement as per our requirement.
► Syntax
UPDATE table_name
SET column1 = value1, column2 =
value2, ... WHERE condition;
► Note: The WHERE clause specifies
which record(s) that should be
updated. If you omit the WHERE
clause, all records in the table will
be updated!
Page
10
SQL | UPDATE |
CustomerID CustomerName
Example
ContactName Address City PostalCode Country
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedado Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
s y helados
Antonio
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Moreno
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglun
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
ds
snabbkö
p
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City=
'Frankfurt' WHERE CustomerID = 1;
Page
11
SQL | UPDATE |
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City=
'Frankfurt'
WHERE CustomerID = 1;
CustomerID CustomerName ContactName Address City PostalCode Country
Alfred Schmidt Obere Str. 57 Frankfurt 12209
1 Alfreds Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedado Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
s y helados
Antonio
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Moreno
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglun
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
ds
snabbkö
p
Page
12
SQL |
UPDATE
► UPDATE Multiple Records
► It is the WHERE clause that determines how many records will be
updated. UPDATE Customers
SET
ContactName='Juan'
WHERE CustomerName ContactName
CustomerID Address City PostalCode Country
Country='Mexico';
1 Alfreds Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Juan Avda. de la Mexico
2 Emparedado México D.F. 05021
Constitución
s y helados
2222
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
Thomas Hardy UK
4 Around the Horn 120 Hanover Sq. London WA1 1DP
Berglun
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
ds
snabbkö
p
Page
13
SQL |
UPDATE
► If you omit the WHERE clause, ALL records will be
updated!
UPDATE Customers
SET ContactName='Juan';
CustomerID CustomerName ContactNam Address City PostalCode Country
e
1 Alfreds Juan Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedado Juan México D.F. 05021 Mexico
Constitución
s y helados
2222
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
Berglun
5 Juan Berguvsvägen 8 Luleå S-958 22 Sweden
ds
snabbkö
p
Page
14
SQL |
DELETE
► The DELETE Statement in SQL is used to delete existing records
from a table.
► We can delete a single record or multiple records depending on the
condition we specify in the WHERE clause.
► Syntax
► DELETE FROM table_name WHERE condition;
► The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE
clause, all records in the table will be deleted!
Page
15
SQL | DELETE |
Example
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedado Ana Trujillo México D.F. 05021 Mexico
Constitución
s y helados
2222
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
Page
16
SQL |
DELETE
► Delete All Records
► It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
► Syntax
► DELETE FROM table_name;
► Example
► DELETE FROM customers;
Page
17
Basic Query
Structure
► A typical SQL query has the form:
► Ri represents a relation
► Ai represents an attribute
► P is a predicate.
► The result of an SQL query is a
relation.
Page
18
The select
Clause
► The select clause lists the attributes desired in the result of a query
► corresponds to the projection operation of the relational algebra
► Example: find the names of all instructors:
select name from instructor
► NOTE: SQL names are case insensitive (i.e., you may use upper-
or lower-case
letters.)
► E.g., Name = NAME = name
Page
19
The select Clause
SELECT name
from
instructor
Page
21
The select
Clause
SELECT
DISTINCT
dept_name
FROM
instructor
Page
22
The select Clause
► An asterisk in the select clause denotes “all
attributes”
select * from instructor
Page
23
The select
► Clause
The select clause can contain arithmetic expressions involving the
operation, +,
–, , and /, and operating on constants or attributes of tuples.
► The query:
SELECT
ID,name,salary
/12 FROM
instructor
Page
25
The where
► Clause
The where clause specifies conditions that the result must satisfy
► Corresponds to the selection predicate of the relational algebra.
► To find all instructors in Comp. Sci. dept
select name
from
instructor
where
dept_name
= ‘Comp.
Sci.'
► Comparison results can be combined using the logical connectives
and, or, and not
► To find all instructors in Comp. Sci. dept with salary > 80000
select name
Page
26 from
The where
Clause
Page
27
The from
► Clauseinvolved in the query
The from clause lists the relations
► Corresponds to the Cartesian product operation of the relational algebra.
► Find the Cartesian product instructor X teaches
select *
from instructor, teaches
► generates every possible instructor – teaches pair, with all attributes from both
relations.
► For common attributes (e.g., ID), the attributes in the resulting table are
renamed using the
relation name (e.g., instructor.ID)
► Cartesian product not very useful directly, but useful combined
with where- clause condition (selection operation in relational
algebra).
Page
28
The from
Clause
Page
30
SQL SELECT
COUNT
Bike_Name Bike_Color Bike_Cost
Pulsar Black 185,000
Apache Black NULL
KTM RC Red 90,0000 SELECT COUNT
Royal Enfield White NULL (Bike_Color) AS
TotalBikeColor FROM
Livo Black 80,000 Bikes ;
KTM DUKE Red 195,000
TotalBikeColor
6
Page
31
SQL SELECT
► COUNT(*)
The count(*) function in SQL shows all the Null and Non-Null
records present in the table.
► Syntax of Count (*) Function in SQL
► SELECT COUNT(*) FROM table_name;
Page
32
SQL SELECT
Bike_Name Bike_Color
COUNT(*)
Bike_Cost
Livo Black 185,000 Suppose, you want to count
the total number of records from
Apache Red NULL the Bike Table.
Pulsar Red 90,0000
Royal Black NULL SELECT COUNT (*) FROM Bikes
Count(*)
Enfield ; 6
KTM DUKE Black 80,000
KTM RC White 195,000
Page
33
Count With WHERE clause in SQL
► We can also use the Count() function with the WHERE clause.
► The Count Function with WHERE clause in the SELECT statement
shows those records that matched the specified criteria.
► Syntax of Count() Function With WHERE clause in SQL
► SELECT COUNT(column_name) FROM
table_name
WHERE [condition];
Page
34
Count With WHERE
clause in SQL
Bike_Name Bike_Color Bike_Cost
Count the total number of bikes whose
Apache Black 90,0000 color is
Livo Black NULL black.
KTM RC Red 185,000
KTM DUKE White NULL SELECT COUNT
Royal Enfield Red 80,000
(Bike_Name) AS
Pulsar Black 195,000
TotalBikeBlackColor FROM
Bikes WHERE Bike_Color =
'Black';
TotalBikeBlackColor
3
Page
35
Count With WHERE clause in
SQL - Exercise
Emp_Id Emp_Name Emp_Salary Emp_City
Page
36
Count With DISTINCT keyword
► The DISTINCT keyword with the COUNT function shows only the
numbers of unique rows of a column.
► Syntax of Count Function With DISTINCT keyword in SQL
► SELECT COUNT(DISTINCT column_name) FROM table_name WHERE
[condition];
Car_Name Car_Color Car_Cost
i20 White 10,85,000
Hyundai Venue Black 9,50,000
SELECT
Swift Dezire Red 9,00,000
Hyundai Creta White 7,95,000
Kia Seltos White 8,00,000 COUNT
Kia Sonet Red 10,00,000
Page
38
Count With DISTINCT keyword-Example Mysql
Page
41
SQL ORDER BY
► Clause
Syntax to sort the records in ascending order:
Page
42
SQL ORDER BY
Clause
Page
43
SQL ORDER BY
Clause
ID NAME AGE ADDRESS SALARY
Page
46
SQL DML (Data Manipulation Language)
SQL JOIN
Page
44
SQL JOIN
► How do I get data from multiple tables?
► A SQL JOIN combines records from two
tables.
► A JOIN locates related column values in the
two tables.
► A query can contain zero, one, or
multiple JOIN operations.
► INNER JOIN is the same as JOIN; the keyword
INNER is optional.
Page
49
SQL
JOIN
► Four different types of JOINs
► (INNER) JOIN: Select records that
have matching values in both
tables.
► FULL (OUTER) JOIN: Selects all
records that match either left or
right table records.
► LEFT (OUTER) JOIN: Select records
from the first (left-most) table
with matching right table records.
► RIGHT (OUTER) JOIN: Select records
from the second (right-most) table
with matching left table records
Page
50
The SQL JOIN syntax
Page
51
The SQL JOIN Example
OR
Page
52
The SQL JOIN
►
Example
Problem: List all orders with customer information
SELECT OrderNumber, TotalAmount, FirstName,
LastName, City, Country FROM Order JOIN Customer
ON Order.CustomerId = Customer.Id
Page
53
SQL LEFT
JOIN
► What is a LEFT JOIN in SQL?
► A LEFT JOIN performs a join starting with the first (left-
most) table.
► Then, any matched records from the second table (right-
most) will be included.
► LEFT JOIN and LEFT OUTER JOIN are the same.
Page
54
The SQL LEFT JOIN syntax
► The general LEFT OUTER JOIN syntax is
SELECT column-names
FROM table-name1 LEFT OUTER JOIN table-name2
ON column-name1 = column-name2
WHERE condition
Page
56
SQL LEFT JOIN
Example
► Problem: List all customers and the total amount they spent
irrespective
whether they placed any orders or not.
SELECT OrderNumber, TotalAmount, FirstName,
LastName, City, Country
FROM Customer C LEFT JOIN Order O
ON O.CustomerId = C.Id
ORDER BY TotalAmount
Page
57
SQL RIGHT
JOIN
► What is a RIGHT JOIN in SQL?
► A RIGHT JOIN performs a join starting with the second (right-most) table
and then any
matching first (left-most) table records.
► RIGHT JOIN and RIGHT OUTER JOIN are the same.
Page
58
The SQL RIGHT JOIN syntax
► The general RIGHT OUTER JOIN syntax is:
SELECT column-names
FROM table-name1 RIGHT OUTER JOIN table-
name2
ON column-name1 = column-name2
WHERE condition
Page
60
SQL RIGHT JOIN Examples
► Problem: List customers that have not placed orders
SELECT TotalAmount, FirstName, LastName,
City, Country
FROM [Order] O RIGHT JOIN Customer C
ON O.CustomerId = C.Id
WHERE TotalAmount IS NULL
Page
61
SQL FULL
JOIN
► What does a SQL FULL JOIN return?
► FULL JOIN returns all matching records from both tables whether
the other table matches or not.
► Be aware that a FULL JOIN can potentially return very large
datasets.
► These two: FULL JOIN and FULL OUTER JOIN are the same.
Page
62
The SQL FULL JOIN syntax
► The general FULL OUTER JOIN syntax is:
SELECT column-names
FROM table-name1 FULL OUTER JOIN table-name2
ON column-name1 = column-name2
WHERE condition
Page
63
SQL FULL JOIN
Examples
► Problem: Match all customers and suppliers by country
SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry,
S.Country AS SupplierCountry, S.CompanyName
FROM Customer C FULL JOIN Supplier S
ON C.Country =S.Country
ORDER BY C.Country, S.Country
Page
64
Aggregation and grouping
Aggregation and grouping
► Aggregate functions are a very powerful tool to analyze the data
and gain
useful business insights.
► The most commonly used SQL aggregate functions include SUM, MAX,
MIN, COUNT
and AVERAGE.
► Aggregators are very often used in conjunction with Grouping
functions in
order to summarize the data.
Page
66
SQL
COUNT()
► The COUNT() function returns the number of rows that matches a specified
criteria.
► SQL COUNT(column_name)
► The COUNT(column_name) function returns the number of values (NULL values
will not be counted) of the specified column:
► SELECT COUNT(column_name) FROM table_name;
► SQL COUNT(*)
► The COUNT(*) function returns the number of records in a table:
► SELECT COUNT(*) FROM table_name;
► SQL COUNT(DISTINCT column_name)
► The COUNT(DISTINCT column_name) function returns the number of distinct
values of the
specified column:
► SELECT COUNT(DISTINCT column_name) FROM
Page
table_name;
67
SQL COUNT()
Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1
Page
68
SQL COUNT(*)
Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1
Page
69
SQL COUNT(DISTINCT
column_name) Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1
COUNT(DISTINCT ShipperID)
2
Page
70
SQL SUM,
AVG
► SELECT SUM returns the sum of the data
values.
► And SELECT AVG returns the average of the
data values.
► The general SUM syntax is:
SELECT SUM(column-name)FROM table-name
► The general AVG syntax is:
SELECT AVG(column-name)FROM table-name
Page
71
SQL SUM, AVG
Examples
► Problem: Compute the total amount sold in 2013.
► SELECT SUM(TotalAmount) Sum
FROM [Order] 658388.7
WHERE YEAR(OrderDate) = 2013 5
Page
72
SQL MAX and
MIN
► SELECT MIN returns the minimum value for a
column.
► And SELECT MAX returns the maximum value for a
column.
Page
75
SQL GROUP BY
Clause
► The SQL GROUP BY syntax
SELECT column-names
FROM table-name
WHERE condition GROUP BY
column-names
► The general syntax with ORDER BY is:
SELECT column-names
FROM table-
name
WHERE condition
GROUP BY column-
Page names
76
SQL GROUP BY Clause -
Example
► Problem: List the number of books in each book category
Page
77
SQL GROUP BY Clause
Example
► Problem: List the number of customers in each
country.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
Page
78
SQL GROUP BY Clause -
Example
► Problem: List the number of books published by each publisher in
the descending order of publisher name.
► SELECT COUNT(bookid) as Number_of_books, publisher FROM book1
GROUP BY publisher
ORDER by publisher DESC;
Page
79
SQL GROUP BY Clause
Example
Problem: List the number of customers in each country sorted
high to low
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
ORDER BY COUNT(Id) DESC
Page
80
SQL GROUP BY Clause
Example
Problem: List the total amount of each category of
books as tot_bookprice and book category in the highest
amount order.
SELECT SUM(b1.bookprice) AS
tot_bookprice,b.bcategory
FROM book1 b1 JOIN book b ON
b.bookid=b1.bookid
GROUP BY b.bcategory
ORDER BY SUM(b1.bookprice) DESC;
Page
81
SQL GROUP BY Clause
Example
Problem: List the total amount ordered for each customer in the
highest amount order.
SELECT SUM(O.TotalAmount) AS SUM, C.FirstName, C.LastName
FROM Order O JOIN Customer C
ON O.CustomerId = C.Id
GROUP BY C.FirstName,
C.LastName
ORDER BY SUM(O.TotalAmount)
DESC
Page
82
SQL HAVING
Clause
► What does the HAVING clause do in a query?
► The HAVING clause is like WHERE but operates on grouped records returned
by a GROUP BY.
► HAVING applies to summarized group records, whereas WHERE
applies to individual records.
► Only the groups that meet the HAVING criteria will be returned.
► HAVING requires that a GROUP BY clause is present.
► Both WHERE and HAVING can be used in the same query at the
same time.
Page
83
The SQL HAVING
syntax
► The general syntax is
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
► The general syntax with
ORDER BY is:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
ORDER BY column-
Page
84
names
SQL GROUP BY
Examples
► Problem: List the number of books published by each publisher and
the publisher name, who has published more than one book.
Page
85
SQL GROUP BY
Examples
► Problem: List the number of books available in each edition in the
ascending order of edition.
Page
86
SQL GROUP BY
Examples
► Problem: List the number of books available(with more than 1
books) in each edition in the ascending order of edition.
Page
87
SQL GROUP BY
Examples
► Problem: List the number of customers in each country. Only include
countries
with more than 10 customers.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
HAVING COUNT(Id)
> 10
Page
88
SQL GROUP BY ,where,having ,order by
Examples
Problem: List the number of customers in each country, except the
USA, sorted
high to low. Only include countries with 9 or more customers.
SELECT
COUNT(Id), Country
FROM Customer
WHERE Country <> 'USA'
GROUP BY Country
HAVING COUNT(Id) >= 9
ORDER BY COUNT(Id) DESC
Page
89
SQL GROUP BY
Examples
Problem: List all customer with average orders between $1000 and
$1200.
SELECT AVG(TotalAmount), FirstName, LastName
FROM Order O JOIN Customer C ON O.CustomerId = C.Id
GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200
Page
90
Nested Queries
SQL 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.
or
Page
82
SQL IN and Not in
Operator
Problem : Display all customers who are located in Germany, France
or UK:
Problem: List all customers that are from the same countries as the
suppliers:
Page
82
Sub Query
in SQL
► SubQuery in SQL is a query inside another query.
► Some time to get particular information from a database you may
need to fire two separate SQL queries, subQuery is a way to
combine or join them in a single query.
► SQL query which is on the inner part of the main query is
called inner query
while the outer part of the main query is called outer query.
► for example in below SQL query
SELECT name FROM city WHERE pincode IN (SELECT
pincode FROM pin WHERE zone='west')
Page
82
Sub Query
in SQL
Page
83
Noncorrelated
Subqueries
► A noncorrelated subquery executes independently of the
outer query.
► The subquery executes first, and then passes its results
to the outer
query,
For example:
► Find the instructor who draws second highest salary
Page
84
Noncorrelated Subqueries
SELECT MAX(salary) from instructor WHERE salary NOT IN
(SELECT MAX(salary) FROM instructor)
Page
86
Correlated
Subqueries
► The same query can written as a correlated
subquery
SELECT as
e.name, e.salary from instructor e
where 2= (SELECT COUNT(`salary`) FROM
instructor p WHERE e.salary >= p.salary)
► In this example, the subquery is SELECT COUNT(`salary`) FROM
instructor p WHERE e.salary <= p.salary, you cannot swap
it's value for the outer query because it needs to be executed for
each employee.
► A correlated subquery depends upon the outer query and
cannot execute in isolation
► A correlated subquery is much slower than a non-correlated
subquery
Page
87
Correlated
Subqueries
SELECT e.name, e.salary from instructor e
where 2= (SELECT COUNT(DISTINCT `salary`)
FROM instructor p WHERE e.salary >=
p.salary)
Page
87
Correlated
Subqueries
► A correlated subquery depends upon the outer query and
cannot execute in isolation
► A correlated subquery is much slower than a non-correlated
subquery
► Here is an example for a typical correlated subquery.
► Find all employees whose salary is above average for their
department.
► In the above nested query the inner query has to be re-executed for
each employee.
Page
87
Subqueries with EXISTS or NOT EXISTS
Subqueries with EXISTS or
NOT EXISTS
► Use EXISTS to identify the existence of a relationship without regard for the
quantity.
► For example, EXISTS returns true if the subquery returns any rows,
and [NOT] EXISTS returns true if the subquery returns no rows.
► The EXISTS condition is considered to be met if the subquery returns at
least one row.
► Syntax
SUPPLIER
Subqueries with EXISTS or
NOT EXISTS
Page
91
Why Views in
DBMS?
► Views are a special version of tables in SQL.
► They provide a virtual table environment for various complex
operations.
► You can select data from multiple tables, or you can select
specific data based on certain criteria in views.
► It does not hold the actual data; it holds only the definition of
the view in
the data dictionary.
► The view is a query stored in the data dictionary, on
which the user can query just like they do on tables.
► It does not use the physical memory, only the query is stored
in the data
dictionary.
Page► It is computed dynamically, whenever the user performs any
92
Why Views in
DBMS?
► In COMPANY database we may frequently issue queries that
retrieve the
employee name and the project names that the employee works
on.
► Rather than having to specify the join of the three tables
EMPLOYEE, WORKS_ON, and PROJECT every time we issue this
query, we can define a view that is specified as the result of
these joins.
► Then we can issue queries on the view, which are specified as
Page
93 single table retrievals rather than as retrievals involving two
Views (Virtual
Tables) in SQL
► A view in SQL terminology is a single table that is derived from other tables
► This limits the possible update operations that can be applied to views, but it does not
Page
95
Create a SQL
VIEW
► The syntax to create a VIEW is as follows:
Page
96
SQL CREATE VIEW
Examples
► The following SQL creates a view that shows all customers from
Brazil:
UNIQUE ASSERTION
S
NOT
NULL
ENITITY INTEGRITY
REFERENTIAL
INTEGRITY
Asserti
ons
► Creation of assertions are constraints that are not associated with only
one table.
► An assertion statement should ensure a certain condition will always
exist in the database.
► DBMS always checks the assertion whenever modifications are done
in the
corresponding table.
► We can use Assertions when we know that the given particular
condition is always true.
► Assertions are not linked to specific table or event.
► It performs task specified or defined by the user.
► When the SQL condition is not met then there are chances to an entire
table or even Database to get locked up.
Asserti
ons
► An assertion is a predicate expressing a condition we wish the
database to always satisfy.
► Domain constraints, functional dependency and referential
integrity are special forms of assertion.
► Where a constraint cannot be expressed in these forms, we
use an assertion, e.g.
► Ensuring the sum of loan amounts for each branch is less than
the sum of all
account balances at the branch.
► Ensuring every loan customer keeps a minimum of $1000 in an
account.
► An assertion in SQL takes the form,
► create assertion assertion-name check
predicated
Asserti
ons
► Confirm that the employee salary should be between 5000 and
300000
What is
Trigger?
What is
Triggers?
► The statement following FOR EACH ROW defines the trigger body;
► that is, the statement to execute each time the trigger activates,
which occurs once for each row affected by the triggering event.
► In the example, the trigger body is a simple SET that accumulates
into a user
variable the values inserted into the amount column.
► The statement refers to the column as NEW.amount which means
“the value of the amount column to be inserted into the new row.”
► To use the trigger, set the accumulator variable to zero, execute an
INSERT
statement, and then see what value the variable has afterward:
exam
ple
exam
ple
exam
ple
Example-inserting data into
tbstudent
Example-inserting data into
tbstudent
Example-after update
Example-after delete
Trigger Uses
Modul
e3
► SQL DML (Data Manipulation Language) - SQL queries on single and
multiple tables, Nested queries (correlated and non-correlated),
Aggregation and grouping, Views, assertions, Triggers,
► SQL data types.
► Physical Data Organization - Review of terms: physical and logical
records, blocking factor, pinned and unpinned organization. Heap
files, Indexing, Single level indices, numerical examples, Multi-level
indices, numerical examples, B-Trees & B+-Trees (structure only,
algorithms not required), Extendible Hashing, Indexing on multiple
keys – grid files.
Page
3
Physical Data Organization
Outli
ne
► It’s all about disks! That’s why we always draw
databases as
► Databases typically stored physically as files of records on
magnetic disks
► Three primary methods for organizing file records on
disk
► Unordered records
► Ordered records
► Hashed records
► The DBMS software can then retrieve, update and process this
data as needed
► Storing data on a disk
► Record Layout
Storage
hierarchy
► primary storage:
► Fastest media but volatile
► cache, main memory
► Fast access and limited storage capacity
► secondary storage: next level in hierarchy, non-volatile,
moderately fast access
time
► also called on-line storage
► E.g. flash memory, magnetic disks
► tertiary storage: lowest level in hierarchy, non-volatile, slow
access time
► also called off-line storage
► E.g. magnetic tape, optical storage
Storage
hierarchy
Registers Why a
hierarchy?
Cach
e
Memor
y
Dis
k
Tap
e
Storage Organization of
Databases
► Persistent data-large amount of data must persist over a long
period. part of this data is accessed and processed repeatedly
during this period
► Transient data persists only for a limited time.
► Exists only during program execution
► Most databases are stored permanently on magnetic disk storage
► File organization
► Determines how records are physically placed on the disk
► Determines how records are accessed
► primary File organization
► determines how the file records are physically placed on disk
and hence how the records can be accessed
Primary file Organization of
Databases
► several primary File organization
► Example:
CREATE TABLE User(uid INT, name CHAR(20), age INT, salary FLOAT);
0 4 24 28 32
154 Ram (padded with 35 25632.5
space)
Files, Fixed-Length Records, and
Variable-Length Records
► The file records are of the same record type, but one or
more of the fields are of varying size (variable-length
fields).
► For example, the Name field of EMPLOYEE can be a
variable-length field.
► 2 Variable length record,with
seperator
Files, Fixed-Length Records, and Variable-Length Records
► For spanned
⎡ records,
►
bfr =(B/R⎤ (ceiling function) rounds the value x up to
the next integer.
Page
3
Indexing
Heap files
Page
3
Heap files
Page
3
Heap Files
Why Indexing is
used?
• Indexing helps you to reduce the total number of I/O operations needed to
retrieve that data.
Indexi
ng
► Indexing is used to optimize the performance of a database by
minimizing the
number of disk accesses required when a query is processed.
► The index is a type of data structure. It is used to locate and access
the data in a database table quickly.
► Indexing is a data structure technique which allows you to quickly
retrieve
records from a database file.
► An Index is a small table having only two columns.
► The first column comprises a copy of the primary or candidate key
of a table.
► Its second column contains a set of pointers for holding the address
of the
disk block where that specific key value stored.
Index
Structures
► The index structures are additional files on disk that provides an
alternative ways to access the records without affecting
the physical placement of records in the primary data file on disk,
► Access of records are based on the indexing fields
that are used to construct the index.
► Any fields /attribute of the table can be used to
create an index.
► A variety of indexes are possible ,each of them uses a particular
data structures to speed up the search.
Structure of an Index in Database
Indexing methods in Database
Types of Indexing
Primary Indexing
Primary Indexing
► Primary Indexing is applied to an ordered file of records
► If the index is created on the basis of the primary key of
the table, then it is known as primary indexing.
► These primary keys are unique to each record and contain 1:1
relations between the records.
► Primary Index is an ordered file that is fixed in length size with two
fields.
► The first field is the same as the primary key and the second, field is
pointed to that specific data block
► As primary keys are stored in sorted order, the performance of
the searching operation is quite efficient.
► There is one index entry in the index file for each block
► The primary index can be classified into two types: Dense index
and Sparse index.
Primary Indexing
Page Presentation
205 title
Primary Indexing
Sparse
Index
1
5
9
13
Index Table
Searching
Mechanism
► If you want to find the record of roll 111
in the diagram, then it will search the
highest entry which is smaller than or
equal to 111 in the first level index. It
will get 100 at this level.
► Then in the second index level, again
it does max (111) <= 111 and gets
110. Now using the address 110, it
goes to the data block and starts
searching each record till it gets 111.
► This is how a search is performed in
this method. Inserting, updating or
deleting is also done in the same
manner
Secondary Index
► A secondary index provides a logical ordering on the records by the
indexing
field.
► The block pointer in the index entry points to a disk block, which
contains a set of record pointers
► Record pointer pointing to each of the repeating blocks
► Each record pointer in that disk block points to one of the data file
records
► If we access the records in order of the entries in the secondary
index , we get them in order of the indexing field
► The primary and clustering indexes assume that the field used for
the physical
ordering of records in the file is the same as the indexing field
Example
► A tree is formed of nodes. Each node except the root, has one
parent node and 0 or more child nodes
► The root node has no parent. A node with no child nodes is a leaf
node
► A non-leaf node is an internal node. The level of a node is always
one higher than its parent. The level of the root node is 0.
► A subtree of a node consists of that node and all its descendant
nodes
► If the leaf nodes are at different levels, it is an unbalanced tree
► B-tree nodes are kept 50-100% full
► Pointers to the data blocks are stored at internal and leaf nodes for
B-trees
► Pointers to the data blocks are stored at leaf nodes for B+ trees
Dynamic Multilevel Indexes
►
Using B-Tree
Search trees:
► A search tree is a special type of tree used to guide the search for a
record given the
value of one of the record’s fields.
► A search tree of order p is a tree such that each node contains p-1 search
values
and p pointers.
► <P1, K1, P2, K2, ….Pq-1, Kq-1, Pq> where q<=p.
K1,K2,…Kq-1 are search values. Each Pi is a pointer to a child node or null
► We can use search tree as a mechanism to search for records on disk.
► Two constraints must hold all the time:
► Within each node K1 < K2 < K3 < X < Ki
► For all values of X in the subtree pointed at by Pi
We have; Ki-1 < X < Ki
Dynamic Multilevel Indexes
Using B-Tree
Node in a
search tree
Search
trees
Dynamic Multilevel Indexes
Using B-Tree
► P1 –Subtree
Pr-actual record/data file
Dynamic Multilevel Indexes
Using B-Tree
► Suppose we want to insert a record 60 in the below structure. It will go to the 3rd leaf
node after 55. It is a balanced tree, and a leaf node of this tree is already full, so we
cannot insert 60 there.
► In this case, we have to split the leaf node, so that it can be inserted into tree without
affecting the fill factor, balance and order.
► The 3rd leaf node has the values (50, 55, 60, 65, 70) and its current root node is 50.
We will split the leaf node of the tree in the middle so that its balance is not altered.
So we can group (50, 55) and (60, 65, 70) into 2 leaf nodes.
► If these two has to be leaf nodes, the intermediate node cannot branch from 50. It
should have 60 added to it, and then we can have pointers to a new leaf node.
Inserting a record in a B+ Tree
Deleting a record in a B+ Tree
► Suppose we want to delete 60 from the above example. In this case, we have to
remove 60 from the intermediate node as well as from the 4th leaf node too. If we
remove it from the intermediate node, then the tree will not satisfy the rule of the B+
tree. So we need to modify it to have a balanced tree.
► After deleting node 60 from above B+ tree and re-arranging the nodes, it will show as
follows:
Hashing
Hashing
In DBMS, hashing is a technique to directly search the location
of desired data on the disk without using an index structure.
Hashing method is used to index and retrieves items in a database
as it is faster to search that specific item using the shorter hashed
key instead of using its original value.
Data is stored in the form of data blocks whose address is
generated by applying a hash function in the memory location
where these records are stored known as a data block or data
bucket.
► Data bucket – Data buckets are memory locations where the
records are stored. It is also known as a Unit Of Storage.
► Hash function: A hash function, is a mapping function that maps
all the set of search keys to the address where actual records are
placed.
Internal Hashing
► K=21,,M=7
21 MOD 7=0
► 23 mod 7=2
Other Hashing Techniques
Other Hashing Techniques
External Hashing
Extendible Hashing
Dynamic Hashing
Dynamic Hashing
Linear Hashing
Grid Files
Grid Files
Thank You
Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective
content creators. Document is compiled exclusively for study purpose and shall not be used for commercial purpose.