DBMS - Week 3 ~ Parampreet Singh
DBMS - Week 3 ~ Parampreet Singh
Nested Subqueries
• We can write a query (sub-query) inside a query, called a nested subquery.
• A subquery is a SELECT-FROM-WHERE expression that is nested within another query.
• The nesting can be done in the following SQL query:
SELECT A1 , A2 , … , An
FROM r1 , r2 , … , rm
WHERE B < operation > (subquery)
Set Membership
• Set membership is used to check whether a particular tuple(row) is a member of a relation(table) or not.
• This can be done using IN and NOT IN operators.
SYNTAX:
Example:
• Find the names of all the students who have taken a course in the Sep 2022 and Jan 2023 term.
Set Comparison
SOME Clause
• The SOME clause will give the result if the condition is true for at least one of the tuples in the subquery.
SYNTAX:
Example:
• Find the names of instructors with salary greater than that of some (at least one) instructor in the Biology
department
SELECT name
FROM instructor
WHERE salary > SOME (
SELECT salary
FROM instructor
WHERE dept_name="Biology"
);
ALL Clause
• The ALL clause will give the result if the condition is true for all of the tuples in the subquery.
SYNTAX:
SELECT column1
FROM table_name
WHERE column1 > ALL (SELECT column1 FROM other_table);
Example:
• Find the names of instructors with salary greater than that of all instructors in the Biology department
EXISTS Clause
• The EXISTS clause will return True if the subquery returns at least one tuple, else it will return False .
• If it returns True , outer query retrives the specified columns from the sub query.
SYNTAX:
Example:
• Find all courses taught in both the Fall 2009 and Spring 2010 terms.
SELECT course_id
FROM section AS S1
WHERE semester="Fall" AND year=2009
AND EXISTS (
SELECT *
FROM section AS S2
WHERE semester="Spring" AND year=2010
AND S1.course_id = S2.course_id
);
• The NOT EXISTS clause will return True if the subquery returns no tuples, else it will return False , it's
the opposite of EXISTS clause.
• If it returns True , outer query retrives the specified columns from the sub query.
SYNTAX:
Example:
SYNTAX:
Example:
• Find the average instructors salaries of those deparatments whose average salary is greater than 40, 000.
WITH Clause
• The WITH clause is used to define a temporary relation (table) whose definition is available only to the
query in which the WITH clause occurs.
SYNTAX:
WITH temp_table_name(attribute_list) AS (
SELECT exp1, ...
FROM table1, ...
WHERE condition
)
SELECT temp_table_name.attribute1
FROM temp_table_name, ...
WHERE condition;
Example:
https://github.com/Param302 https://twitter.com/Param3021 https://t.me/Param_302
• Find all departments with the maximum budget
WITH max_budget(budget) AS (
SELECT max(budget)
FROM department
)
SELECT dept_name
FROM department, max_budget
WHERE department.budget = max_budget.budget;
WITH avg_total(total) AS (
SELECT avg(total_amount)
FROM orders
)
SELECT *
FROM orders, avg_total
WHERE orders.total_amount > avg_total.total;
Scalar Subquery
• Scalar Subquery is used where a single value is expected
• It gives Runtime Error if the subquery returns more than one tuple.
SYNTAX:
SELECT <attribute>, (
SELECT scalar_subquery
) AS <alias>
FROM <relation>;
Example:
• List all departments along with the number of instructors in each department.
SELECT dept_name, (
SELECT COUNT(*)
FROM instructor
WHERE department.dept_name = instructor.dept_name
) AS num_instructors
FROM department;
CASE-WHEN Expression
• The CASE statement is used to evaluation a condition and return a value Yased on the outcome.
• The ELSE clause is used to specify a default value that will be returned if none of the conditions are met.
SYNTAX:
Example:
• Give discount in total bill of 10% where bill is equal to or greater than 5, 000, and 5% where bill is less
than 5, 000.
SELECT order_id, (
CASE
WHEN total_amount >= 5000 THEN total_amount * 0.9
ELSE total_amount * 0.95
END
) AS total_after_discount
FROM orders;
Join Expressions
• Join operations take two relations and returns as a result another relation.
• A join operation is a Cartesian product followed by a selection.
• The join operations are typically used as a subquery expressions in the FROM clause.
prereq
course_id prereq_id
BIO-301 BIO-101
BIO-190 BIO-101
CS-347 CS-101
Cross Join
• CROSS JOIN returns the Cartesian product of the two relations.
Explicit Syntax:
SELECT *
FROM table1 CROSS JOIN table2;
Implicit Syntax:
SELECT *
FROM table1, table2;
Inner Join
• INNER JOIN returns the tuples from all the relations.
• It includes same column names from both the tables on which the join is performed.
• It includes only those tuples which satisfy the join condition.
INNER JOIN
SYNTAX:
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column
INNER JOIN table3 ON table2.column = table3.column;
Example:
SELECT *
FROM Course
INNER JOIN prereq ON Course.course_id = prereq.course_id;
Natural Join
• NATURAL JOIN returns the tuples from all the relations.
• It only includes one column name from which the join is performed.
• It only includes those tuples which satisfy the join condition.
NATURAL JOIN
Table 1 Table 2
SYNTAX:
Example:
SELECT *
FROM Course
NATURAL JOIN prereq;
Outer Join
• OUTER JOIN returns the tuples from all the relations.
• It includes unmatched tuples from one or both the tables on which the join is performed.
• If there are no mathcing rows, NULL values are used.
• LEFT OUTER JOIN returns all the tuples from the left table and only those tuples from the right table which
satisfy the join condition.
• If there are no matching rows, NULL values are used.
Table 1 Table 2
SYNTAX:
Example:
SELECT *
FROM Course
LEFT OUTER JOIN prereq ON Course.course_id = prereq.course_id;
• RIGHT OUTER JOIN returns all the tuples from the right table and only those tuples from the left table which
satisfy the join condition.
• If there are no matching rows, NULL values are used.
Table 1 Table 2
SYNTAX:
SELECT columns
FROM table1
RIGHT OUTER JOIN table2 ON table1.column = table2.column;
Example:
• FULL OUTER JOIN returns all the tuples from both the tables.
• If there are no matching rows, NULL values are used.
Table 1 Table 2
SYNTAX:
SELECT columns
FROM table1
FULL OUTER JOIN table2 on table1.column = table2.column;
Example:
SELECT *
FROM Course
FULL OUTER JOIN prereq ON Course.course_id = prereq.course_id;
Views
• *A View is a Virutal table* derived from one or more underlying tables or views.
Purpose of Views
• Simplify complex queries
Views can encapsulate complex queries, making them easier to use and understand by providing a
simplified and tailored view of the data.
• Data security
Views can restrict access to certain columns or rows of the underlying tables, allowing you to control the
level of data visibility for different users.
• Data Abstraction
Views can provide an abstraction layer by presenting a logical representation of the data, hiding the
underlying structure and complexity of the data.
SYNTAX
Example
• A view of instructors without their salary
Types of Views
• Depend directly
A view is said to depend directly on a table if it is created using the FROM clause and the table is listed in
the FROM clause.
◦ Example: The following view depends directly on the customers table:
• Depend on
A view is said to depend on a table if it is craeted using the FROM clause and the table is indirectly
referenced by another table that is listed in the FROM clause.
◦ Example: The following view depends on the orders table because the orders table is indirectly
referenced by the products table.
• Recursive views
A recursive view is a view that references itself in its FROM clause.
Recursive views can be used to create self-joins or to traverse a hierarchical data structure.
◦ Example: The following recursive view will return all customers and their children:
View Expansion
• It refers to the process by which a query involving a view is rewritten or expanded into an equivalent query
that directly accesses the underlying tables.
• When a query is executed against a view, the database system may interanlly perform view expansion to
optimize the query execution.
• Let view v1 be defined by an expression e1 that may itself contain uses of view relations.
• View expansion of an expression repeats the following replacement step:
REPEAT
Find any view relation vi in e1
Replce the view realtion vi by the expression defining vi
UNTIL no more view relations are present in e1
• As long as the view definitions are not recursive, this loop with terminate.
Updation of a View
• Adding a new tuple to some view v1 lead to updation in the underlying base tables.
Example:
• This insertion will represent insertion of this tuple in underlying instructor table
Materialized Views
• Materializing a view will create a physical table containing all the tuples in the result of the query defining
the view
• If relations used in the query are updated, the maerialized view will not be updated automatically.
Transactions
• a Transaction is a group of one or more SQL statements that are treated as a single unit of work.
• If the transaction is successful, all of the data modifications made during the transaction are committed and
become a permanent part of the database.
• If the transaction encounters ERRORS and must be cancelled or rolled back, then all of the data
modifications are erased.
• Transactions commands comes under Transaction Control Language (TCL)
ACID Properties
• Transactions are used to ensure the ACID properties of data
Atomicity
• A transaction is an atomic unit of work.
• This means that either all of the statements in the transaction are executed successfully, or none of them
are executed.
Consistency
• A transaction must maintain the consistency of the database.
• This means that the database must be in a valid state after the transaction is committed.
Isolation
• Transactions must be isolated from each other.
• This means that the changes made by one transaction must not be visible to other transactions until the first
Durability
• Once a transaction has been committed, the changes made by the transaction must be permanent.
• This means that they must not be lost even if the database crashes or the server loses power.
Integrity Constraints
• Integrity constraints are rules or conditions that are defined on database tables to enforce data integrity
and maintain the consistency of data.
• Integrity constraints commands comes under Data Definition Language (DDL).
NOT NULL
• The NOT NULL constraint ensures that a column cannot have a NULL value.
PRIMARY KEY
UNIQUE
• The UNIQUE constraint ensures that all values in a column are different.
Referential Integrity
• It ensures that if a value of one attribute of a relation (table) references a value of another attribute on
another relation (table), then the referenced value must exist.
ON DELETE CASCADE
• This constraint specifies that if a row is deleted from the parent table, then all rows in child table that
reference the deleted row will also be deleted.
ON UPDATE CASCADE
• This constraint specifies that if a row is updated in the parent table, then all rows in child table that
reference the updated row will also be updated.
• This constraint specifies that if a row is deleted from the parent table, then all rows in child table that
reference the deleted row will have the referencing column set to NULL .
• NO ACTION
• SET DEFAULT
• RESTRICT
• The DATE type is used for values with a date part but no time part.
• It's in the format: YYYY-MM-DD
TIME
TIMESTAMP
• The TIMESTAMP type is used for values that contain both date and time parts.
• It's in the format: YYYY-MM-DD HH:MI:SS:MS
• Example: TIMESTAMP '2023-06-30 12:30:45.56'
INTERVAL
Index
• An index is a data structure that improves the speed of data retrieval operations on a database table at the
cost of additional writes and storage space to maintain the index data structure.
Example
Example table:
student_id details
(John Doe,
1
Computer Science)
(Jane Doe,
2
Accounting)
Domains
• A domain is a user-defined data type that has a set of valid values.
Example:
CLOB
When a query returns a large object, a pointer is returned rather than the large object itself.
Authorization
Authorization Specification
• Authorization is specified using the GRANT and REVOKE statements.
Roles
• A role is a named group of privileges.
• Roles can be granted to users.
• Creating a role
◦ Example:
◦ Example:
◦ Example:
◦ Example:
GRANT TA TO student;
Functions
• Functions are used to perform a specific task such as performing calculations, transformations on data.
• Functions returns a value.
• Functions can be called from within other queries.
Calling
Procedures
• Procedures are used to perform actions on data such as inserting, updating, deleting rows from a table.
• Procedures do not return a value.
Invoking
Overloading
• SQL allows overloading of functions and procedures.
• This means that multiple functions/procedures can have the same name but different parameters.
Most database systems implement their own variant of the standard syntax.
Loops
• SQL supports two types of loops:
◦ WHILE loop
◦ REPEAT loop
WHILE loop
• The WHILE loop executes a block of code repeatedly as long as a condition is true.
WHILE condition DO
sequence of statements
END WHILE;
REPEAT loop
• The REPEAT loop executes a block of code repeatedly until a condition is true.
• This is similar to a DO-WHILE loop in other programming languages.
FOR loop
• The FOR loop executes a block of code repeatedly for a specified number of times.
DECLARE
n INTEGER DEFAULT 0;
FOR r AS
SELECT budget FROM department
DO
SET n = n + r.budget;
END FOR;
Conditional Statements
• SQL supports two types of conditional statements:
◦ IF-THEN-ELSE statement
◦ CASE statement
IF-THEN-ELSE statement
• The IF-THEN-ELSE statement executes a block of code if a condition is true, otherwise it executes another
block of code.
• If none of the conditions are true, then the ELSE block is executed.
IF condition THEN
sequence of statements
ELSEIF condition THEN
sequence of statements
ELSE
sequence of statements
END IF;
CASE statement
https://github.com/Param302 https://twitter.com/Param3021 https://t.me/Param_302
• The CASE statement executes a block of code based on a condition.
• It is similar to a switch-case statement in other programming languages.
CASE
WHEN condition THEN
sequence of statements
WHEN condition THEN
sequence of statements
ELSE
sequence of statements
END CASE;
CASE
WHEN sql-expression = value1 THEN
sequence of statements
WHEN sql-expression = value2 THEN
sequence of statements
ELSE
sequence of statements
END CASE;
Exception Handling
• Exception handling is used to handle errors that occur during execution of a program.
• SQL supports exception handling using the DECLARE EXIT HANDLER statement.
◦ The EXIT HANDLER is a block of code that will be executed when an exception occurs / raised.
◦ It can be used to perform any cleanup tasks such as rolling back a transaction or closing a connection.
• The SIGNAL statement is used to raise an exception.
-- If the custom exception is not raised, continue with the rest of the procedure
END;
Example
IF number2 = 0 THEN
SIGNAL divide_by_zero;
END IF;
Note: This exmaple I found from the internet, it's not much clear, but I hope you got the idea, how to use it.
SYNTAX:
• This statement creates a UDR named factorial that is written in C. The my_factorial_library library
contains the code for the factorial routine. The factorial routine is called factorial in the external
code file.
• TO call the factorial UDR, we use the CALL statement as follows:
CALL factorial(5);
Triggers
• Ttrigger in SQL is a stored procedure that is automatically executed when a specific event occurs on a
table.
• Triggers can bew used to enforce business rules, maintain data integrity, maintain an audit trail of changes
and automate certain actions within a database.
SYNTAX:
BEFORE triggers
AFTER triggers