Professional Documents
Culture Documents
Unit-2 1
Unit-2 1
Unit-2 1
UNIT-2
The table name and column names are helpful to interpret the meaning of values in each row.
The data are represented as a set of relations. In the relational model, data are stored as tables.
However, the physical storage of the data is independent of the way the data are logically
organized.
UNIT-2 Page 1
KIT Ajeet Singh
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation
key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain
There are many types of integrity constraints. Constraints on the Relational database
management system is mostly divided into three main categories are:
1. Domain constraints
2. Key constraints
UNIT-2 Page 2
KIT Ajeet Singh
4 Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the corresponding
domain or it is not of the appropriate data type.
Domain constraints specify that within each tuple, and the value of each attribute must be
unique. This is specified as data types which include standard data types integers, real numbers,
characters, Booleans, variable length strings, etc.
Example:
The example shown demonstrates creating a domain constraint such that CustomerName is not
NULL
5 Key constraints
An attribute that can uniquely identify a tuple in a relation is called the key of the table. The
value of the attribute for different tuples in the relation has to be unique.
Example:
In the given table, CustomerID is a key attribute of Customer Table. It is most likely to have a
single key for one customer, CustomerID =1 is only for the CustomerName =" Google".
1 Google Active
2 Amazon Active
UNIT-2 Page 3
KIT Ajeet Singh
3 Apple Inactive
Example:
UNIT-2 Page 4
KIT Ajeet Singh
● Modify allows you to change the values of some attributes in existing tuples.
Whenever one of these operations are applied, integrity constraints specified on the relational
database schema must never be violated.
The insert operation gives values of the attribute for a new tuple which should be inserted into a
relation.
You can see that in the below-given relation table CustomerName= 'Apple' is updated from
Inactive to Active.
UNIT-2 Page 5
KIT Ajeet Singh
To specify deletion, a condition on the attributes of the relation selects the tuple to be deleted.
The Delete operation could violate referential integrity if the tuple which is deleted is referenced
by foreign keys from other tuples in the same database.
UNIT-2 Page 6
KIT Ajeet Singh
● Simplicity: A relational data model is simpler than the hierarchical and network model.
● Structural Independence: The relational database is only concerned with data and not
with a structure. This can improve the performance of the model.
● Easy to use: The relational model is easy as tables consisting of rows and columns is
quite natural and simple to understand
● Query capability: It makes possible for a high-level query language like SQL to avoid
complex database navigation.
● Scalable: Regarding a number of records, or rows, and the number of fields, a database
● Few relational databases have limits on field lengths which can't be exceeded.
● Relational databases can sometimes become complex as the amount of data grows, and
the relations between pieces of data become more complicated.
● Complex relational database systems may lead to isolated databases where the
information cannot be shared from one system to another.
11 Summary
● The Relational database model represents the database as a collection of relations (tables)
UNIT-2 Page 7
KIT Ajeet Singh
● Relational Integrity constraints are referred to conditions which must be present for a
valid relation
● Insert, Select, Modify and Delete are operations performed in Relational Model
● The relational database is only concerned with data and not with a structure which can
improve the performance of the model
● Few relational databases have limits on field lengths which can't be exceeded.
12 Relational Algebra
RELATIONAL ALGEBRA is a widely used procedural query language. It collects instances of
relations as input and gives occurrences of relations as output. It uses various operations to
perform this action. Relational algebra operations are performed recursively on a relation. The
output of these operations is a new relation, which might be formed from one or more input
relations.
● SELECT (symbol: σ)
● PROJECT (symbol: π)
● RENAME (symbol: )
UNIT-2 Page 8
KIT Ajeet Singh
● UNION (υ)
● INTERSECTION ( ),
● DIFFERENCE (-)
● CARTESIAN PRODUCT ( x )
● JOIN
● DIVISION
SELECT (σ)
The SELECT operation is used for selecting a subset of the tuples according to a given selection
condition. Sigma(σ)Symbol denotes it. It is used as an expression to choose tuples which meet
the selection condition. Select operation selects tuples that satisfy a given predicate.
σp(r)
σ is the predicate
p is prepositional logic
Example 1
Example 2
Output - Selects tuples from Tutorials where the topic is 'Database' and 'author' is guru99.
UNIT-2 Page 9
KIT Ajeet Singh
Example 3
Output - Selects tuples from Customers where sales is greater than 50000
Projection(π)
The projection eliminates all attributes of the input relation but those mentioned in the projection
list. The projection method defines a relation that contains a vertical subset of Relation.
This helps to extract the values of specified attributes to eliminates duplicate values. (pi) The
symbol used to choose attributes from a relation. This operation helps you to keep specific
columns from a relation and discards the other columns.
Example of Projection:
1 Google Active
2 Amazon Active
3 Apple Inactive
4 Alibaba Active
CustomerName Status
UNIT-2 Page 10
KIT Ajeet Singh
Google Active
Amazon Active
Apple Inactive
Alibaba Active
UNION is symbolized by ∪ symbol. It includes all tuples that are in tables A or in B. It also
eliminates duplicate tuples. So, set A UNION set B would be expressed as:
Example
Table A Table B
1 1 1 1
UNIT-2 Page 11
KIT Ajeet Singh
1 2 1 3
A ∪ B gives
Table A ∪ B
column 1 column 2
1 1
1 2
1 3
Symbol denotes it. The result of A - B, is a relation which includes all tuples that are in A
but not in B.
● It should be defined relation consisting of the tuples that are in relation A, but not in B.
Example
A-B
Table A – B
column 1 column 2
UNIT-2 Page 12
KIT Ajeet Singh
1 2
Intersection
A B
Defines a relation consisting of a set of all tuple that are in both A and B. However, A and B
must be union-compatible.
Fig No 7 Intersection
Example:
A B
Table A B
column 1 column 2
1 1
UNIT-2 Page 13
KIT Ajeet Singh
Cartesian product(X)
This type of operation is helpful to merge columns from two relations. Generally, a Cartesian
product is never a meaningful operation when it performs alone. However, it becomes
meaningful when it is followed by other operations.
σ column 2 = '1' (A X B)
Output – The above example shows all rows from relation A and B whose column 2 has value 1
σ column 2 = '1' (A X B)
column 1 column 2
1 1
1 1
Join Operations
JOIN operation also allows joining variously related tuples from different relations.
Types of JOIN:
Inner Joins:
UNIT-2 Page 14
KIT Ajeet Singh
● Theta join
● EQUI join
● Natural join
Outer join:
Inner Join:
In an inner join, only those tuples that satisfy the matching criteria are included, while the rest
are excluded. Let's study various types of Inner Joins:
Theta Join:
The general case of JOIN operation is called a Theta join. It is denoted by symbol θ
Example
A ⋈θ B
For example:
column 1 column 2
UNIT-2 Page 15
KIT Ajeet Singh
1 2
EQUI join:
When a theta join uses only equivalence condition, it becomes a equi join.
For example:
column 1 column 2
1 1
EQUI join is the most difficult operations to implement efficiently in an RDBMS and one reason
why RDBMS have essential performance problems.
Natural join can only be performed if there is a common attribute (column) between the
relations. The name and type of the attribute must be same.
Example
Num Square
UNIT-2 Page 16
KIT Ajeet Singh
2 4
3 9
Num Cube
2 8
3 27
C⋈D
C D
2 4 4
3 9 27
OUTER JOIN
In an outer join, along with tuples that satisfy the matching criteria, we also include some or all
tuples that do not match the criteria.
UNIT-2 Page 17
KIT Ajeet Singh
In the left outer join, operation allows keeping all tuple in the left relation. However, if there is
no matching tuple is found in right relation, then the attributes of right relation in the join result
are filled with null values.
Num Square
2 4
3 9
4 16
UNIT-2 Page 18
KIT Ajeet Singh
Num Cube
2 8
3 18
5 75
A B
A⋈B
2 4 4
3 9 9
4 16 -
In the right outer join, operation allows keeping all tuple in the right relation. However, if there is
no matching tuple is found in the left relation, then the attributes of the left relation in the join
result are filled with null values.
UNIT-2 Page 19
KIT Ajeet Singh
A B
A B
2 8 4
3 18 9
5 75 -
In a full outer join, all tuples from both relations are included in the result, irrespective of the
matching condition.
A B
A B
2 4 8
3 9 18
4 16 -
5 - 75
UNIT-2 Page 20
KIT Ajeet Singh
Summary
Operation Purpose
UNIT-2 Page 21
KIT Ajeet Singh
Full Outer Join( ) In a full outer join, all tuples from both
relations are included in the result
irrespective of the matching condition.
13 Relational Calculus
o Relational calculus is a non-procedural query language. In the non-procedural query language, the
user is concerned with the details of how to obtain the end results.
o The relational calculus tells what to do but never explains how to do.
Notation:
UNIT-2 Page 22
KIT Ajeet Singh
Where
For example:
OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).
For example:
Output: This query will yield the same result as the previous one.
o It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.
Notation:
UNIT-2 Page 23
KIT Ajeet Singh
Where
For example:
Output: This query will yield the article, page, and subject from the relational javatpoint, where
the subject is a database.
14 Introduction on SQL
14.1 SQL
o SQL stands for Structured Query Language. It is used for storing and managing data in
relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read,
update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.
14.2 Rules:
o Structure query language is not case sensitive. Generally, keywords of SQL are written in
uppercase.
UNIT-2 Page 24
KIT Ajeet Singh
o Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database.
UNIT-2 Page 25
KIT Ajeet Singh
o SQL is used to define the data in the database and manipulate it when needed.
16 Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records
from a database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
Well defined standards
Long established are used by the SQL databases that are being used by ISO and ANSI.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.
Multiple data view
Using the SQL language, the users can make different views of the database structure.
17 SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
UNIT-2 Page 26
KIT Ajeet Singh
Binary Datatypes
There are Three types of binary Datatypes which are given below:
Binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
UNIT-2 Page 27
KIT Ajeet Singh
Datatype Description
Timestamp It stores the year, month, day, hour, minute, and the second value.
18 SQL Commands
UNIT-2 Page 28
KIT Ajeet Singh
o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
UNIT-2 Page 29
KIT Ajeet Singh
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
Example:
DROP: It is used to delete both the structure and record stored in the table.
Syntax
DROP TABLE ;
Example
ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
UNIT-2 Page 30
KIT Ajeet Singh
EXAMPLE
TRUNCATE: It is used to delete all the rows from the table and free the space containing the
table.
Syntax:
Example:
o INSERT
o UPDATE
o DELETE
INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
UNIT-2 Page 31
KIT Ajeet Singh
Syntax:
Or
For example:
UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'
Syntax:
For example:
UNIT-2 Page 32
KIT Ajeet Singh
DCL commands are used to grant and take back authority from any database user.
o Grant
o Revoke
Example
Example
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
Commit: Commit command is used to save all the transactions to the database.
Syntax:
UNIT-2 Page 33
KIT Ajeet Singh
COMMIT;
Example:
Rollback: Rollback command is used to undo transactions that have not already been saved to
the database.
Syntax:
ROLLBACK;
Example:
SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
o SELECT
UNIT-2 Page 34
KIT Ajeet Singh
SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.
Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;
For example:
SELECT emp_name
FROM employee
WHERE age > 20;
19 SQL Operator
There are various types of SQL operator:
UNIT-2 Page 35
KIT Ajeet Singh
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
- It is used to subtract the right-hand operand from the a-b will give 10
left-hand operand.
* It is used to multiply the value of both operands. a*b will give 200
UNIT-2 Page 36
KIT Ajeet Singh
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
= It checks if two operands values are equal or not, if the (a=b) is not true
values are queal then condition becomes true.
!= It checks if two operands values are equal or not, if values (a!=b) is true
are not equal, then condition becomes true.
<> It checks if two operands values are equal or not, if values (a<>b) is true
are not equal then condition becomes true.
> It checks if the left operand value is greater than right (a>b) is not true
operand value, if yes then condition becomes true.
< It checks if the left operand value is less than right operand (a<b) is true
value, if yes then condition becomes true.
>= It checks if the left operand value is greater than or equal to (a>=b) is not true
the right operand value, if yes then condition becomes true.
<= It checks if the left operand value is less than or equal to the (a<=b) is true
right operand value, if yes then condition becomes true.
!< It checks if the left operand value is not less than the right (a!=b) is not true
operand value, if yes then condition becomes true.
!> It checks if the left operand value is not greater than the (a!>b) is true
right operand value, if yes then condition becomes true.
Operator Description
UNIT-2 Page 37
KIT Ajeet Singh
BETWEEN It is used to search for values that are within a set of values.
20 SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns. In
DBMS, the table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient
representation of relations.
UNIT-2 Page 38
KIT Ajeet Singh
In the above table, "EMPLOYEE" is the table name, "EMP_ID", "EMP_NAME", "CITY",
"PHONE_NO" are the column names. The combination of data of multiple columns forms a
row, e.g., 1, "Kristen", "Washington" and 7289201223 are the data of one row.
SQL create table is used to create a table in the database. To define the table, you should define
the name of the table and also define its columns and column's data type.
Syntax
Example
UNIT-2 Page 39
KIT Ajeet Singh
If you create the table successfully, you can verify the table by looking at the message by the
SQL server. Else you can use DESC command as follows:
Now you have an EMPLOYEE table in the database, and you can use the stored information
related to the employees.
Drop table
A SQL drop table is used to delete a table definition and all the data from a table. When this
command is executed, all the information available in the table is lost forever, so you have to
very careful while using this command.
Syntax
Firstly, you need to verify the EMPLOYEE table using the following command:
UNIT-2 Page 40
KIT Ajeet Singh
This table shows that EMPLOYEE table is available in the database, so we can drop it as
follows:
Now, we can check whether the table exists or not using the following command:
In SQL, DELETE statement is used to delete rows from a table. We can use WHERE condition
to delete a specific row from a table. If you want to delete all the records from the table, then you
don't need to use the WHERE clause.
Syntax
Example
UNIT-2 Page 41
KIT Ajeet Singh
If you don't specify the WHERE condition, it will remove all the rows from the table.
UNIT-2 Page 42
KIT Ajeet Singh
Syntax
Here, the expression is the field name of the table that you want to select data from.
Use the following syntax to select all the fields available in the table:
Example:
EMPLOYEE
To fetch the EMP_ID of all the employees, use the following query:
Output
EMP_ID
UNIT-2 Page 43
KIT Ajeet Singh
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000
To fetch all the fields from the EMPLOYEE table, use the following query:
Output
UNIT-2 Page 44
KIT Ajeet Singh
Sample Table
EMPLOYEE
If you want to specify all column values, you can specify or ignore the column values.
Syntax
Query
Output: After executing this query, the EMPLOYEE table will look like:
UNIT-2 Page 45
KIT Ajeet Singh
To insert partial column values, you must have to specify the column names.
Syntax
Query
INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40);
Output: After executing this query, the table will look like:
UNIT-2 Page 46
KIT Ajeet Singh
Note: In SQL INSERT query, if you add values for all columns then there is no need to
specify the column name. But, you must be sure that you are entering the values in the
same order as the column exists.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Sample Table
EMPLOYEE
UNIT-2 Page 47
KIT Ajeet Singh
Update the column EMP_NAME and set the value to 'Emma' in the row where SALARY is
500000.
Syntax
UPDATE table_name
SET column_name = value
WHERE condition;
Query
UPDATE EMPLOYEE
SET EMP_NAME = 'Emma'
WHERE SALARY = 500000;
Output: After executing this query, the EMPLOYEE table will look like:
If you want to update multiple columns, you should separate each field assigned with a comma.
In the EMPLOYEE table, update the column EMP_NAME to 'Kevin' and CITY to 'Boston'
where EMP_ID is 5.
UNIT-2 Page 48
KIT Ajeet Singh
Syntax
UPDATE table_name
SET column_name = value1, column_name2 = value2
WHERE condition;
Query
UPDATE EMPLOYEE
SET EMP_NAME = 'Kevin', City = 'Boston'
WHERE EMP_ID = 5;
Output
If you want to update all row from a table, then you don't need to use the WHERE clause. In the
EMPLOYEE table, update the column EMP_NAME as 'Harry'.
Syntax
UPDATE table_name
SET column_name = value1;
UNIT-2 Page 49
KIT Ajeet Singh
Query
UPDATE EMPLOYEE
SET EMP_NAME = 'Harry';
Output
The SQL DELETE statement is used to delete rows from a table. Generally, DELETE statement
removes one or more records form a table.
Syntax
Sample Table
EMPLOYEE
UNIT-2 Page 50
KIT Ajeet Singh
Delete the row from the table EMPLOYEE where EMP_NAME = 'Kristen'. This will delete only
the fourth row.
Query
Output: After executing this query, the EMPLOYEE table will look like:
Delete the row from the EMPLOYEE table where AGE is 30. This will delete two rows(first and
third row).
UNIT-2 Page 51
KIT Ajeet Singh
Query
Output: After executing this query, the EMPLOYEE table will look like:
Delete all the row from the EMPLOYEE table. After this, no records left to display. The
EMPLOYEE table will become empty.
Syntax
Query
Output: After executing this query, the EMPLOYEE table will look like:
UNIT-2 Page 52
KIT Ajeet Singh
25 Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
UNIT-2 Page 53
KIT Ajeet Singh
Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.
Syntax:
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
UNIT-2 Page 54
KIT Ajeet Singh
View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
Deleting View
Syntax
UNIT-2 Page 55
KIT Ajeet Singh
Example:
26 SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very fast.
o An Index is used to speed up select queries and where clauses. But it shows down the
data input with insert and update statements. Indexes can be created or dropped without
affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic, you
first have to refer to the index, which alphabetically lists all the topics and then referred
to one or more specific page numbers.
Syntax
Example
It is used to create a unique index on a table. It does not allow duplicate value.
UNIT-2 Page 56
KIT Ajeet Singh
Syntax
Example
Syntax
Example
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query,
and the inner query is known as a subquery.
UNIT-2 Page 57
KIT Ajeet Singh
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can
be used to perform the same function as ORDER BY command.
SQL subqueries are most frequently used with the Select statement.
Syntax
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
UNIT-2 Page 58
KIT Ajeet Singh
SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
Syntax:
Example
UNIT-2 Page 59
KIT Ajeet Singh
Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.
The subquery of SQL can be used in conjunction with the Update statement. When a subquery is
used with the Update statement, then either single or multiple columns in a table can be updated.
Syntax
UPDATE table
SET column_name = new_value
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);
Example
UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
UNIT-2 Page 60
KIT Ajeet Singh
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
The subquery of SQL can be used in conjunction with the Delete statement just like any other
statements mentioned above.
Syntax
Example
UNIT-2 Page 61
KIT Ajeet Singh
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
1 John 20 US 2000.00
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work on
UNIT-2 Page 62
KIT Ajeet Singh
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
UNIT-2 Page 63
KIT Ajeet Singh
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:
10
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
UNIT-2 Page 64
KIT Ajeet Singh
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670
UNIT-2 Page 65
KIT Ajeet Singh
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output:
320
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
UNIT-2 Page 66
KIT Ajeet Singh
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax
AVG()
or
AVG( [ALL|DISTINCT] expression )
Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.
Syntax
MAX()
or
MAX( [ALL|DISTINCT] expression )
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
UNIT-2 Page 67
KIT Ajeet Singh
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.
Syntax
MIN()
or
MIN( [ALL|DISTINCT] expression )
Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
29 SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
UNIT-2 Page 68
KIT Ajeet Singh
4. FULL JOIN
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
UNIT-2 Page 69
KIT Ajeet Singh
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
UNIT-2 Page 70
KIT Ajeet Singh
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
UNIT-2 Page 71
KIT Ajeet Singh
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
UNIT-2 Page 72
KIT Ajeet Singh
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
UNIT-2 Page 73
KIT Ajeet Singh
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both the
tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
UNIT-2 Page 75
KIT Ajeet Singh
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
UNIT-2 Page 76
KIT Ajeet Singh
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
Syntax
Example:
UNIT-2 Page 77
KIT Ajeet Singh
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
ID NAME
1 Jack
UNIT-2 Page 78
KIT Ajeet Singh
2 Harry
31 Cursors in PL/SQL
31.1Cursor in SQL
To execute SQL statements, a work area is used by the Oracle engine for its internal processing
and storing the information. This work area is private to SQL’s operations. The ‘Cursor’ is the
PL/SQL construct that allows the user to name the work area and access the stored information
in it.
UNIT-2 Page 79
KIT Ajeet Singh
● Implicit Cursor: If the Oracle engine opened a cursor for its internal processing it is
known as an Implicit Cursor. It is created “automatically” for the user by Oracle when a
query is executed and is simpler to code.
● Explicit Cursor: A Cursor can also be opened for processing data through a PL/SQL
block, on demand. Such a user-defined cursor is known as an Explicit Cursor.
31.4.1 Explicit cursor
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row. A suitable name for the cursor.
General syntax for creating a cursor:
UNIT-2 Page 80
KIT Ajeet Singh
3. FETCH the data from the cursor into PL/SQL variables or records in the Execution
Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
Syntax:
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
CLOSE cursor;
END;
[before | after]
on [table_name]
[trigger_body]
UNIT-2 Page 81
KIT Ajeet Singh
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the
trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
+-------+-------------+------+-----+---------+----------------+
+-------+-------------+------+-----+---------+----------------+
UNIT-2 Page 82
KIT Ajeet Singh
+-------+-------------+------+-----+---------+----------------+
before INSERT
on
Student
Above SQL statement will create a trigger in the student database in which whenever subjects
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.,
mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
+-----+-------+-------+-------+-------+-------+------+
+-----+-------+-------+-------+-------+-------+------+
| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |
+-----+-------+-------+-------+-------+-------+------+
UNIT-2 Page 83
KIT Ajeet Singh
33.1 Advantages:
● They reduce the traffic between the database and the application, since the lengthy
statements are already fed into the database and need not be sent again and again
via the application.
● They add to code reusability, similar to how functions and methods work in other
33.2 Disadvantages:
● Stored procedures can cause a lot of memory usage. The database administrator
should decide an upper bound as to how many stored procedures are feasible for a
particular application.
● MySQL does not provide the functionality of debugging the stored procedures.
UNIT-2 Page 84
KIT Ajeet Singh
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments --
AS
BEGIN
-- Query --
END
GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
UNIT-2 Page 85
KIT Ajeet Singh
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments --
AS
BEGIN
-- Query --
END
GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
UNIT-2 Page 86
KIT Ajeet Singh
Example:
DROP PROCEDURE GetStudentDetails
UNIT-2 Page 87