Control Structures
Control Structures
CONTROL STRUCTURES
Table of contents
1. Conditional Statements
2. Iterative control/ Looping control
3. Sequential Control Statements
4. Cursors
5. Views
Introduction to Conditional Statements
● In Database Management Systems (DBMS), conditional statements are crucial in controlling the data retrieval,
● Conditional statements in DBMS are used to define specific conditions and criteria for extracting or modifying
● The primary purpose is to filter data based on certain conditions, ensuring that only relevant information is
retrieved or updated.
● These statements allow users to query the database more precisely and efficiently, making data retrieval
● Conditional statements are based on Boolean ● The syntax of conditional statements may vary
logic, which deals with expressions that can depending on the programming language
● These true/false conditions are often the involve an "if" condition and often include an
1. if Statement:
The "if" statement is the most basic form of a conditional statement. It checks a specific condition and executes a
block of code if the condition is true. If the condition is false, the code block is skipped, and execution proceeds to
IF condition THEN
ELSE
END IF;
Conditional Statements
2. else Statement:
The "else" statement is used in conjunction with the "if" statement. If the "if" condition evaluates to false, the code
within the "else" block is executed instead.
IF condition THEN
-- SQL statements to be executed if the condition is true
ELSE
-- SQL statements to be executed if the condition is false
END IF;
Conditional Statements
Many programming languages support an "else if" or "elif" statement, which allows the program to test multiple
conditions in sequence. The first condition that evaluates to true will trigger the corresponding code block, and
the rest of the conditions will be skipped.
IF condition THEN
-- SQL statements to be executed if the condition is true
ELSEIF condition2 THEN
-- SQL statements to be executed if condition2 is true (optional)
ELSE
-- SQL statements to be executed if all conditions are false (optional)
END IF;
Practice Questions
Conditional Statements:
1. Consider the following table "products": Write SQL query uses an IF-ELSE statement to
| 102 | Phone | 10 |
| 103 | Tablet |5 |
Practice Questions
Conditional Statements:
2. Consider the following table "students": Write SQL query uses an ELSE IF (CASE) statement
| 102 | Mary | 75 |
| 103 | Alex | 92 |
Practice Questions: Solution
2. SELECT student_name,
1. SELECT product_name,
CASE
CASE
WHEN marks >= 90 THEN 'A'
WHEN quantity_in_stock > 0 THEN 'In Stock' WHEN marks >= 80 THEN 'B'
FROM products;
Iterative Control / Looping Control
Iterative Control / Looping Control
● In Database Management Systems (DBMS), iterative control, often referred to as looping control, is a
programming concept that allows for the repetitive execution of a sequence of statements or commands.
● Looping control structures are essential in DBMS to process data iteratively, typically in batches or over a set
of records.
● These structures enable you to perform the same operation multiple times until a specific condition is met or
•A simple loop, as you can see from its name, is the most basic kind of loop and has the following structure:
•The reserved word LOOP marks the beginning of the simple loop.
LOOP
•Statements are a sequence of statements that is executed repeatedly. sequence
•These statements consist of one or more of the standard programming structures. of statements
END LOOP;
•END LOOP is a reserved phrase that indicates the end of the loop construct.
Simple Loops
• The sequence of statements will be executed an infinite number of times because there is no statement
● Hence, a simple loop is called an infinite loop because there is no means to exit the loop.
set serveroutput on;
DECLARE
i int;
BEGIN
i := 1;
LOOP
if i>10 then
exit;
end if;
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
While Loop
WHILE CONDITION
LOOP
STATEMENT 1;
STATEMENT 2;
STATEMENT N;
END LOOP;
While Loop
● The word CONDITION is the test condition of the loop that evaluates to TRUE or FALSE.
● The END LOOP is a reserved phrase that indicates the end of the loop construct.
While Loop: Example
DECLARE In this example the body of the loop is not executed
v_counter NUMBER := 5; at all because the test condition of the loop evaluates
BEGIN to FALSE.
END LOOP;
END;
For loop
● The reserved word IN or IN REVERSE must be present when defining the loop. If the REVERSE keyword is
used, the loop counter will iterate from upper limit to lower limit.
DECLARE
-- Declare variables
v_num INTEGER;
BEGIN
-- FOR loop syntax
FOR v_num IN 1..10 LOOP -- Loop from 1 to 10
-- Perform operations on v_num (e.g., print the value)
DBMS_OUTPUT.PUT_LINE('Current number: ' || v_num);
END LOOP;
END;
/
For loop
Nested Loops
● Nested loops in SQL refer to using one loop inside another loop to perform iterative tasks on data.
● Simple loops, WHILE loops, and numeric FOR loop can be nested inside one another.
● For example, a simple loop can be nested inside a WHILE loop and vice versa.
Nested Loops: Example
DECLARE LOOP
v_counter1 INTEGER := 0; DBMS_OUTPUT.PUT_LINE('v_counter2:
v_counter2 INTEGER; '||v_counter2);
v_counter1 := v_counter1 + 1;
DBMS_OUTPUT.PUT_LINE('v_counter END LOOP;
1: '||v_counter1);
END;
v_counter2 := 0;
Nested Loops: Example
● In this example, the WHILE loop is called an outer loop because it encompasses the simple loop.
● The simple loop is called an inner loop because it is enclosed by the body of the WHILE loop.
● The outer loop is controlled by the loop counter, v_counter1, and it will execute providing the value of
v_counter1 is less than 3.
● With each iteration of the loop, the value of v_counter1 is displayed on the screen.
● Next, the value of v_counter2 is initialized to 0. It is important to note that v_counter2 is not initialized at the
time of the declaration.
● The simple loop is placed inside the body of the WHILE loop, and the value of v_counter2 must be initialized
every time before control is passed to the simple loop.
Nested Loops: Example
● Once control is passed to the inner loop, the value of v_counter2 is displayed on the screen, and incremented
by 1.
● Next, the EXIT WHEN condition is evaluated. If the EXIT WHEN condition evaluates to FALSE, control is passed
back to the top of the simple loop.
● If the EXIT WHEN condition evaluates to TRUE, the control is passed to the first executable statement outside
the loop.
● In our case, control is passed back to the outer loop, and the value of v_counter1 is incremented by 1, and
the TEST condition of the WHILE loop is evaluated again.
Output
v_counter1: 0
v_counter2: 0
v_counter1: 2
v_counter2: 1
v_counter2: 0
v_counter1: 1
v_counter2: 1
v_counter2: 0
PL/SQL procedure successfully completed
v_counter2: 1
.
Sequential Control
Sequential Control Statements
Sequential control statements in Database Management Systems (DBMS) refer to the basic flow of execution, where
statements are executed one after another in the order they appear in the program or query.
1. SELECT Statement:
The SELECT statement is used to retrieve data from one or more database tables. It allows you to specify the
columns you want to retrieve and the conditions for filtering the data.
Example in SQL:
2. INSERT Statement:
The INSERT statement is used to insert new records into a database table. It specifies the values to be inserted into
Example in SQL:
INSERT INTO Employees (FirstName, LastName, Age, Department) VALUES ('John', 'Doe', 30, 'Sales');
Sequential Control Statements
3. UPDATE Statement:
The UPDATE statement is used to modify existing records in a database table. It allows you to change the values of
Example in SQL:
These sequential control statements form the core operations for interacting with a database in a DBMS
environment.
4. DELETE Statement:
The DELETE statement is used to remove records from a database table based on specific conditions.
5. CREATE Statement:
The CREATE statement is used to create new database objects such as tables, views, or indexes.
Example in SQL:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50),
Consider the following table "employees": them in ascending order based on the
"emp_name."
● A cursor is a database object that allows you to retrieve and manipulate the result set of a query in a
procedural manner. Cursors are particularly useful when you want to traverse the records in a result set one
● Cursors are commonly used in procedural languages like PL/SQL (Oracle), T-SQL (Microsoft SQL Server), and
● Declaration:
DECLARE
CURSOR c1 IS fetch c1 into c1_rec;
select sid,fname while c1%found loop
from students;
c1_rec c1%rowtype; dbms_output.put_line('Row
BEGIN Number ' || c1%rowcount || '> ' ||
if not c1%isopen then c1_rec.sid || ' ' ||
open c1; c1_rec.fname);
end if; fetch c1 into c1_rec;
end loop;
close c1;
END;
/
How to work with cursors
DECLARE
CURSOR c1 IS
select sid,fname
from students;
BEGIN
for c1_rec in c1 loop
dbms_output.put_line('Row Number ' || c1%rowcount || '> ' ||
c1_rec.sid || ' ' || c1_rec.fname);
end loop;
END;
/
● When using “for loops” the cursor does not have to be explicitly opened and fetched from.
Practice Questions
1. Use a cursor to fetch and display all employee names and salaries.
Practice Question: Solution
DECLARE
CURSOR emp_cursor IS
v_emp_name employees.emp_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
END LOOP;
CLOSE emp_cursor;
END;
/
Views
Views
● View is a virtual table derived from one or more existing database tables or other views.
● It does not store any data itself; instead, it represents a saved query that produces a result set based on the
underlying data.
● Views provide an abstraction layer to simplify data access and hide the complexity of underlying table
● Views are powerful tools in DBMS, allowing for better data management, data security, and simplification of
data access.
● They are commonly used in scenarios where complex queries need to be simplified, and specific data access
In this syntax:
Syntax:
- `view_name`: The name of the view to be created.
CREATE VIEW view_name AS
- `column1, column2, ...`: The columns selected from
SELECT column1, column2, ...
the underlying table(s) to be included in the view.
FROM table_name
- `table_name`: The name of the table(s) from which
WHERE condition;
the view will be derived.
the view.
Once the view is created, users can query it just like they would query a regular table.
Consider the following table "employees": that shows only the employees in the "HR"
50000.
Practice Questions: Solution
1.
2.