DBMS Lab Manual 2024
DBMS Lab Manual 2024
LAB MANUAL
OF
DATABASE MANAGEMENT SYSTEMS
II B.TECH II Semester
(HITS – R22)
Prepared By:
Mr. A . GOPI
Assistant Professor
DEPARTMENT OF CSE
(ARTIFICIAL INTELLIGENCE & MACHINE LEARNING)
COURSE OBJECTIVES:
The course should enable the students to learn:
1. Discuss the basic database concepts, applications, data models, schemas and instances.
2. Design Entity Relationship model for a database.
3. Demonstrate the use of constraints and relational algebra operations.
4. Describe the basics of SQL and construct queries using SQL
5. Understand the importance of normalization in databases.
COURSE OUTCOMES:
At the end of the course the students are able to:
1. Use the basic concepts of Database Systems in Database design
2. Design a Database using ER Modeling
3. Apply normalization on database design to eliminate anomalies
4. Apply SQL queries and PL/SQL queries to interact with Database
5. Analyze database transactions and can control them by applying ACID properties.
1 WEEK -1 12
DDL Commands
Creation of Tables using SQL- Overview of using SQL tool and Data types in SQL
Altering Tables and
Dropping Tables
2 WEEK -2 13
Create Table with Primary key and Foreign Key& DML Commands
Creating Tables (along with Primary and Foreign keys), Practicing DML commands-
Insert,
Update
Delete.
3 WEEK -3 14
Selection Queries
Practicing Select command using following operations
AND, OR
ORDER BY
BETWEEN
LIKE
Apply CHECK constraint
4 WEEK -4 20
Aggregate Functions and Views
Practice Queries using following functions
COUNT,
SUM,
AVG,
MAX,
MIN,
Apply constraint on aggregation using
GROUP BY,
HAVING,VIEWS Create, Modify and Drop
5 WEEK -5 21
Nested Queries
Practicing Nested Queries using
UNION,
INTERSECT,
CONSTRAINTS
IN
6 WEEK -6 22
Co- Related Nested Queries
Practicing Co – Related Nested Queries using
EXISTS
,NOT EXISTS. ANY, ALL
7 WEEK -7 24
Join Queries
Practicing Join Queries using
Inner join
Outer join
Equi join
Natural join
8 WEEK -8 25
Triggers
Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using
trigger, Updating using trigger.
9 WEEK -9 32
Procedures
Procedures- Creation of Stored Procedures, Execution of Procedure, and Modification
of Procedure.
10 WEEK -10
Cursors
Cursors- Declaring Cursor, Opening Cursor, Fetching the data, closing the cursor.
11 WEEK -11
PL/SQL Part 1
Practice PL/SQL –
block structure,
variables,
data types,
12 WEEK -12
PL/SQL Part 2
Practice PL/SQL –
operators,
control structures;
aseca
To bring out creativity in students that would promote innovation, research and
entrepreneurship.
To preserve and promote cultural heritage, humanistic and spiritual values promoting
peace and harmony in society.
PEO-II: To provide graduates with analytical and problem solving skills to design
algorithms, other hardware/ software systems, and inculcate professional ethics,
interpersonal skills to work in a multi-cultural team.
PEO-III: To facilitate graduates get familiarized with state of the art software/hardware
tools, imbibing creativity and innovation that would enable them to develop cutting-edge
technologies of multi-disciplinary nature for societal development.
PROGRAM OUTCOMES (POs): Program Outcomes (POs) describe what students are
expected to know and be able to do by the time of graduation to accomplish Program
Educational Objectives (PEOs). The Program Outcomes for Computer Science and
Engineering graduates are: Engineering Graduates would be able to:
PO 1:Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
PO 2: Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO 3:Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations.
PO 4: Conduct investigations of complex problems: Use research-based knowledge
and research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
PO 5:Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO 6:The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO 7:Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO 8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO 9:Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
PO 10: Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
PO 11:Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.
PO 12: Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
PROGRAM SPECIFIC OUTCOMES (PSOs):
PSO 1: To identify and define the computing requirements appropriate for its solution
under given constraints.
PSO 2: To follow the best practices, namely, SEI-CMM levels and 6-sigma which varies
from time to time for software development projects using open-ended programming
environments to produce software deliverables as per customer needs.
Lab Course Objectives
After the completion of the “Machine Learning” lab, the student can able to:
understand complexity of Machine Learning algorithms and their limitations;
understand modern notions in data analysis oriented computing;
be capable of confidently applying common Machine Learning algorithms in
practice and implementing their own;
Be capable of performing experiments in Machine Learning using real-world data.
Course
S.N Componen PEO 1 PEO 2 PEO 3
o t Code Course Semester
Profession
al
A1AM407P
1 1 2
1 Course C DBMS II
POs P P P P P P P P P P P P
O O O O O O O O O O O O
1 2 3 4 5 6 7 8 9 1 1 1
0 1 2
Database Management Systems
EXP
NO.
1to 3 2 2 3 - - 3 - - - - 2
Discuss the basic database concepts, 12
applications, data models, schemas and
instances.
3,4 2 2 3 2 2 - 3 - 3 3 1 2
Design Entity Relationship model for a
database.
5,6 2 3 3 3 2 2 2 2 3 3 3 3
Demonstrate the use of constraints and
relational algebra operations.
8,5,10, 2 1 3 1 2 - 3 3 - 2 - 3
Describe the basics of SQL and construct 11,12,
queries using SQL. 9
Understand the importance of normalization in
databases.
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to laboratory at least 5 minutes before (to the
starting time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepare to the
lab with Synopsis/ program/experiment details.
3. Students should enter into the laboratory with :
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedures, program, Expected output ,etc) filled in for lab session.
b. Laboratory record updated up to the last session experiments and other
utensils(if any) needed in the lab.
4. Sign in the laboratory log in register, write the TIME-IN ,and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results /output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staffs must
maintained the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems
which should be utilized properly.
8. Students / faculty must keep their mobile phones in SWITCHED OFF mode during
the lab sessions. Miss use of equipment, miss behaviors with the staff and
system etc,. will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to out ; if
any body found loitering outside the lab /class without permission during the
work hours will be treated seriously and punish appropriately .
10. Student should LOGOFF / SHUTDOWN the computer systems before he/she
leaves the lab after completing the task (experiment) in all aspects. He/ She
must ensure the system/ seat is kept properly.
PROGRAM:
Creation of Tables using SQL- Overview of using SQL tool and Data types in SQL
Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check the complete details at Create
Table Using another Table.
Example
The following code block is an example, which creates a CUSTOMERS table with an ID
as a primary key and NOT NULL are the constraints showing that these fields cannot be
NULL while creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the message
displayed by the SQL server, otherwise you can use the DESC command as follows −
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Now, you have CUSTOMERS table available in your database which you can use to store
the required information related to customers.
Altering Tables and
The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table. You should also use the ALTER TABLE command to add and drop various
constraints on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New Column in an existing
table is as follows.
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table
is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column
in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a
column in a table is as follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table
is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a
table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is
as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP INDEX MyUniqueConstraint;
The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint
from a table is as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyPrimaryKey;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP PRIMARY KEY;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example to ADD a New Column to an existing table −
ALTER TABLE CUSTOMERS ADD SEX char(1);
Now, the CUSTOMERS table is changed and following would be output from the SELECT
statement.
+----+---------+-----+-----------+----------+------+
| ID | NAME | AGE | ADDRESS | SALARY | SEX |
+----+---------+-----+-----------+----------+------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |
| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |
| 3 | kaushik | 23 | Kota | 2000.00 | NULL |
| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |
| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |
| 6 | Komal | 22 | MP | 4500.00 | NULL |
| 7 | Muffy | 24 | Indore | 10000.00 | NULL |
+----+---------+-----+-----------+----------+------+
Following is the example to DROP sex column from the existing table.
ALTER TABLE CUSTOMERS DROP SEX;
Now, the CUSTOMERS table is changed and following would be the output from the
SELECT statement.
+----+---------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+---------+-----+-----------+----------+
Dropping Tables
The SQL DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints and permission specifications for that table.
NOTE − You should be very careful while using this command because once a table is
deleted then all the information available in that table will also be lost forever.
Syntax
The basic syntax of this DROP TABLE statement is as follows −
DROP TABLE table_name;
Example
Let us first verify the CUSTOMERS table and then we will delete it from the database as
shown below −
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
This means that the CUSTOMERS table is available in the database, so let us now drop
it as shown below.
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try the DESC command, then you will get the following error −
SQL> DESC CUSTOMERS;
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
Here, TEST is the database name which we are using for our examples.
Viva Questions
1. Define SQL?
2. What is DDL ?
PROGRAM:
If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:
This SQL statement displays the following values of the student table:
BCA1001 Abhay 85
BCA1002 Anuj 75
BCA1003 Bheem 60
BCA1004 Ram 79
BCA1005 Sumit 80
Example 2: This example shows all the values of a specific column from the table.
This SELECT statement displays all the values of Emp_Salary and Emp_Id column
of Employee table:
Emp_Id Emp_Salary
201 25000
202 45000
203 30000
204 29000
205 40000
Example 3: This example describes how to use the WHERE clause with the SELECT
DML command.
BCA1001 Abhay 80
BCA1002 Ankit 75
BCA1003 Bheem 80
BCA1004 Ram 79
BCA1005 Sumit 80
If you want to access all the records of those students whose marks is 80 from the
above table, then you have to write the following DML command in SQL:
BCA1001 Abhay 80
BCA1003 Bheem 80
BCA1005 Sumit 80
Let's take the following student table, which consists of only 2 records of the student.
101 Ramesh 92 20
201 Jatin 83 19
Suppose, you want to insert a new record into the student table. For this, you have to
write the following DML INSERT command:
1. INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, Anmol, 89, 19);
UPDATE DML Command
UPDATE is another most important data manipulation command in Structured Query
Language, which allows users to update or modify the existing data in database tables.
Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the name
of the table whose values you want to update.
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
Suppose, you want to update the Product_Price of the product whose Product_Id is
P102. To do this, you have to write the following DML UPDATE command:
Example 2: This example describes how to update the value of multiple fields of the
database table.
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
Suppose, you want to update Stu_Marks and Stu_Age of that student whose Stu_Id is
103 and 202. To do this, you have to write the following DML Update command:
1. UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id = 103 AND Stu_Id = 202;
This command of Data Manipulation Language does not delete the stored data
permanently from the database. We use the WHERE clause with the DELETE command
to select specific rows from the table.
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
Suppose, you want to delete that product from the Product table whose Product_Id is
P203. To do this, you have to write the following DML DELETE command:
Example 2: This example describes how to delete the multiple records or rows from
the database table.
101 Ramesh 92 20
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
Suppose, you want to delete the record of those students whose Marks is greater than
70. To do this, you have to write the following DML Update command:
2. ?
3. Define dataset?
WEEK -3
AIM:
Selection Queries
Practicing Select command using following operations
AND, OR
ORDER BY
BETWEEN
LIKE
Apply CHECK constraint
PROGRAM:
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Demo Database
The table below shows the complete "Customers" table from the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 0543
AND Example
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is
"Germany" OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form complex
expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
Example
SELECT * FROM Customers
ORDER BY Country DESC;
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark
(?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in
any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r" in
the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts with
"a" and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that starts with "a"
and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does NOT
start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
If you define a CHECK constraint on a column it will allow only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.
MySQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
MySQL:
Viva Questions:
WEEK -4
AIM
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails"
table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
GROUP BY With JOIN Example
The following SQL statement lists the number of orders sent by each shipper:
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country, sorted high to
low (Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
The following SQL statement lists if the employees "Davolio" or "Fuller" have registered
more than 25 orders:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
Test
Viva Questions:
WEEK -5
AIM
Nested Queries
Practicing Nested Queries using
UNION,
INTERSECT,
CONSTRAINTS
IN
Program:
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104
Note: If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SQL UNION With WHERE
The following SQL statement returns the German cities (only distinct values) from both the
"Customers" and the "Suppliers" table:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a
temporary name. An alias only exists for the duration of the query. So, here we have created
a temporary column named "Type", that list whether the contact person is a "Customer" or a
"Supplier".
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database
The table below shows the complete "Customers" table from the Northwind sample
database:
Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexic
helados 2222 D.F.
Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexic
D.F.
Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the
suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
Viva Questions:
WEEK -6
AIM
Program:
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 New Orleans Cajun Shelley Burke P.O. Box 78934 New 70117
Delights Orleans
3 Grandma Kelly's Regina Murphy 707 Oxford Rd. Ann Arbor 48104
Homestead
The following SQL statement returns TRUE and lists the suppliers with a product price equal
to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);
ANY means that the condition will be true if the operation is true for any of the values in the
range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
The SQL ALL Operator
The ALL operator:
ALL means that the condition will be true only if the operation is true for all values in the
range.
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles
3 Aniseed Syrup 1 2 12 - 550 ml bottles
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
7 10250 51 35
8 10250 65 15
9 10251 22 6
10 10251 57 15
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 99 (this will return TRUE because the Quantity
column has some values larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 1000 (this will return FALSE because the
Quantity column has no values larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
Viva Questions:
WEEK -7
AIM
Join Queries
Practicing Join Queries using
Inner join
Outer join
Equi join
Natural join
Program:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID"
column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that
selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
(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.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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!
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);
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if
there are no matches in the left table (Orders).
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Note: FULL OUTER JOIN can potentially return very large result-sets!
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
CustomerName OrderID
Null 10309
Null 10310
Demo Database
In this tutorial we will use the well-known Northwind sample database.
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;
Viva Questions:
WEEK -8
AIM
Triggers
Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using trigger, Updating using
trigger.
Program:
One of the most used scenarios for triggers is to maintain a log of changes in a given
table. In such case, there is no point on having three different triggers, each one firing
on INSERT, UPDATE and DELETE operations. Fortunately we have the chance to use
one single trigger for all of those operations. The only drawback is that you have to add
logic to know what event fired the trigger. With a bit of ingenuity and using the
INSERTED and DELETED pseudo tables we can know the type of operation that fired the
trigger by comparing the number of rows of each pseudo table.
To give you an example, suppose the INSERTED pseudo table contains rows and the
DELETED pseudo table is empty then we know that the event that fired the trigger was
an INSERT statement. In opposition, if the DELETED pseudo table has rows and the
INSERTED pseudo table is empty then the statement that fired the trigger was a DELETE.
But if both INSERTED and DELETED have rows then the statement that fired the trigger
was an UPDATE.
Now on the code section below you will see a simple trigger that has the logic to
determine which statement was responsible for firing the trigger and prints the
statement type.
UPDATE dbo.NestingTest
SET Test = 1
WHERE NestingTestID = 1;
Types of Triggers
SQL Server has three types of triggers:
DML Triggers allow us to execute code in response to data modification. In other words,
they allow us to run additional code in response of the execution of an insert, update or
delete statement.
DDL Triggers give us the possibility to execute code in response of changes in the
structure of a database, like dropping or creating a table; or a server event like when
someone logs in. DDL Triggers can be split into two different types according to where
they are scoped.
Logon Triggers are a particular case of Server Scoped DDL triggers that fire in response
to the LOGON event that's raised when a user's session is being established.
Additional Information
How to View Triggers in SQL Server Management Studio.
DML Triggers
This type of trigger is the most known and used by developers. As you may
already know, DML stands for Data Manipulation Language and refers to the SQL
instructions that changes data. Those instructions are INSERT, UPDATE and
DELETE. Basically, DML triggers can be defined as pieces of code written mostly
in Transact SQL language whose execution is not performed manually by the
user and instead is run automatically in response to DML events.
DML Triggers are associated to a table or view and to any of the DML events
(INSERT, UPDATE and DELETE). Something to remark is that a trigger can only be
associated with one single table or view, but can be associated to more than one
DML event. For instance, you could have a trigger that is associated with a table
that fires in response to INSERT and UPDATE events, we will see this further on
in the tutorial.
To create a trigger we need to use the CREATE TRIGGER statement.
In this code section you will see the basic CREATE TRIGGER syntax.
CREATE TRIGGER trigger_name
Additionally the next table describes each of the arguments of the CREATE
TRIGGER syntax.
Argument Description
Indicates when the trigger must fire. FOR or AFTER occurs after the insert,
FOR | AFTER | INSTEAD OF delete or update occurs. INSTEAD OF occurs instead of the insert, delete or
update operation from occurring.
[INSERT], [UPDATE], [DELETE] The DML event (or list of events) that will cause the trigger to fire.
GO
)
(
EmployeeName,
EmployeeAddress,
MonthSalary
)
VALUES
( 'Mark Smith',
'Ocean Dr 1234',
10000
),
( 'Joe Wright',
'Evergreen 1234',
10000
),
( 'John Doe',
'International Dr 1234',
10000
),
( 'Peter Rodriguez',
10000
);
In the code below you will see the most basic DML trigger we can make, which
will return "Hello World". This trigger will show a "Hello World!" line every time a
row is added to the Employees table.
USE [SampleDB]
GO
FOR INSERT
AS
In order to test this trigger we need to insert some data into the Employees table.
We can do so with the next script.
SELECT * FROM dbo.Employees
GO
GO
GO
On the next image you can see the execution of the previous script. Notice that
when the INSERT statement executes it prints a "Hello World!" message.
Viva Questions:
WEEK -9
AIM
Procedures
Procedures- Creation of Stored Procedures, Execution of Procedure, and Modification of Procedure
Program:
SQL Server builds an execution plan when the stored procedure is called the first time
and stores them in the cache memory. The plan is reused by SQL Server in subsequent
executions of the stored procedure, allowing it to run quickly and efficiently.
o Reduced Traffic: A stored procedure reduces network traffic between the application
and the database server, resulting in increased performance. It is because instead of
sending several SQL statements, the application only needs to send the name of the
stored procedure and its parameters.
o Stronger Security: The procedure is always secure because it manages which processes
and activities we can perform. It removes the need for permissions to be granted at the
database object level and simplifies the security layers.
o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents
unnecessary rewrites of the same code, and makes the code transparent to all
applications or users.
o Easy Maintenance: The procedures are easier to maintain without restarting or
deploying the application.
o Improved Performance: Stored Procedure increases the application performance. Once
we create the stored procedures and compile them the first time, it creates an execution
plan reused for subsequent executions. The procedure is usually processed quicker
because the query processor does not have to create a new plan.
o Types of Stored Procedures
o SQL Server categorizes the stored procedures mainly in two types:
o T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular types
of SQL Server procedures. It takes parameters and returns them. These procedures
handle INSERT, UPDATE, and DELETE statements with or without parameters and output
row data.
o CLR Stored Procedures: The SQL Server procedures are a group of SQL commands, and
the CLR indicates the common language runtime. CLR stored procedures are made up of
the CLR and a stored procedure, which is written in a CLR-based language like VB.NET or
C#. CLR procedures are .Net objects that run in the SQL Server database's memory.
Parameter Explanations
The stored procedure syntax has the following parameters:
1. EXEC procedure_name;
2. Or,
3. EXECUTE procedure_name;
If we are using the SSMS, we need to use the below steps to execute stored procedures:
We will take a student table to demonstrate the stored procedure examples. This table
has the following data:
The below example uses the CREATE PROCEDURE SQL statement for creating a stored
procedure that displays the student's list in the increasing order of a salary from the
STUDENT table in the selected database:
In this syntax, the studentList is the name of the stored procedure, and the AS keyword
distinguishes the stored procedure's heading and body. The BEGIN and END keywords
that accompany a single statement in a stored procedure are optional. However, it's a
good idea to include them to make the code more understandable.
When we run this statement, and everything is correct, the following message will
appear: "Commands completed successfully." It indicates that the stored procedure
was successfully compiled and saved to the database system.
1. EXEC studentList;
If we are using the SSMS, use the following steps for creating the stored procedure:
Step 2: Right-click on the Stored Procedures folder to open the menu and then select
the New -> Stored Procedure option as follows:
Step 3: When we select the New Stored Procedure option, we will get the new query
window containing the default Stored Procedure Template. Here, we can add the
procedure name, parameters (if any), and the SQL query we want to use.
Step 2: Expand the Stored Procedures folder, right-click on the stored procedure that
you want to modify, and then select the Modify option as follows:
Step 3: Once we click the Modify option, we will get a new query window with an
auto-generated ALTER PROCEDURE code. Here we can make changes as per our needs.
The best way for listing all user-defined stored procedures in a database is to use
the ROUTINES information schema view as below:
OR,
1. SELECT *
2. FROM db_name.INFORMATION_SCHEMA.ROUTINES
3. WHERE ROUTINE_TYPE = 'PROCEDURE'
Another way to return a list of stored procedures is to query the sys.objects system
catalog view.
1. SELECT
2. SCHEMA_NAME(schema_id) AS [Schema],
3. name
4. FROM sys.objects
5. WHERE type = 'P';
Step 2: Expand the Stored Procedures folder, right-click on the stored procedure that
you want to remove, and then select the Delete option as follows:
Step 3: Once we click the Delete option, we will get a Delete Object window. We can
check the dependencies by clicking on the Show Dependencies button and then click OK
to remove the stored procedure.
Delete Stored Procedures using T-SQL Query
SQL Server provides a DROP PROCEDURE statement to remove the existing stored
procedures. We can write the DROP PROCEDURE statement as follows:
NOTE: It's a good idea to use IF OBJECT ID ('procedure name', 'P') IS NOT NULL to see if the
stored procedure exists in the database.
If we want to execute this stored procedure, we need to pass the value for
the @States parameter. We can pass the parameter value in any of the following ways:
Let us understand how to use Output Parameters in a stored procedure with the help of
an example. The following statement will create a procedure called countStudent, in
which we will declare an integer type variable called @StudentCount and use
the OUTPUT keyword. The procedure uses the COUNT function to find the number of
students in the STUDENT table, and then the value is assigned to the output parameter.
Now, we will execute the stored procedure. Here, we need to pass the output
parameter @StudentaCouns as follows:
Local Temporary Stored Procedures: We can create this type of procedure by using the
# as prefix and accessed only in the session in which they were created. When the
connection is closed, this process is immediately terminated.
Global Temporary Stored Procedure: We can create this type of procedure by using the
## as a prefix and accessed from any sessions. When the connection that was used to
create the procedure is closed, this procedure is automatically terminated.
Viva Questions:
WEEK -10
AIM
Cursors
Cursors- Declaring Cursor, Opening Cursor, Fetching the data, closing the cursor.
Program:
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that
needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the
rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used
attributes −
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or
more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement
returned no rows. Otherwise, it returns FALSE.
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.
Example
We will be using the CUSTOMERS table we had created and used in the previous
chapters.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by
500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected
−
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Viva Questions:
WEEK -11
AIM
PL/SQL Part 1
Practice PL/SQL –
block structure,
variables,
data types,
Program:
In PL/SQL, the code is not executed in single line format, but it is always
executed by grouping the code into a single element called Blocks. In this
tutorial, you are going to learn about these blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instruction
will be executed as a whole rather than executing a single instruction at a time.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped.
Below are different sections of PL/SQL blocks.
1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section
order.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part.
This is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the
block will be declared. Below are few more characteristics of this part.
Execution Section
Execution part is the main and mandatory part which actually executes the
code that is written inside it. Since the PL/SQL expects the executable
statements from this block this cannot be an empty block, i.e., it should have
at least one valid executable code line in it. Below are few more
characteristics of this part.
This is the section where the exception raised in the execution block is
handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword ‘EXCEPTION’.
This section should always be followed by the keyword ‘END’.
DECLARE --optional
<declarations>
BEGIN --mandatory
<executable statements. At least one executable statement is mandatory>
EXCEPTION --optional
<exception handles>
END; --mandatory
/
Note: A block should always be followed by ‘/’ which sends the information to
the compiler about the end of the block.
1. Anonymous blocks
2. Named Blocks
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned
to them. They need to be created and used in the same session because they
will not be stored in the server as database objects.
Since they need not store in the database, they need no compilation steps.
They are written and executed directly, and compilation and execution happen
in a single process.
These blocks don’t have any reference name specified for them.
These blocks start with the keyword ‘DECLARE’ or ‘BEGIN’.
Since these blocks do not have any reference name, these cannot be
stored for later purpose. They shall be created and executed in the
same session.
They can call the other named blocks, but call to anonymous block is
not possible as it is not having any reference.
It can have nested block in it which can be named or anonymous. It can
also be nested in any blocks.
These blocks can have all three sections of the block, in which
execution section is mandatory, the other two sections are optional.
Named blocks:
Named blocks have a specific and unique name for them. They are stored as
the database objects in the server. Since they are available as database
objects, they can be referred to or used as long as it is present on the server.
The compilation process for named blocks happens separately while creating
them as a database objects.
1. Procedure
2. Function
We will learn more about these named blocks in “Procedure” and “Function”
topics in later tutorial.
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data
temporarily during the execution of code. It helps you to manipulate data in PL/SQL
programs. It is nothing except a name given to a storage area. Each variable in the
PL/SQL has a specific data type which defines the size and layout of the variable's
memory.
A variable should not exceed 30 characters. Its letter optionally followed by more letters,
dollar signs, numerals, underscore etc.
1. It needs to declare the variable first in the declaration section of a PL/SQL block before
using it.
2. By default, variable names are not case sensitive. A reserved PL/SQL keyword cannot be
used as a variable name.
Here, variable_name is a valid identifier in PL/SQL and datatype must be valid PL/SQL
data type. A data type with size, scale or precision limit is called a constrained
declaration. The constrained declaration needs less memory than unconstrained
declaration.
Example:
Radius Number := 5;
Date_of_birth date;
Declaration Restrictions:
In PL/SQL while declaring the variable some restrictions hold.
o Forward references are not allowed i.e. you must declare a constant or variable before
referencing it in another statement even if it is a declarative statement.
val number := Total - 200;
Total number := 1000;
The first declaration is illegal because the TOTAL variable must be declared before using
it in an assignment expression.
o Variables belonging to the same datatype cannot be declared in the same statement.
N1, N2, N3 Number;
It is an illegal declaration.
1. counter binary_integer := 0;
2. greetings varchar2(20) DEFAULT 'Hello JavaTpoint';
You can also specify NOT NULL constraint to avoid NULL value. If you specify the NOT
NULL constraint, you must assign an initial value for that variable.
You must have a good programming skill to initialize variable properly otherwise,
sometimes program would produce unexpected result.
1. DECLARE
2. a integer := 30;
3. b integer := 40;
4. c integer;
5. f real;
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;
Value of c: 70
Value of f: 33.333333333333333333
o Local Variable: Local variables are the inner block variables which are not accessible to
outer blocks.
o Global Variable: Global variables are declared in outermost block.
1. DECLARE
2. -- Global variables
3. num1 number := 95;
4. num2 number := 85;
5. BEGIN
6. dbms_output.put_line('Outer Variable num1: ' || num1);
7. dbms_output.put_line('Outer Variable num2: ' || num2);
8. DECLARE
9. -- Local variables
10. num1 number := 195;
11. num2 number := 185;
12. BEGIN
13. dbms_output.put_line('Inner Variable num1: ' || num1);
14. dbms_output.put_line('Inner Variable num2: ' || num2);
15. END;
16. END;
17. /
Variable Attributes:
When you declare a PL/SQL variable to hold the column values, it must be of correct
data types and precision, otherwise error will occur on execution. Rather than hard
coding the data type and precision of a variable. PL/SQL provides the facility to declare
a variable without having to specify a particular data type using %TYPE and %ROWTYPE
attributes. These two attributes allow us to specify a variable and have that variable
data type be defined by a table/view column or a PL/SQL package variable.
A % sign servers as the attribute indicator. This method of declaring variables has an
advantage as the user is not concerned with writing and maintaining code.
o %TYPE:
The %TYPE attribute is used to declare variables according to the already declared
variable or database column. It is used when you are declaring an individual variable, not
a record. The data type and precision of the variable declared using %TYPE attribute is
the same as that of the column that is referred from a given table. This is particularly
useful when declaring variables that will hold database values. When using the %TYPE
keyword, the name of the columns and the table to which the variable will correspond
must be known to the user. These are then prefixed with the variable name. If some
previously declared variable is referred then prefix that variable name to the %TYPE
attribute.
1. <var_name> <tab_name>.<column_name>%TYPE;
Consider a declaration.
1. This declaration will declare a variable SALARY that has the same data type as column S
DECLARE
2. SALARY EMP.SAL % TYPE;
3. ECODE EMP.empno % TYPE;
4. BEGIN
5. Ecode :=&Ecode;
6. Select SAL into SALARY from EMP where EMPNO = ECODE;
7. dbms_output.put_line('Salary of ' || ECODE || 'is = || salary');
8. END;
o %ROWTYPE:
The %ROWTYPE attribute is used to declare a record type that represents a row in a
table. The record can store an entire row or some specific data selected from the table.
A column in a row and corresponding fields in a record have the same name and data
types.
1. <var_name> <tab_name>.ROW%TYPE;
EMPLOYEE.SAL := 10000;
EMPLOYEE.ENAME := ‘KIRAN’;
Example:
1. DECLARE
2. EMPLOYEE EMP. % ROW TYPE;
3. BEGIN
4. EMPLOYEE.EMPNO := 2092;
5. 5 EMPLOYEE.ENAME := 'Sanju';
6. Insert into EMP where (EMPNO, ENAME) Values (employee.empno, employee.ename);
7. dbms_output.put_line('Row Inserted');
8. END;
Row Inserted
PL/SQL procedure successfully completed.
Advantages:
o If you don’t know the data type at the time of declaration. The data type assigned
to the associated variables will be determined dynamically at run time.
o If the data type of the variable you are referencing changes the %TYPE or
%ROWTYPE variable changes at run time without having to rewrite variable
declarations. For example: if the ENAME column of an EMP table is changed
from a VARCHAR2(10) to VRACHAR2(15) then you don’t need to modify the
PL/SQL code.
Viva Questions:
WEEK -12
AIM
PL/SQL Part 2
Practice PL/SQL –
operators,
control structures;
aseca
Program:
we will discuss operators in PL/SQL. An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulation. PL/SQL language is rich in
built-in operators and provides the following types of operators −
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Here, we will understand the arithmetic, relational, comparison and logical operators
one by one. The String operators will be discussed in a later chapter − PL/SQL - Strings.
Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 5, then −
Show Examples
Relational Operators
Relational operators compare two expressions or values and return a Boolean result.
Following table shows all the relational operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 20, then −
Show Examples
!=
Checks if the values of two operands are equal or not, if (A != B) is
<> values are not equal then condition becomes true. true.
~=
Checks if the value of left operand is greater than the (A > B) is not
> value of right operand, if yes then condition becomes true.
true.
Checks if the value of left operand is less than the value (A < B) is
<
of right operand, if yes then condition becomes true. true.
Comparison Operators
Comparison operators are used for comparing one expression to another. The result is
always either TRUE, FALSE or NULL.
Show Examples
Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators
work on Boolean operands and produce Boolean results. Let us assume variable
A holds true and variable B holds false, then −
Show Examples
Called the logical AND operator. If both the operands are (A and B) is
and
true then condition becomes true. false.
Called the logical NOT Operator. Used to reverse the not (A and B)
not logical state of its operand. If a condition is true then is true.
Logical NOT operator will make it false.
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
comparison
AND conjunction
OR inclusion
Want to know more about SQL? Read this extensive SQL Tutorial and enhance your
knowledge!
S u b m it
Like the IF statement, the CASE statement selects one sequence of statements to
execute. However, to select the sequence, the CASE statement uses a selector rather
than multiple Boolean expressions. A selector is an expression whose value is used to
select one of several alternatives.
Example: Using the CASE-WHEN Statement
DECLARE
grade CHAR(1);
BEGIN
grade := 'B';
CASE grade
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');
WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');
WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');
ELSE DBMS_OUTPUT.PUT_LINE('No such grade');
END CASE;
END;
/
The simplest form of LOOP statement is the basic loop, which encloses a sequence of
statements between the keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements
END LOOP;
With each iteration of the loop, the sequence of statements is executed, then control
resumes at the top of the loop. You use an EXIT statement to stop looping and prevent
an infinite loop. You can place one or more EXIT statements anywhere inside a loop, but
not outside a loop. There are two forms of EXIT statements: EXIT and
EXIT-WHEN.
The EXIT-WHEN statement lets a loop complete conditionally. When the EXIT statement
is encountered, the condition in the WHEN clause is evaluated. If the condition is true,
the loop completes and control passes to the next statement after the loop.
Like PL/SQL blocks, loops can be labeled. The optional label, an undeclared identifier
enclosed by double angle brackets, must appear at the beginning of the LOOP
statement. The label name can also appear at the end of the LOOP statement. When
you nest labeled loops, use ending label names to improve readability.
The WHILE-LOOP statement executes the statements in the loop body as long as a
condition is true:
WHILE condition LOOP
sequence_of_statements
END LOOP;
The GOTO statement branches to a label unconditionally. The label must be unique
within its scope and must precede an executable statement or a PL/SQL block. When
executed, the GOTO statement transfers control to the labeled statement or block. The
labeled statement or block can be down or up in the sequence of statements.
Example: Using a Simple GOTO Statement
DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37; -- test any integer > 2 for prime
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN -- test for prime
p := ' is not a prime number'; -- not a prime number
GOTO print_now;
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
/
Check out the top PL/SQL Interview Questions to learn what is expected from PL/SQL
professionals!
The NULL statement does nothing and passes control to the next statement. Some
languages refer to such instruction as a no-op (no operation).
Example: Using the NULL Statement to Show No Action
DECLARE
v_job_id VARCHAR2(10);
v_emp_id NUMBER(6) := 110;
BEGIN
SELECT job_id INTO v_job_id FROM employees WHERE employee_id = v_emp_id;
IF v_job_id = 'SA_REP' THEN
UPDATE employees SET commission_pct = commission_pct * 1.2;
ELSE
NULL; -- do nothing if not a sales representative
END IF;
END;
/
Viva Questions: