How to Get Counts of all Tables in a Schema in PL/SQL?
Last Updated :
07 Nov, 2024
In Database Management System, it is essential to retrieve the statistical information about tables with the schema. Whether it is for monitoring the database health, optimizing the performance, or simply understanding the data structures having access to row counts of the tables can be more valuable.
How to Get Counts of all Tables in a Schema in PL/SQL?
In database management obtaining insights into the structure and the content of the database tables is crucial for various tasks like performance optimization, resource management, and data analysis. One of the fundamental aspects of this process is determining the number of rows within each table of the schema.
Syntax to get counts of all tables in a schema in PL/SQL:
DECLARE
v_table_name VARCHAR2(100);
v_count NUMBER;
BEGIN
-- Cursor loop to iterate through tables in the schema
FOR tables IN (SELECT table_name FROM user_tables) LOOP
-- Get the table name
v_table_name := tables.table_name;
-- Construct and execute dynamic SQL to count rows in the table
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || v_table_name INTO v_count;
-- Output the table name and row count
DBMS_OUTPUT.PUT_LINE('Table ' || v_table_name || ' has ' || v_count || ' rows.');
END LOOP;
END;
/
Explanation:
- DECLARE keyword is begins the declaration section of PL/SQL block where the variables and cursors are to be declared.
- v_table_name is used to hold the names of the each table which can be iterate them.
- v_count is variable which is used to store the row count for each table.
- BEGIN keyword is used to mark the beginning of the executable section of PL/SQL block.
- FOR tables IN (....) LOOP is the cursor loop which is used to iterate the result set of the table names obtained from the querying user_tables.
- EXECUTE IMMEDIATE is the statement which is used to execute the dynamic SQL. It will be take a string contains the SQL statements as input and it will execute it.
- DBMS_OUTPUT.PUT_LINE procedure is used to output text to the console or output buffer.
- END LOOP is used to end the loop.
- END; is used to end the block of the PL/SQL.1.
Using PL/SQL Cursors
Using PL/SQL cursors are an effective method for the retrieving the data from database and it process it row by row. Cursors are allowed to the iterate through the result set returned by the SQL query and enabling to the perform operations on each row individually.
Step 1: Create a table and name it as employee.
Here is the employee table.
Employee tableStep 2: Implement the Code
DECLARE
v_total_salary NUMBER := 0;
BEGIN
FOR emp_record IN (SELECT * FROM employee) LOOP
v_total_salary := v_total_salary + emp_record.salary;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total Salary: ' || v_total_salary);
END;
/
Output:
OutputExplanation:
- We declare the variable v_total_salary to store the total salary is initialized to 0.
- We can use cursor loop to the iterate the each row of the employee table. The cursor emp_record holds the current row data.
- In the loop, we increment the v_total_salary by adding the salary of the employee.
- Once the loop is finished, we print the total salary with the help of DBMS_OUTPUT.PUT_LINE.
Using PL/SQL Procedures
Using the PL/SQL procedure is the structured way to the encapsulate the series of SQL and PL/SQL statements into reusable units of the code. Procedures can be accept the input parameters, perform the operations and it returns output values. These are mainly useful for the modularizing the code, improving the maintainability and promoting the code reuse.
Let us take same employee table to retrieve the average salary for the specific department.
Step 1: Create or Replace the procedure
CREATE OR REPLACE PROCEDURE CalculateAvgSalary(
department_id IN NUMBER,
avg_salary OUT NUMBER
)
AS
BEGIN
SELECT AVG(salary)
INTO avg_salary
FROM employee
WHERE DepartmentID = department_id;
END;
/
Explanation:
- We can create the PL/SQL procedure and named as CalculateAvgSalary with the two parameters such as department_id and avg_salary.
- In the Procedure, we use the SQL query to calculate the average salary of the employee which is related to the specific department.
- The query result is stores in the avg_salary output parameter with the help of INTO clause.
Step 2: Calling the Procedure
DECLARE
v_avg_salary NUMBER;
BEGIN
CalculateAvgSalary(1, v_avg_salary);
DBMS_OUTPUT.PUT_LINE('Average Salary for Department 1: ' || v_avg_salary);
END;
/
For call the procedure and retrieve the average salary for the specific department, you can execute the above PL/SQL block.
Output:
OutputIn the above output, average salary for Department 1 is 5000.
Conclusion
Using PL/SQL to retrieve row counts for all tables in a schema is an efficient way to gather statistical data, automate row counting, and monitor database health. This approach helps identify performance bottlenecks and understand data distribution. Integrating PL/SQL solutions streamlines database monitoring, optimization, and decision-making, enhancing overall database management effectiveness.
Similar Reads
How to List All Tables in a Schema in Oracle Database?
In Oracle Database, listing all tables within a schema can be crucial for database management and analysis. we can use specific queries to retrieve information about tables in our schema. Below, we explore various queries to list tables, focusing on the SYSOBJECTS view that provides essential metada
3 min read
How to Show Schema of a Table in MySQL Database?
A table schema in MySQL database defines the structure of table, including columns, data types, relationships between columns, etc. It is a blueprint for the table, describing how data is organized in the table and how it relates to other tables in the database. To see the schema of a table in MySQL
2 min read
Copy a Table from One Schema to Another in SQL?
When working with MySQL, there are several scenarios where we may need to copy tables (including their structure and data) from one schema (database) to another. This is a common task during database migrations, backups, or when testing with different environments. In this article, we will go throug
5 min read
How to Export Database and Table Schemas in SQLite?
Exporting database schemas in SQLite is an important task for database management, enabling functions like data backup, recovery, migration, and auditing. In this article, We will go through the process of exporting database and table schemas in SQLite by understanding various examples to manage SQL
4 min read
How to Check if a Column Exists in a SQL Server Table?
In this article, we will look at how to check if a particular column exists in a database table or not. For checking the existence of a column we need to create the table first. So, let us create a table with some columns and data. Creating table: Syntax: CREATE TABLE table_name ( column1 datatype,
2 min read
How to Display all Tables in PL/SQL?
In Oracle PL/SQL, we need to work with database objects like tables. It provides various approaches to display all the tables. Such as using the USER_TABLES, ALL_TABLES, and DBA_TABLES views. Each approach is explained with syntax and examples. In this article, We will learn about How to Display all
5 min read
How to Get Record Count for All Tables in MySQL Database
In DBMS, counting records for all tables within a MySQL database is a fundamental requirement. Understanding the size and distribution of data across tables helps optimize database performance and provides insights into data utilization and growth patterns. Row or record count means how many records
5 min read
How to Show a List of Databases in PL/SQL?
Managing databases is a fundamental aspect of database administration and development. In Oracle Database, schemas represent logical containers for database objects like tables, views, procedures, and functions. PL/SQL is the procedural extension of and used in Oracle Database and provides powerful
5 min read
How to Export Schema Without Data in PL/SQL?
In database management, there are times when you need to export the structure of your database objects such as tables, views, and procedures without including the data. This can be useful for creating backups, migrating databases, setting up development or testing environments, or sharing your schem
4 min read
How to count rows in MySQL table in PHP ?
PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases. In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL. Requirements: XAMPP Approach: By using PHP and MySQL, one can p
3 min read