I have a set of tables in Oracle and I would like to identify the table that contains the maximum number of rows.
So if, A has 200 rows, B has 345 rows and C has 120
Here's another method, likely to be much slower than simply getting ALL_TABLES.NUM_ROWS, but it doesn't depend on statistics having been gathered and gives exact, current values -- although how current depends on how long it takes to run!
-- For running in SQLPlus you need this to see the output.
-- If running in Toad or similar tool, output is enabled by default
SET SERVEROUTPUT ON SIZE 100000
DECLARE
l_rows INTEGER;
l_max_rows INTEGER := 0;
l_table_name all_tables.table_name%TYPE := NULL;
BEGIN
FOR table_record IN (SELECT table_name FROM all_tables) LOOP
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM '||table_record.table_name
INTO l_rows;
IF l_rows > l_max_rows THEN
l_max_rows := l_rows;
l_table_name := table_record.table_name;
END IF;
END LOOP;
IF l_table_name IS NULL THEN
dbms_output.put_line( 'All tables are empty' );
ELSE
dbms_output.put_line( 'Table ' || table_record.table_name ||
' has ' || TO_CHAR(l_max_rows) || ' rows'
);
END IF;
END;
/