Writing a query to count entries for all tables

I'd like to write a query to count the number of rows in every table for a given database. For example, if I have two tables in a database called TEST1 and TEST2 with 20 and 30 rows respectively, I'd like the output of the query to be
TABLE_NAME          ROW_COUNT
TEST1               20
TEST2               30
Any ideas?

or justin,
How about this
SQL> ed
Wrote file afiedt.buf
  1  declare
  2  t_count number;
  3  begin
  4    dbms_output.put_line('table_name          Num_rows  ');
  5    dbms_output.put_line('----------         ---------- ');
  6   for i in (select table_name  from user_tables) loop
  7    execute immediate 'select count(*) from '||i.table_name into t_count;
  8    dbms_output.put_line(i.table_name||'       '||t_count);
  9    end loop;
10* end;
SQL> /
table_name          Num_rows
EMP_TEST         0
BOOK            2
MONTH           36
BOOK_SALES           65
CURRENCY          2
EMP          18
BONUS          0
DEPT          5
SALGRADE         0
PLAN_TABLE         0
PL/SQL procedure successfully completed.

Similar Messages

  • Counting rows for db tables with 500 million+ entries

    Hi
    SE16 transaction timesout in foreground when showing number of entries for db tables with 500million+ entries. In background this takes too long.
    I am writing a custom report to get number of records of a table and using OPEN CURSOR concept to determine number of records.
    Is there any other efficient way to read number of records from such huge tables.
            OPEN CURSOR l_cursor FOR
            SELECT COUNT(*)
               FROM (u_str_param-p_tabn) WHERE (l_tab_cond).  " u_str_param-p_tabn is the table name in input and l_tab_cond is a
              DO.                                                                              " dynamic where condition
                FETCH NEXT CURSOR l_cursor INTO l_new_count.
               PACKAGE SIZE p_pack.
                IF sy-subrc NE 0.
                  EXIT.
                ELSE.
                  l_tot_cnt = l_tot_cnt + l_new_count. " l_tot_cnt will contain number of records at end of loops
                  CLEAR l_new_count.
                ENDIF.
              ENDDO.
              CLOSE CURSOR l_cursor.

    Hello,
    For sure it is a huge number of entries!!!
    Is any key-fields?
    Use a variable to keep a counter of the key-fields , for example row_table and also a low and high variable .
    Try to use a do-loop and in this loop use:
    do .
    low_row  = row_table.
    low_high = row_table + 200.000.:increse the select every 200.000 entries
    Do  "select statement into table"  based on the key-fields 
    For example : if the key-field is the docnr,
    Do a "select into table itab where docnr >low_row
                                            and docnr < low_high"
    Count the lines of itab and keep them in a variable.
    free the itab.
    enddo
    Good luck.
    Antonis

  • What is the problem with native dynamic sql when counting rows in all table

    what is the problem with native dynamic sql when counting rows in all table?Giving an error "table or view does not exist". Thanks.
    DECLARE
    v_sql_string varchar2(1000);
    v_no_of_rows number;
    BEGIN
    for i in ( select table_name from all_tables )
    loop
    v_sql_string := ' select count(1) from ' || i.table_name;
    dbms_output.put_line( v_sql_string );
    --execute immediate v_sql_string into v_no_of_rows;
    end loop;
    END;

    Usually your problem can be described with 'Who cares'. I mean, for what reason do you do this? I doubt that there's a business need to get 100 % accurate answers for this. Normally such things are used to get a picture about the growth of data.
    Personally I would prefer to have up-to-date statistics for all tables and just query the number of rows from there. Sufficient for me in < 99 % of all cases.
    Just my $ .02...

  • How to query the count of the temporary table from user_objects

    e.g. select count(*) from user_objects where object_type='TABLE'
    According to the SQL,I can query the all table including the temporary table,Can I how to query the count of the temporary table from user_objects excluding the permanent table?
    thanks a lot!

    select count(*)  from user_objects where object_type='TABLE' and temporary = 'Y'

  • How do I run sp_spaceused for all tables in a database?

    Hi,
    I am struggling to understand how to run the sp_spaceused sproc for all tables in a database.
    I know how to use it for one table but how would I replicate it automatically for each table in a given database?
    Regards,
    Ian.

    I just managed to alter the code of VidyaSagar and have pulled out all the information including Schema name. Below is what it looks like:
    set
    nocount
    on
    select
    'Database Name: ',
    db_name
    if
    exists(select
    name from tempdb..sysobjects
    where name='##tmp'
    drop
    table ##tmp
    create
    table ##tmp(TABLE_SCHEMA
    nvarchar(256),TABLE_NAME
    nvarchar(256),
    num_rows int,
    reserved_KB varchar(15),data_KB
    varchar(15),index_KB
    varchar(15),unsed_KB
    varchar(15
    go
    declare
    @tbl_schema nvarchar(256
    declare
    @tbl_name nvarchar(256
    declare
    @schema_tbl_name nvarchar(256
    declare
    tblname CURSOR
    for
    select
    TABLE_SCHEMA
    TABLE_NAME
    from
    INFORMATION_SCHEMA.TABLES
    where TABLE_TYPE='BASE
    TABLE' 
    open
    tblname
    Fetch
    next
    from tblname
    INTO @tbl_schema,@tbl_name
    WHILE
    @@FETCH_STATUS
    = 0
    BEGIN
    set @schema_tbl_name=@tbl_schema+'.'+@tbl_name
    insert
    into ##tmp(TABLE_NAME
    , num_rows
    , reserved_KB
    ,data_KB
    ,index_KB
    ,unsed_KB
    exec
    sp_spaceused
    @schema_tbl_name
    update ##tmp
    set TABLE_SCHEMA
    =@tbl_schema
    where TABLE_SCHEMA
    is
    NULL
    and TABLE_NAME=@tbl_name
    FETCH
    NEXT
    FROM tblname
    INTO @tbl_schema,@tbl_name 
    END
    CLOSE
    tblname
    deallocate
    tblname
    go
    select
    from
    ##tmp
    drop
    table ##tmp
    Warm Regards, Ajay

  • Extract schema/metadata - names for all tables and attributes

    Hi, I am quite new to Oracle DB (only been doing dev mostly with sqlserver before). Is there a way to extract schema (names for all tables and attributes) for 10g and 11g in application code (either java or .net) or pl/sql?
    Thank you,
    -Tony

    There are built in views that start with DBA_, ALL_, and USER_. All means all the user can see, user means all the user has, and dba means everything, which generally means the same as the others plus an owner. So you can desc user_tables to see what-all that view has, then select columns from the view with ordinary sql. See the doc set for all the views available, interesting ones are ...views, ...objects, ...tab_cols and so forth.
    There are also built in procedures for getting metadata, google for details.
    Many tools have easy GUI's for this too. EM has ways on the administration screen to get to various objects, and then you can show the ddl. Maybe sqldeveloper has something too.

  • Count(*) for all tables

    Hi ,
    I want the Query to get the table name and count(*) display in excel like this.Can i get count(*) from metadata table .Please let me know ??
    ACCT 53
    ACCT_CHEQUE 45
    EMP 50
    DEPT 90

    Karthick_Arp wrote:
    A XML solution.
    This one is not mine. This question comes up often in this forum. And once i saw this answer. And i thought its really cool so just saved it in my Google Note Book ;)You need to update your google note book. It doesn't take account of Index Organised Tables.
    Based on answer from Laurent Schneider
    http://laurentschneider.com/wordpress/2007/04/how-do-i-store-the-counts-of-all-tables.html
    SQL> select
      2    table_name,
      3    to_number(
      4      extractvalue(
      5        xmltype(
      6 dbms_xmlgen.getxml('select count(*) c from '||table_name))
      7        ,'/ROWSET/ROW/C')) count
      8  from user_tables
      9 where iot_type != 'IOT_OVERFLOW';
    TABLE_NAME                      COUNT
    DEPT                                4
    EMP                                14
    BONUS                               0
    SALGRADE                            5Edited by: BluShadow on Jul 8, 2009 12:00 PM

  • Query on Counting Rules for CL

    Our customer has the following requirement regarding Casual Leave (CL). If the CL days are BOTH prefixed & suffixed by OFF days and/or holidays then ONE extra day of CL is to be counted. E.g. Assume an employee takes one day CL on 5-Mar-12, 6-Mar-12 and 4-Jan-12 is his weekly OFF and 7-Mar-12 is a holiday. Then CL days days have to be counted as 2+1 = 3 days (one day extra).
    However, if CL days are only prefixed or only suffixed with OFF days or holidays, then the actual CL days have to be counted. E.g. employee takes CL on 8-Mar-12 and 7-Mar-12 is a OFF day or holiday. Then only ONE day CL (Actual) is to be counted. Similarly, if employee takes CL on 9-Mar-12 and 10-Mar-12 is a OFF day or holiday, then also only ONE day Cl (actual) is to be counted.
    Please guide me on how to configure the counting rules for the above scenarios.
    -Kalpana

    Hi,
    Check all the week days, Allholiday class, All the DWS class,  conditions for day selected in countingrule.
    With same counting rule number with other grouings i.e ESG grouping for Time quotas, PSG grouping for Time Quotas with different cobination having any collution. in case of employee subgroup changes it may reflect.
    Eventhough everything is fine then already updated employee master again you need to save the masterdata with change mode through PA30.

  • Count number of distinct values for a column for all tables that contains that column

    Imagine I have one Column called cdperson. With the query below I know which Tables have column cdperson
    select
    t.[name]fromsys.schemassinnerjoin 
    sys.tables 
    tons.schema_id=t.schema_idinnerjoin 
    sys.columnscont.object_id=c.object_idinnerjoin 
    sys.types  
    donc.user_type_id=d.user_type_idwherec.name ='cdperson'
    now I want to know for each table, how many distinct values of cdperson I have and I want the result ordered by the table that has more distinct values (descending)
    Table1                                                                                     
       cdperson                        select distinct(cdperson) = 10
       cdadress
       quant
    Table2 with 
       cdaddress                      (no column cdperson in this table)
       quant
    Table3
       cdperson                        select distinct(cdperson) = 100
       value
    Table 4
       cdperson                        select distinct(cdperson) = 18
       sum
    I want this result ordered by number of distinct cdperson
    table3   100
    table4   18
    table    10
    Thks for your answers

    I had to add schema name to the above script to make it work in AdventureWorks:
    CREATE TABLE #temp(TableName sysname , CNT BIGINT)
    DECLARE @QRY NVARCHAR(MAX);
    SET @qry=(SELECT
    N'INSERT INTO #TEMP SELECT '''+schema_name(t.schema_id)+'.'+T.[name] +''' AS TableName, COUNT (DISTINCT ProductID) DistCount FROM '+
    schema_name(t.schema_id)+'.'+t.[name] +';'
    FROM sys.schemas s INNER JOIN sys.tables t ON s.schema_id=t.SCHEMA_ID
    INNER JOIN sys.columns c ON t.object_id=c.object_id INNER JOIN sys.types d ON c.user_type_id=d.user_type_id
    WHERE c.name ='ProductID'
    FOR XML PATH(''))
    EXEC(@QRY)
    SELECT * FROM #temp ORDER BY TableName
    DROP TABLE #temp
    Production.Product 504
    Production.ProductCostHistory 293
    Production.ProductDocument 31
    Production.ProductInventory 432
    Production.ProductListPriceHistory 293
    Production.ProductProductPhoto 504
    Production.ProductReview 3
    Production.TransactionHistory 441
    Production.TransactionHistoryArchive 497
    Production.WorkOrder 238
    Production.WorkOrderRouting 149
    Purchasing.ProductVendor 211
    Purchasing.PurchaseOrderDetail 211
    Sales.SalesOrderDetail 266
    Sales.ShoppingCartItem 3
    Sales.SpecialOfferProduct 295
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Single query for displaying all but 1 column values for all tables

    Hi,
    All the tables have SYS_CREATION_DATE column.
    But I dont want to display this column value
    Can someone suggest some way in which i could achive this?
    Oracle version:11gR1
    OS:SunOS
    Cheers,
    Kunwar
    Edited by: user9131570 on Jul 6, 2010 7:57 PM

    user9131570 wrote:
    @Tubby
    I *want to display table-wise the values of all but 1(SYS_CREATION_DATE) columns in my database.*
    I need this in order to compare it to another database for all these values .Let me make a wild guess at what you are getting at.
    Given these two tables
    create table emp
       (empid number,
        empname varchar2(15),
        empaddr   varchar2(15),
        sys_creation_date date);
    create table dept
       (deptid number,
        deptmgr varchar2(10),
        sys_creation_date date);you want to somehow combine
    select empid,
             empname,
             empaddr
    from emp;with
    select deptid,
             deptmgr
    from dept;into a single sql statement?

  • All calendar entries for all accounts just duplicated today, how do I remove?

    Today, 10/9/14, when I opened Thunderbird I had to re-enter the gmail account passwords (I have multiple gmail accounts in Thunderbird and Lightening). After doing so, all the (1000's of) calendar events for all accounts are now duplicated. Am using the latest Lightening 3.3.1, Thunderbird 31.1.2. If I go to Google Calendar directly, there is no duplication so the problem (seems to be) that Lightening is reading in the events twice. Must be a simple edit to some profile file but which one and how to edit?

    Hmm - I don't use Mail (I use Outlook - and that's where my iCloud mail goes, too, never to Mail as I've never set it up in Mail).
    If you've deleted the iCloud account in Mail, you may want to check your iCloud System Preferences and make sure that you have "Mail" unchecked.
    But I don't know really... just another reason I don't use Mail, I guess.
    I DO know that I have a very personal account still active in Mail - but I only use it on Outlook 2013 for Windows, so I never get any alerts, etc. I don't know why you'd be getting any sort of error messages from Mail - unless it has something to do with iCloud preferences...
    Clinton

  • Query to find list of all tables relating to BP

    Hi,
    Is there any query which can generate list of all table names relating to BP?
    For example tables like BUT000,020,051 etc which are related to BP. I know a list of 14-15 table names but do not know the name of each and every field that is existing in BP.
    By writing a query can we get a list of all such table names for all the fields which appear in Field Grouping (which may be Role specfic)

    Hi Praveen,
    Well I am not aware of such query but if you want the CRM data model give me your mail ID i will send it to you in which you will find all the required details.
    Best regards,
    Vikash.

  • Creating synonys for all table

    i want to create synonyms for all atbles.the synonyn name and table name are same.instead creating one by one synonym i wnat to create all synonyms at a time.
    1)select 'CREATE PUBLIC SYNONYM'||' '||'test'||' '||'for' ||' '||'test' from dual
    2)select OBJECT_NAME from user_objects where OBJECT_TYPE ='TABLE'
    in the first query if we replace with test with 2nd query then we can get the script for that.
    i replaced that biut its not working how to do it

    Here is a generic grant script. If you review it, you will see how it works and can adapt it to your varying needs.
    BEGIN
        FOR x IN ( SELECT owner,
                          object_name,
                          DECODE(object_type, 'TABLE' ,   'select, insert, update, delete',
                                              'SEQUENCE', 'select',
                                              'VIEW',     'select',
                                                          'execute') AS privs,
                          DECODE (owner, 'SCHEMA_1', 'USER_1',
                                         'SCHEMA_2', 'ROLE_A'
                                          ) AS app_user
                     FROM dba_objects
                    WHERE object_type IN ('TABLE',    'PACKAGE', 'PROCEDURE',
                                          'FUNCTION', 'SEQUENCE', 'VIEW')
                      AND owner       IN ('SCHEMA_1', 'SCHEMA_2' ))
        LOOP
          BEGIN
            EXECUTE IMMEDIATE 'grant ' || x.privs       || ' on ' || x.owner ||
                              '.'      || x.object_name || ' to ' || x.app_user   ;
            EXECUTE IMMEDIATE 'create or replace synonym '|| x.app_user||'.'||x.object_name||
                               ' for ' ||x.owner||'.'||x.object_name ;
          EXCEPTION
            WHEN others THEN
              dbms_output.put_line('Bad owner = '||x.owner||';  Bad app_user='||x.app_user||
                                   ';  Bad object_name='||x.object_name);
          END;
        END LOOP;
    END;
    /

  • Sql query to find dependencies for a table

    Hi All,
    I am having a table (REPT_ALL) with dependent objects on it ( child tables, indexes, constraints, views, synonyms, sequences , packages,procedures,functions,triggers).
    I want the query to find out all the above dependencies for the above table(REP_ALL).
    I m looking for the query to find dependencies inorder to find out the risks before dropping the above table(drop table REP_ALL cascade constraints)?
    Thnx

    To find foreign key constraints for a table you cannot use DBA_DEPENDENCIES but you have to use DBA_CONSTRAINTS.
    Example Re: Find out foreign key column

  • How to tcack the table update event in sap for all tables by use of single

    Hello,
         I want to store the list of all OM,HR tables in a file which are updated after perticular date. For that i tried TRIGGER but i can write only one trigger for one table, i want such a that  i have to write only one trigger which will be invoked affter update operation on every HR,OM tables and i store information in a file  regarding which rows are updated and external application can use it.
    Thanks in advance,     
    SANDIP

    hi all the log for the change of any thing will be available in the tables DBTABLOG..REPOSRC ....
    regards,
    venkat.

Maybe you are looking for

  • Can I get the Trash and Send folder in IMAP

    Hi, I work now for a mail aplication using IMAP. I connect to Microsoft Exchange Server and my question is if there is a posibility to find which folder is the TRASH and which one is the SEND folder. The idea is that I can not use the name because I

  • Problem in pp order settlement

    I tried to settle production order system displays message "there are no accrued amounts;settlement is not possible where as when I go to cost-->analysis actual cost is visible in the order. The posting period is also correct. Can any body help me in

  • Help Please! Offline Clips!

    Ok here's my problem. I am using a clip of green screen footage that I have keyed out with two different backgrounds that I want to eventually layer on top of each other. Basically, it is the same clip on top of itself but with two different backgrou

  • Internet Explorer upgrade

    My HP Officejet 6110 works fine with Safari, but certain web sites come up in IE which won't work. The HP tech people advised me on the phone but couldn't resolve the problem, suggesting that it's an Apple problem. One suggested that I upgrade my IE

  • ADF BC deploy problem

    Hi, using JDeveloper 10.1.3.3. with Firebird database. I've created ADF BC application, added firebird jar to project. I am instantiating driver for database this way: Class.forName("org.firebirdsql.jdbc.FBDriver");This is my connection string: jdbc: