Module 2 Relational Model & SQL (1)
Module 2 Relational Model & SQL (1)
• In procedural query language, user instructs the system to perform a series of operations to
produce the desired results. Here users tells what data to be retrieved from database and how to
retrieve it.
• In procedural query language, a user gives step-by-step instructions to the system on how to get the
information they want from a database.
For example – Let’s take a real world example to understand the procedural language, you are
asking your younger brother to make a cup of tea, if you are just telling him to make a tea and
not telling the process then it is a non-procedural language, however if you are telling the step
by step process like switch on the stove, boil the water, add milk etc. then it is a procedural
language.
Non-procedural query language:
• In Non-procedural query language, user instructs the system to produce the desired result
without telling the step by step process. Here users tells what data to be retrieved from database
but doesn’t tell how to retrieve it.
• In a non-procedural query language, the user only specifies what information they want from the
• You tell the system what data you need, and it figures out the most efficient way to get it for you.
• This approach allows for more flexibility and abstraction, as users don't have to worry about the
detailed process of retrieving the data – they just focus on what results they want.
Relational Algebra, Calculus, RDBMS & SQL:
• Relational algebra and calculus are the theoretical concepts used on
relational model.
• σ Condition/Predicate(Relation/Table name)
• Select Operator (σ) Example
• Table: CUSTOMER
• ---------------
• σ Customer_City="Agra" (CUSTOMER)
Examples to solve
• Select All Rows:
• The σ symbol represents the SELECT operator, and the condition inside the brackets specifies the rows to be selected.
• σ(True)(Employees)
• This selects all rows from the "Employees" relation because the condition is always true.
• π(FirstName, LastName)(σ(Department='IT')(Employees))
Project Operator (∏)
• Table: CUSTOMER
• Output:
• Customer_Name Customer_City
• ------------- -------------
• Steve Agra
• Raghu Agra
• Chaitanya Noida
• Ajeet Delhi
• Carl Delhi
Examples to solve
• Consider the following table
1. projection of CustomerName
and status from customer table.
2. Projection of id and name
From student table
Output
Union Operator (∪)
• Union operator is denoted by ∪ symbol and it is used to select all the rows (tuples)
from two tables (relations).
• Lets discuss union operator a bit more. Lets say we have two relations R1 and R2
both have same columns and we want to select all the tuples(rows) from these
relations then we can apply the union operator on these relations.
• Note: The rows (tuples) that are present in both the tables will only appear once in
the union set. In short you can say that there are no duplicates present after the
union operation.
• table_name1 ∪ table_name2
Union Operator (∪) Example
Query:
• Lets say we have two relations R1 and R2 both have same columns and we want
to select all those tuples(rows) that are present in both the relations, then in that
case we can apply intersection operation on these two relations R1 ∩ R2.
• Note: Only those rows that are present in both the tables will appear in the
result set.
• table_name1 ∩ table_name2
Intersection Operator (∩) Example
Lets take the same example that we have taken above.
• Query:
• Student_Name
• ------------
• Aditya
• Steve
• Paul
• Lucy
Set Difference (-)
• table_name1 - table_name2
Set Difference (-) Example
Lets take the same tables COURSE and STUDENT that we have seen above.
• Query:
• Lets write a query to select those student names that are present in
STUDENT table but not present in COURSE table.
• Student_Name
• ------------
• Carl
• Rick
Cartesian product (X)
• Cartesian Product is denoted by X symbol. Lets say we have two
relations R1 and R2 then the cartesian product of these two relations (R1
X R2) would combine each tuple of first relation R1 with the each tuple of
second relation R2. I know it sounds confusing but once we take an
example of this, you will be able to understand this.
• R1 X R2
Cartesian product (X) Example
Query:
Lets find the cartesian product of table R and S.
RXS
ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Extended Operators
• Derived from basic operators.
Extended
Operators
Types of Joins
• You may also perform EQUI JOIN by using JOIN keyword followed by ON
keyword and then specifying names of the columns along with their associated
tables to check equality.
Syntax:
• SELECT column_list
• FROM table1, table2....
• WHERE table1.column_name =
• table2.column_name;
• or
• SELECT *
• FROM table1
• JOIN table2
• [ON (join_condition)]
Outer Join
• An outer join doesn't require each record in the two join tables to have a
matching record.
• In this type of join, the table retains each record even if no other matching
record exists.
• Three types of Outer Joins are:
• Left Outer Join
• Right Outer Join
• Full Outer Join
Left Outer Join
Right Outer Join
Intersection Join
• SQL | INTERSECT Clause
• INTERSECT
Queries-2: Find the loan number for each loan of an amount greater or equal to 10000.
Queries-3: Find the names of all customers who have a loan and an account at the
bank.
Queries-4: Find the names of all customers having a loan at the “ABC” branch.
2. Domain Relational Calculus (DRC)
• Domain Relational Calculus is a non-procedural query language equivalent in
power to Tuple Relational Calculus. Domain Relational Calculus provides only
the description of the query but it does not provide the methods to solve it. In
Domain Relational Calculus, a query is expressed as,
• { < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) }
• where, < x1, x2, x3, …, xn > represents resulting domains variables and P (x1,
x2, x3, …, xn ) represents the condition or formula equivalent to the Predicate
calculus.
• the basic components and concepts of Domain Relational Calculus:
• Domains: In DRC, a domain is a set of possible values that an attribute in a relation can take. For example, the
single letters. For instance, "x" might represent a name from the "Name" domain.
• Predicates: Predicates are conditions that must be satisfied for a tuple to be included in the result. These
conditions are expressed using logical operators such as AND, OR, and NOT. For example, you might have a
predicate like "x = 'John'" to retrieve tuples where the name is 'John'.
• Quantifiers: DRC uses quantifiers to express the scope of variables. There are two types of quantifiers:
• Existential Quantifier (∃): Represents "there exists." For example, ∃x means "there exists an x."
• Universal Quantifier (∀): Represents "for all." For example, ∀x means "for all x."
• Suppose you have a relation called "Students" with attributes "Name" and "Age." You
want to find the names of all students who are 20 years old. In DRC, you could
express this as:
• A Database is defined as a structured set of data. So, in SQL the very first step to
store the data in a well structured manner is to create a database. The CREATE
DATABASE statement is used to create a new database in SQL.
• Syntax:
• The ALTER TABLE statement is also used to add and drop various constraints
on an existing table.
ALTER TABLE - ADD Column
• To add a column in a table, use the following syntax:
• Example
• ALTER TABLE Customers ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
• To delete a column in a table, use the following syntax (notice that
some database systems don't allow deleting a column):
• ALTER TABLE table_name DROP COLUMN column_name;
• The following SQL deletes the "Email" column from the "Customers"
table:
• Example
• ALTER TABLE Customers DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN
• To change the data type of a column in a table, use the following syntax:
• Oracle 10G and later:
• ALTER TABLE table_name MODIFY column_name datatype;
SQL RENAME TABLE
• A SQL DROP TABLE statement is used to delete a table definition and all data
from a table.
• This is very important to know that once a table is deleted all the information
available in the table is lost forever, so we have to be very careful when using
this command.
• Let's see the syntax to drop the table from the database.
• DROP TABLE "table_name";
SQL DELETE TABLE
• The DELETE statement is used to delete rows from a table. If you want to
remove a specific row from a table you should use WHERE condition.
• DELETE FROM table_name [WHERE condition];
• But if you do not specify the WHERE condition it will remove all the rows from
the table.
• DELETE FROM table_name;
• There are some more terms similar to DELETE statement like as DROP
statement and TRUNCATE statement but they are not exactly same there are
some differences between them.
Difference between DELETE and TRUNCATE statements
• When you use the drop statement it deletes the table's row together
with the table's definition so all the relationships of that table with
other tables will no longer be valid.
• When you drop a table:
• Table structure will be dropped
• Relationship will be dropped
• Integrity constraints will be dropped
• Access privileges will also be dropped
• On the other hand when we TRUNCATE a table, the table structure
remains the same, so you will not face any of the above problems.
DML Data Manipulation Language
• DML:
• SELECT
• INSERT
• UPDATE
• DELETE
• MERGE
• CALL
• EXPLAIN PLAN
• LOCK TABLE
SQL Select
= equal
WHERE clause is used in SELECT, UPDATE, DELETE
statement etc. > greater than
Let's see the syntax for sql where: < less than
1.SELECT column1, column 2, ... column n
>= greater than or equal
2.FROM table_name
3.WHERE [conditions] <= less than or equal
WHERE clause uses some conditional selection <> not equal to
SQL SELECT UNIQUE
• Actually, there is no difference between DISTINCT and UNIQUE.
• SELECT UNIQUE is an old syntax which was used in oracle
description but later ANSI standard defines DISTINCT as the official
keyword.
• After that oracle also added DISTINCT but did not withdraw the
service of UNIQUE keyword for the sake of backward compatibility.
• In simple words, we can say that SELECT UNIQUE statement is used
to retrieve a unique or distinct element from the table.
• the syntax of select unique statement.
1.SELECT UNIQUE column_name FROM table_name;
• SQL SELECT DISTINCT statement can also be used for the same
cause.
SQL SELECT DISTINCT
• The SQL first() function is used to return the first value of the
selected column.
• Let's see the syntax of sql select first() function:
1.SELECT FIRST(column_name) FROM table_name;
• Here a point is notable that first function is only supported by MS
Access.
SQL SELECT LAST
• The last() function is used to return the last value of the specified
column.
• Syntax for SQL SELECT LAST() FUNCTION:
1.SELECT LAST (column_name) FROM table_name;
• You should note that the last() function is only supported in MS
Access. But there are ways to get the last record in MySql, SQL
Server, Oracle etc. databases.
SQL INSERT INTO Statement
• It is not possible to test for NULL values with comparison operators, such as =,
<, or <>.
• We will have to use the IS NULL and IS NOT NULL operators instead.
• IS NULL Syntax
• SELECT column_names
FROM table_name
WHERE column_name IS NULL;
• IS NOT NULL Syntax
• SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
SQL UPDATE Statement
• /* Update the records in TARGET */ /* When no records are matched with SOURCE
• THEN UPDATE table
• SET TARGET.P_NAME = Then delete the records from the target table */
SOURCE.P_NAME, WHEN NOT MATCHED BY SOURCE
•
•
TARGET.P_PRICE = SOURCE.P_PRICE THEN DELETE
•
/* END OF MERGE */
• MERGE - UPSERT operation (insert or update)
• CALL - call a PL/SQL or Java subprogram
• EXPLAIN PLAN - interpretation of the data access path
• LOCK TABLE - concurrency Control
(DCL) DATA CONTROL LANGUAGE
• DCL is short name of Data Control Language which includes commands such
as GRANT and mostly concerned with rights, permissions and other controls
of the database system.
• Oracle Syntax:
• CREATE USER username IDENTIFIED BY password
COMMIT command
• This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
• If we have used the UPDATE command to make some changes into the
database, and realise that those changes were not required, then we can use
the ROLLBACK command to rollback those changes, if they were not
commited using the COMMIT command.
• Following is rollback command's syntax,
• ROLLBACK TO savepoint_name;
SAVEPOINT command
• To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:
• ALTER TABLE Persons ADD UNIQUE (ID);
• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
• ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
DROP a UNIQUE Constraint
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE
• The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
• CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
• To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
• CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
• Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However,
the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
SQL PRIMARY KEY on ALTER TABLE
• To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
• To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
• Note: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table
was first created).
DROP a PRIMARY KEY Constraint
• A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
• The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
• Look at the following two tables:
• The following SQL creates a FOREIGN KEY on the "PersonID" column when
the "Orders" table is created:
• CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
• To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN
KEY constraint on multiple columns, use the following SQL syntax:
• Often this is the primary key field that we would like to be created automatically every time a new record is
inserted.
• You will have to create an auto-increment field with the sequence object (this object generates a number
sequence).
• Examples
• The following example returns the current operating system date and time:
• SELECT TO_CHAR
• (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW"
• FROM DUAL;
• NOW
• -------------------
• 04-13-2001 09:45:51
SET Operations in SQL
• SQL supports few Set operations which can be performed on the table data.
These are used to get meaningful results from data stored in the table, under
different special conditions.
• UNION
• UNION ALL
• INTERSECT
• MINUS
UNION Operation
• The Minus operation combines results of two SELECT statements and return
only those in the final result, which belongs to the first set of the result.
• Group By Clause
• Having Clause
• Aggregate Functions
Group By Clause
• The GROUP BY Clause is utilized in SQL with the SELECT statement to
organize similar data into groups. It combines the multiple records in single or
more columns using some functions. Generally, these functions are aggregate
functions such as min(),max(),avg(), count(), and sum() to combine into single
or multiple columns. It uses the split-apply-combine strategy for data analysis.
• The inner query will return a set with members C1 and C3 and outer query will return those S_IDs
for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and
S4.
• Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it can be done
as:
• NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’, it can
be done as:
• For each row of STUDENT S, it will find the rows from STUDENT_COURSE
where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S,
atleast a row exists in STUDENT_COURSE SC with C_ID=’C1’, then inner
query will return true and corresponding S_ID will be returned as output.
VIEWS
• SQL CREATE VIEW Statement
• In SQL, a view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
• You can add SQL functions, WHERE, and JOIN statements to a view and present the data
as if the data were coming from one single table.
• Example
• CREATE VIEW [Brazil Customers] AS
• SELECT CustomerName, ContactName
• FROM Customers
• WHERE Country = "Brazil";
• SQL Updating a View
• A view can be updated with the CREATE OR REPLACE VIEW command.
• Example
• CREATE OR REPLACE VIEW [Brazil Customers] AS
• SELECT CustomerName, ContactName, City
• FROM Customers
• WHERE Country = "Brazil";
• SQL Dropping a View
• A view is deleted with the DROP VIEW command.
• Example
• DROP VIEW [Brazil Customers];
JOINS
• A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Different Types of SQL JOINs
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
SQL INNER JOIN Keyword
• The INNER JOIN keyword selects records that have matching values in both
tables.
• Example
• SELECT Orders.OrderID, Customers.CustomerName
• FROM Orders
• INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID;
• Note: The INNER JOIN keyword selects all rows from both tables as long
as there is a match between the columns. If there are records in the
"Orders" table that do not have matches in "Customers", these orders will
not be shown!
• JOIN Three Tables
• The following SQL statement selects all orders with customer and shipper
information:
• Example
• SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
• FROM ((Orders
• INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
• INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
• SQL LEFT JOIN Keyword
• The LEFT JOIN keyword returns all records from the left table (table1), and
the matched records from the right table (table2). The result is NULL from the
right side, if there is no match.
• Example
• SELECT Customers.CustomerName, Orders.OrderID
• FROM Customers
• LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
• ORDER BY Customers.CustomerName;
• Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
• SQL RIGHT JOIN Keyword
• The RIGHT JOIN keyword returns all records from the right table (table2),
and the matched records from the left table (table1). The result is NULL
from the left side, when there is no match.
• Example
• SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
• FROM Orders
• RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID
• ORDER BY Orders.OrderID;
• SQL FULL OUTER JOIN Keyword
• The FULL OUTER JOIN keyword returns all records when there is a match
in left (table1) or right (table2) table records.
• Note: FULL OUTER JOIN can potentially return very large result-sets!
• Tip: FULL OUTER JOIN and FULL JOIN are the same.
• Note: The FULL OUTER JOIN keyword returns all matching records from
both tables whether the other table matches or not. So, if there are rows in
"Customers" that do not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "Customers", those rows will be listed
as well.
• SQL Self JOIN
• A self JOIN is a regular join, but the table is joined with itself.
• Example
• SELECT A.CustomerName AS CustomerName1, B.CustomerName AS
CustomerName2, A.City
• FROM Customers A, Customers B
• WHERE A.CustomerID <> B.CustomerID
• AND A.City = B.City
• ORDER BY A.City;
• Consider the two tables below:
• Student
• Implement a query will show the names and age of students enrolled in
different courses.