Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Retrieve Data From Multiple Tables Using PL/SQL Cursors
Next article icon

How to Retrieve Data from Multiple Tables in PL/SQL

Last Updated : 12 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PL/SQL is “Procedural Language extensions to the Structured Query Language”. SQL is a popular language for both querying and updating data in relational database management systems (RDBMS). PL/SQL adds many procedural constructs to SQL language to overcome some limitations of SQL. In addition, PL/SQL provides a more comprehensive programming language solution for building mission-critical applications on Oracle Databases.

Retrieving data from multiple tables in PL/SQL mainly involves using SQL Joins, which allows to combination of rows from one or more tables based on the related column between them. Before going with the query of retrieving data from multiple tables make sure you have sufficient or basic knowledge about SQL joins.

Steps for Retrieving data from multiple tables in PL/SQL

Step 1: CREATE TABLE Statement

The PL/SQL CREATE TABLE statement allows you to create and define a table.

Syntax:

The syntax for the CREATE TABLE statement in Oracle/PLSQL is:

CREATE TABLE table_name
(
column1 constraints,
column2 constraints,
...
column_n constraints
);

Step 2: INSERT Statement

The Oracle/PLSQL INSERT statement is used to insert a single record or multiple records into a table in Oracle.

Syntax:

The syntax for the Oracle/PLSQL INSERT statement when inserting a single record using the VALUES keyword is:

INSERT INTO table_name
(column1, column2, ... column_n )
VALUES
(expression1, expression2, ... expression_n );

The syntax for the Oracle INSERT statement when inserting multiple records using a SELECT statement is:

INSERT INTO table_name
(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
[WHERE conditions];

PS: expressions are nothing but values that we want to insert into the table.

Step 3: SQL Queries with Joins to Retrieve Data from Tables

Oracle JOINS are used to retrieve data from multiple tables. An Oracle JOIN is performed whenever two or more tables are joined in an SQL statement.

There are 4 different types of Oracle joins:

  • INNER JOIN
  • LEFT OUTER JOIN
  • RIGHT OUTER JOIN
  • FULL OUTER JOIN

Visual Representation

JOINS
JOINS

Step 4: Declaration of variables within a PL/SQL Block

You must have to declare the PL/SQL variables in the declaration section as global variables. After the declaration, the variable's name is associated with storage location, and variable's value is allocated by PL/SQL in memory.

Syntax:

DECLARE
variable_name datatype;
-- additional variable's declaration
BEGIN
-- PL/SQL statements here
END;
/

Step 5: Working with Cursor

A PL/SQL cursor is a pointer that points to the result set of an SQL query against database tables. The following picture describes steps that you need to follow when you work with PL/SQL Cursor :

Cursors
Cursors

Syntax:

CURSOR cursor_name [([parameter_1 [, parameter_2...])]
[RETURN return_specification]
IS sql_select_statements
[FOR UPDATE [OF [Column-_list]];

Step 6: Retrieving the Data from the SQL query using the PL/SQL loop

In this step, we use cursor to retrieve and process data that is returned by SQL queries. Since the cursor provides mechanism for iterating over the rows of a result set and enables us to perform operations on each row individually.

Step 7: End of PL/SQL block

The end of PL/SQL block is marked by 'END' statement. This represents the conclusion of the block's executable section.

Syntax:

DECLARE
-- variable declaration
BEGIN
-- PL/SQL Statements
-- End of executive section
END;
/

Query for Retrieving Data from multiple tables in PL/SQL

After utilizing the above concepts, we will now we write a query for retrieving data from multiple tables in PL/SQL. We will proceed with the mentioned steps only, which help you to understand the structure of the query thoroughly.

1. Creating 'Customers', 'Products' & 'Orders' Table using CREATE TABLE Statement

Query for Creating 'Customers' Table

CREATE TABLE customers (
customer_id NUMBER PRIMARY KEY,
customer_name VARCHAR2(100)
);

Query for Creating 'Products' Table

CREATE TABLE products (
product_id NUMBER PRIMARY KEY,
product_name VARCHAR2(100),
price NUMBER
);

Query for Creating 'Orders' Table

CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
customer_id NUMBER,
product_id NUMBER,
order_date DATE,
quantity NUMBER,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
);

2. Inserting values to the tables using INSERT INTO Statement

Inserting the values into 'Customers':

INSERT INTO customers VALUES (1, 'Custom-1');
INSERT INTO customers VALUES (2, 'Custom-2');

Output:

'Customers'-Table-Data
Inserted data into 'Customers'

Inserting the values into 'Products':

INSERT INTO products VALUES (101, 'Product-A', 2000);
INSERT INTO products VALUES (102, 'Product-B', 3000);

Output:

'Products'-table-Data
Inserted data into 'Products'

Inserting the values into 'Orders':

INSERT INTO orders VALUES (1001, 1, 101, SYSDATE, 2);
INSERT INTO orders VALUES (1002, 1, 102, SYSDATE-1, 1);
INSERT INTO orders VALUES (1003, 2, 101, SYSDATE-2, 3);

Output:

Columns-of-Orders-Table
Inserted data into 'Orders'

3. Declaring the Variables

DECLARE
v_customer_id NUMBER := 1; -- Specify the desired customer ID
v_product_name products.product_name%TYPE;
v_product_price products.price%TYPE;

4. Working with Cursor

BEGIN
FOR order_rec IN (
SELECT o.order_id, p.product_name, p.price, o.order_date, o.quantity
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE o.customer_id = v_customer_id
)

5. Processing Cursor Results

LOOP
-- Assign values to variables
v_product_name := order_rec.product_name;
v_product_price := order_rec.price;

-- Display order details
DBMS_OUTPUT.PUT_LINE('Order ID: ' || order_rec.order_id);
DBMS_OUTPUT.PUT_LINE('Product Name: ' || v_product_name);
DBMS_OUTPUT.PUT_LINE('Product Price: ' || v_product_price);
DBMS_OUTPUT.PUT_LINE('Order Date: ' || TO_CHAR(order_rec.order_date, 'MM/DD/YYYY'));
DBMS_OUTPUT.PUT_LINE('Quantity: ' || order_rec.quantity);
DBMS_OUTPUT.PUT_LINE('---');
END LOOP;
END;
/

Output:

Retrieving the data from the 'Customers', 'Products' and 'Orders' Table:

OUTPUT-1-(1)
First Record

Second Record:

OUTPUT-2
Second Record

Conclusion

So, by this, we have successfully demonstrated the PL/SQL query for retrieving the data from multiple tables using cursors within the PL/SQL loop. Additionally, we utilized the concept of JOINS to connect the tables based on their common keys, which allows us to extract the relevant information from the database. At last, by utilizing the DBMS_OUTPUT.PUT_LINE procedure, we represented the Order details in an obvious and organized manner.


Next Article
How to Retrieve Data From Multiple Tables Using PL/SQL Cursors
author
nehap0302
Improve
Article Tags :
  • Databases
  • PL/SQL
  • PL/SQL Query

Similar Reads

  • How to Retrieve Data from Multiple Tables in SQL?
    In SQL, retrieving data from multiple tables is a common requirement in database operations. Efficiently combining data from different tables allows developers to create complex queries and extract valuable insights from interconnected datasets. In this article, we will explore multiple approaches t
    5 min read
  • How to Retrieve Data From Multiple Tables Using PL/SQL Cursors
    In database programming, the ability to retrieve data from multiple tables is essential for building robust and efficient applications. PL/SQL Cursors is a powerful feature that enables developers to navigate through result sets and make them the best option for querying data from multiple tables. I
    4 min read
  • SELECT Data from Multiple Tables in SQL
    In SQL (Structured Query Language), it is a common requirement to retrieve data from more than one table at once. When you work with relational databases, you often have to combine data from multiple tables to get meaningful results. SQL provides many methods for selecting data from multiple tables,
    4 min read
  • How to Query Multiple Tables in SQL
    SQL (Structured Query Language) is a powerful tool for managing and querying relational databases. One of its most valuable features is the ability to query multiple tables simultaneously, allowing us to retrieve and integrate related data efficiently. In this article, we will explain how to query m
    4 min read
  • Retrieve Records from Multiple Tables in MySQL
    In relational databases like MySQL, data is often spread across multiple tables to maintain normalization and avoid redundancy. To effectively work with such data, you need to combine and retrieve records from these tables using various types of joins and other methods. This article will guide you t
    5 min read
  • SQL - SELECT from Multiple Tables with MS SQL Server
    In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we con
    3 min read
  • How to Perform SQL Join on Multiple Columns in Same Table?
    To perform a SQL JOIN on multiple columns in the same table, we use the Self Join. This technique allows us to create connections between different columns of the same table by comparing them directly. We can implement a Self Join using various types of joins such as “inner,” “left,” “right,” “full,
    4 min read
  • How to Get Multiple Counts With Single Query in PL/SQL?
    In PL/SQL, it's very common that we need to count rows based on the different conditions in the single query. This can be done using conditional aggregation or we also do this with the multiple subqueries within the SELECT statement. Here, the SELECT statement is necessary to perform this operation.
    4 min read
  • How to Retrieve Column Data Type in Oracle Using PL/SQL
    In Oracle databases, understanding column data types is essential for effective database management. PL/SQL provides a straightforward way to retrieve these data types, aiding in database design and query formulation. By querying system views like USER_TAB_COLUMNS, users can obtain valuable insights
    4 min read
  • How to Left Join Multiple Tables in SQL
    Left Join is one of the Keywords used while writing queries in SQL. In SQL we normally use Join for the purpose of forming a new table by taking out common data like rows or records or tuples from both the tables which are having matching records in general. Here when it comes to Left Join in SQL it
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences