0% found this document useful (0 votes)
17 views

Control Structures

The document provides an overview of control structures in Database Management Systems (DBMS), including conditional statements, iterative control, and sequential control statements. It covers key concepts such as Boolean logic, various types of loops (simple, while, for, and nested), and essential SQL commands like SELECT, INSERT, UPDATE, and DELETE. Additionally, it discusses cursors and views, highlighting their importance in data retrieval and manipulation.

Uploaded by

NIKHIL GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Control Structures

The document provides an overview of control structures in Database Management Systems (DBMS), including conditional statements, iterative control, and sequential control statements. It covers key concepts such as Boolean logic, various types of loops (simple, while, for, and nested), and essential SQL commands like SELECT, INSERT, UPDATE, and DELETE. Additionally, it discusses cursors and views, highlighting their importance in data retrieval and manipulation.

Uploaded by

NIKHIL GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Database Management System

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,

manipulation, and processing flow.

● Conditional statements in DBMS are used to define specific conditions and criteria for extracting or modifying

data from the database.

● 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

more targeted and reducing the amount of unnecessary data processing.


Key Concepts

Boolean Logic: Syntax:

● 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

only have two values: true or false being used.

(represented as 1 or 0, respectively). ● The core concept remains the same: they

● These true/false conditions are often the involve an "if" condition and often include an

result of comparisons or evaluations made optional "else" block.

within the conditional statement.


Conditional Statements

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

the next part of the program.

IF condition THEN

-- SQL statements to be executed if the condition is true

ELSE

-- SQL statements to be executed if the condition is false (optional)

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

3. else if Statement (elif or elseif):

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

display the product status as "In Stock" if the


| product_id | product_name | quantity_in_stock |
quantity is greater than 0, and "Out of Stock"
| 101 | Laptop | 15 |
otherwise?

| 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

to display the grade of each student based on the


| student_id | student_name | marks |
marks?
| 101 | John | 85 |

| 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'

WHEN marks >= 70 THEN 'C'


ELSE 'Out of Stock'
END AS grade
END AS product_status
FROM students;

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 defined number of iterations is reached.


Simple Loops

•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

specifying when the loop must terminate.

● 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

•A WHILE loop has the following structure:

WHILE CONDITION

LOOP

STATEMENT 1;

STATEMENT 2;

STATEMENT N;

END LOOP;
While Loop

● The reserved word WHILE marks the beginning of a loop construct.

● The word CONDITION is the test condition of the loop that evaluates to TRUE or FALSE.

● The result of this evaluation determines whether the loop is executed.

● Statements 1 through N are a sequence of statements that is executed repeatedly.

● 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.

• While the test condition of the loop must evaluate


WHILE v_counter < 5
to TRUE at least once for the statements in the loop
LOOP
to execute, it is important to insure that the test
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
condition will eventually evaluate to FALSE as well.

v_counter := v_counter - 1; • Otherwise, the WHILE loop will execute continually.

END LOOP;

END;
For loop

● The reserved word FOR marks the beginning of a loop construct.


● The variable, loop_counter, is an implicitly defined index variable. So, there is no need to define loop counter
in the declaration section of the PL/SQL block.
● This variable is defined by the loop construct.
● Lower_limit and upper_limit are two integer numbers that define the number of iterations for the loop.
● The values of the lower_limit and upper_limit are evaluated once, for the first iteration of the loop. At this
point, it is determined how many times the loop will iterate.
● Statements 1 through N are a sequence of statements that is executed repeatedly.
● END LOOP is a reserved phrase that marks the end of the loop construct.
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);

BEGIN v_counter2 := v_counter2 + 1;

WHILE v_counter1 < 3 EXIT WHEN v_counter2 >= 2;

LOOP END LOOP;

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:

SELECT FirstName, LastName, Age FROM Employees WHERE Department = 'Sales';


Sequential Control Statements

2. INSERT Statement:

The INSERT statement is used to insert new records into a database table. It specifies the values to be inserted into

the respective columns.

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

specific columns based on certain conditions.

Example in SQL:

UPDATE Employees SET Department = 'Marketing' WHERE Department = 'Sales';

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.

Example in SQL: DELETE FROM Employees WHERE Age > 60;

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),

Age INT, Department VARCHAR(50));


Practice Questions

1. Write an SQL query to retrieve all employee

records from the "employees" table and sort

Consider the following table "employees": them in ascending order based on the

"emp_name."

| emp_id | emp_name | department | salary | 2. Write an SQL query to retrieve employee

| 101 | John | HR | 45000 | names and their corresponding salaries from

| 102 | Mary | IT | 55000 | the "employees" table, sorted in descending

| 103 | Alex | HR | 40000 | order of salary.


Cursors
CURSORS

● 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

by one and perform operations on each record individually.

● Cursors are commonly used in procedural languages like PL/SQL (Oracle), T-SQL (Microsoft SQL Server), and

PL/pgSQL (PostgreSQL) to process query results row by row.

● Declaration:

cursor <sname> is <select statement>;


Cursor example

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 the cursor


● Declare a variable rec_name of type cursor%rowtype
● “open c_name”
● Fetch row by row “fetch c_name into rec_name”
● “close cursor”
● –c_name%found – returns true if there are still records , false otherwise
● –c_name%isopen - returns true if the cursor is open, false otherwise
Cursor “for” example

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

Consider the following table "employees":

| emp_id | emp_name | department | salary |

| 101 | John | HR | 45000 |

| 102 | Mary | IT | 55000 |

| 103 | Alex | HR | 40000 |

1. Use a cursor to fetch and display all employee names and salaries.
Practice Question: Solution

DECLARE

CURSOR emp_cursor IS

SELECT emp_name, salary FROM employees;

v_emp_name employees.emp_name%TYPE;

v_salary employees.salary%TYPE;

BEGIN

OPEN emp_cursor;

LOOP

FETCH emp_cursor INTO v_emp_name, v_salary;


Practice Question:Solution

EXIT WHEN emp_cursor%NOTFOUND;

-- Display the data

DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name || ', Salary: ' || v_salary);

END LOOP;

-- Close the cursor

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

structures, making it easier for users to interact with the database.

● 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

permissions need to be granted to users.


Views

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.

- `condition`: The optional condition to filter the rows in

the view.

Once the view is created, users can query it just like they would query a regular table.

For example: SELECT * FROM view_name;


Practice Questions

1. Create a view named "hr_employees"

Consider the following table "employees": that shows only the employees in the "HR"

| emp_id | emp_name | department | salary | department.

| 101 | John | HR | 45000 | 2. Create a view named

| 102 | Mary | IT | 55000 | "high_paid_employees" that shows only

| 103 | Alex | HR | 40000 | the employees with a salary greater than

50000.
Practice Questions: Solution

1.

CREATE VIEW hr_employees AS

SELECT * FROM employees

WHERE department = 'HR';

2.

CREATE VIEW high_paid_employees AS

SELECT * FROM employees

WHERE salary > 50000;

You might also like