How to get row count of a sql query

After firing a query, how can i get the number of records returned by the query from the database, it should be database indipendent.
Statement stmt = conn.createStatement();
                  stmt.executeQuery(query);After this I want the number of row i.e. the number of records returned by the database.

Number of rows in a ResultSet may be obtained with:
ResultSet rs;
int numRows=rs.last().getRow();
I would have said this too, as a matter of fact I mentioned scrollable result sets in my post, but as I said, not all drivers support this, and he said he needed it to be database independent, so this method should not be used.

Similar Messages

  • How to get row count(*) for each table that matches a pattern

    I have the following query that returns all tables that match a pattern (tablename_ and then 4 digits). I also want to return the row counts for these tables.
    Currently a single column is returned: tablename. I want to add the column RowCount.
    DECLARE @SQLCommand nvarchar(4000)
    DECLARE @TableName varchar(128)
    SET @TableName = 'ods_TTstat_master' --<<<<<< change this to a table name
    SET @SQLCommand = 'SELECT [name] as zhistTables FROM dbo.sysobjects WHERE name like ''%' + @TableName + '%'' and objectproperty(id,N''IsUserTable'')=1 ORDER BY name DESC'
    EXEC sp_executesql @SQLCommand

    The like operator requires a string operand.
    http://msdn.microsoft.com/en-us/library/ms179859.aspx
    Example:
    DECLARE @Like varchar(50) = '%frame%';
    SELECT * FROM Production.Product WHERE Name like @Like;
    -- (79 row(s) affected)
    For variable use, apply dynamic SQL:
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Rows count all tables:
    http://www.sqlusa.com/bestpractices2005/alltablesrowcount/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • How to get index fragmentation percentage by sql query

    hi, experts, I built some indexes in my database. the database is not accessible by me. it is by DBA. I could not ask him to use interface on management studio to check every indexes fragmentation percentage everyday. is there any sql queries to get the  index
    fragmentation percentage?
    then I could write a sql and execute from a windows scheduler to export report everyday.
    the sql server version is 2005
    Thank you very much!

    hi
    check this link: http://gallery.technet.microsoft.com/scriptcenter/Check-SQL-Server-a-a5758043
    SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
    ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
    indexstats.avg_fragmentation_in_percent
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
    INNER JOIN sys.indexes ind
    ON ind.object_id = indexstats.object_id
    AND ind.index_id = indexstats.index_id
    WHERE indexstats.avg_fragmentation_in_percent > 30
    ORDER BY indexstats.avg_fragmentation_in_percent DESC
    [Personal Site] [Blog] [Facebook]

  • How to get the desire output from sql query

    Consider an Order Table: ...
    Order Table:
    Order Id Item Qty
    O1 A1 5
    O2 A2 1
    O3 A3 3
    Please provide SQL which will explode the above data into single unit level records as shown below
    Desired Output:
    Order Id Order Id Qty
    O1 A1 1
    O1 A1 1
    O1 A1 1
    O1 A1 1
    O1 A1 1
    O2 A2 1
    O3 A3 1
    O3 A3 1
    O3 A3 1

    How do I ask a question on the forums?
    SQL and PL/SQL FAQ

  • GETTING ROW COUNTS OF ALL TABLES AT A TIME

    Is there any column in any Data dictionary table which gives the row counts for particular table..
    My scenario is...i need to get row counts of some 100 tables in our database...
    instead of doing select count(*) for each table....is there any way i can do it?
    similary How to get column counts for each table..in database .For example
    Employee table has 3 columns...empid,empname,deptno....i want count(empid),
    count(empname),count(deptno) ...is there any easy way for finding all column counts of each table in data base? is it possible?

    Why does "select count(mgr) from emp" return null and not 13?Good question ;)
    Seems that xml generation in principle can't handle »counting nulls«:
    SQL> select xmltype(cursor(select null c from dual)) x from dual
    X                                                
    <?xml version="1.0"?>                            
    <ROWSET>                                         
    <ROW>                                           
    </ROW>                                          
    </ROWSET>                                        
    1 row selected.
    SQL> select cursor(select count(null) c from dual) x from dual
    Cur

    1 row selected.
    SQL> select xmltype(cursor(select count(null) c from dual)) x from dual
    select xmltype(cursor(select count(null) c from dual)) x from dual
    Error at line 1
    ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00229: input source is empty
    Error at line 0
    ORA-06512: at "SYS.XMLTYPE", line 0
    ORA-06512: at line 1
    but
    SQL> select xmltype(cursor(select count(1) c from dual)) x from dual
    X                                                
    <?xml version="1.0"?>                            
    <ROWSET>                                         
    <ROW>                                           
      <C>1</C>                                       
    </ROW>                                          
    </ROWSET>                                        
    1 row selected.Looks like a bug to me ...

  • Trying to get row counts for all tables at a time

    Hi,
    i am trying to get row counts in database at a time with below query but i am getting error:
    its giving me ora-19202 error..please advise me
    select
          table_name,
          to_number(
            extractvalue(
              xmltype(dbms_xmlgen.getxml('select count(*) c from '||table_name))
              ,'/ROWSET/ROW/C')
              count
        from all_tables;

    ALL_TABLES returns tables/views current user has access to. These tables/views are owned not just by current user. However your code
    dbms_xmlgen.getxml('select count(*) c from '||table_name)does not specify who the owner is. You need to change it to:
    dbms_xmlgen.getxml('select count(*) c from '||owner || '.' || table_name)However, it still will not work. Why? As I said, ALL_TABLES returns tables/views current user has access to. Any type of access, not just SELECT. So if current user is, for example, granted nothing but UPDATE on some table the above select will fail. You would have to filter ALL_TABLES through ALL_SYS_PRIVS, ALL_ROLE_PRIVS, ALL_TAB_PRIVS and PUBLIC to get list of tables current user can select from. For example, code below does it for tables/views owned by current user and tables/views current user is explicitly granted SELECT:
    select
          t.owner,
          t.table_name,
          to_number(
            extractvalue(
              xmltype(dbms_xmlgen.getxml('select count(*) c from '||t.owner || '.' || t.table_name))
              ,'/ROWSET/ROW/C')
              count
        from all_tables t,user_tab_privs p
        where t.owner = p.owner
          and t.table_name = p.table_name
          and privilege = 'SELECT'
    union all
    select
          user,
          t.table_name,
          to_number(
            extractvalue(
              xmltype(dbms_xmlgen.getxml('select count(*) c from '||t.table_name))
              ,'/ROWSET/ROW/C')
              count
        from user_tables t
    OWNER                          TABLE_NAME                                                          COUNT
    SCOTT                          DEPT                                                                    4
    U1                             QAQA                                                                    0
    U1                             TBL                                                                     0
    U1                             EMP                                                                     1
    SQL> SY.

  • How about get item count of table in formGroup.vm

    JHeadstart Team:
    I want change maxColumns=" 1" or" 2" by item count of table .but I do not know how about get item count of table .
    #if (${JHS.current.group.columns} > 10)
    #set ($majin = 2)
    #else
    #set ($majin = 1)
    #end
    <af:panelForm rows="1" maxColumns="$majin" width="${JHS.current.group.formWidth}" id="${JHS.current.group.shortName}FormItems">
    majin
    #FORM_ITEMS()
    </af:panelForm>

    You can do this using the following syntax:
    #if (${JHS.current.itemContainer.items.size()}>10)
    maxColumns="2"
    #else
    maxColumns="1"
    #end
    Steven Davelaar,
    Jheadstart Team

  • How to get Listener Information using PL/SQL code

    How to get Listener Information using PL/SQL code

    user2075318 wrote:
    How to get Listener Information using PL/SQL codeThis approach (somewhat of a hack) can be used - but it does not really provide meaningful data at application layer.
    SQL> create or replace function TnsPing( ipAddress varchar2, port number default 1521 ) return varchar2 is
      2          type THexArray is table of varchar2(2);
      3          --// tnsping packet (should be 10g and 11g listener compatible)
      4          TNS_PING_PACKET constant THexArray := new THexArray(
      5                  '00', '57', '00', '00', '01', '00', '00', '00',
      6                  '01', '39', '01', '2C', '00', '00', '08', '00',
      7                  '7F', 'FF', '7F', '08', '00', '00', '01', '00',
      8                  '00', '1D', '00', '3A', '00', '00', '00', '00',
      9                  '00', '00', '00', '00', '00', '00', '00', '00',
    10                  '00', '00', '00', '00', '00', '00', '00', '00',
    11                  '00', '00', '00', '00', '00', '00', '00', '00',
    12                  '00', '00', '28', '43', '4F', '4E', '4E', '45',
    13                  '43', '54', '5F', '44', '41', '54', '41', '3D',
    14                  '28', '43', '4F', '4D', '4D', '41', '4E', '44',
    15                  '3D', '70', '69', '6E', '67', '29', '29'
    16          );
    17 
    18          socket  UTL_TCP.connection;
    19          txBytes number;
    20          rxBytes number;
    21          rawBuf  raw(1024);
    22          resp    varchar2(1024);
    23  begin
    24          socket := UTL_TCP.open_connection(
    25                          remote_host => ipAddress,
    26                          remote_port => port,
    27                          tx_timeout => 10
    28                  );
    29 
    30          --// convert hex array into a raw buffer
    31          for i in 1..TNS_PING_PACKET.Count loop
    32                  rawBuf := rawBuf || HexToRaw( TNS_PING_PACKET(i) );
    33          end loop;
    34 
    35          --// send packet
    36          txBytes := UTL_TCP.write_raw( socket, rawBuf, TNS_PING_PACKET.Count  );
    37 
    38          --// read response
    39          rxBytes := UTL_TCP.read_raw( socket, rawBuf, 1024 );
    40 
    41          UTL_TCP.close_connection( socket );
    42 
    43          --// convert response to varchar2
    44          resp := UTL_RAW.Cast_To_Varchar2( rawBuf );
    45 
    46          --// strip the header from the response and return the text only
    47          return( substr(resp,13) );
    48  end;
    49  /
    Function created.
    SQL>
    SQL> select tnsping( '10.251.93.30' ) as TNSPING from dual;
    TNSPING
    (DESCRIPTION=(TMP=)(VSNNUM=169869568)(ERR=0)(ALIAS=LISTENER))
    SQL> select tnsping( '10.251.95.69' ) as TNSPING from dual;
    TNSPING
    (DESCRIPTION=(TMP=)(VSNNUM=0)(ERR=0)(ALIAS=LISTENER))
    SQL>

  • How to get attendies count for a calendar list in sharepoint 2013?

    Hi everybody,
    I am using calendar list in SharePoint 2013 for my project.
    Could please tell me how to get the count of attendees using SP Designer or OOTB calculated field.
    Because I want to display the fields like
    TOTAL SEATS =20
    Attendees= Need count
    Avail seats= total - Attendees count.
    In that way I want to show information about availability seats for training session.
    Regards,
    Dhayanand

    Hi Dhaya
    Please refer the links.Hope it helps :-)
    http://social.msdn.microsoft.com/Forums/en-US/b8677dc5-3eb1-4bdc-92f2-f57201bfabb1/field-that-counts-attendees?forum=sharepointcustomizationprevious
    http://sharepoint.stackexchange.com/questions/54253/use-count-related-column-value-as-int-in-a-sp-designer-workflow

  • How to get row number of selected entry from OVS search result

    Hi,
    Anyone having any idea on how to get row number of the  selected entry/ how to differentiate rows in OVS search result in ON_OVS method?
    Regards,
    Jatin

    Hi,
    You can get the selected record to <ls_selection> structure in co phase 3.
    From that structure you can get what ever field you want.,
    check the below code for reference,
    << Moderator message - Cut and paste response from F4 help for ALV table field removed. Plagiarism is not allowed in SCN >>
    hope this helps u.,
    Thanks & Regards,
    Kiran
    Edited by: Rob Burbank on Jan 5, 2012 5:24 PM

  • Multi Mapping : How to get Message count after splitting

    Hi all,
    I am following below blog.
    /people/narendra.jain/blog/2005/12/30/various-multi-mappings-and-optimizing-their-implementation-in-integration-processes-bpm-in-xi
    Can any body please tell me how to get the count of messages generated after splitting in the message mapping.. I have created the message data type but not aware what is needed to be done.
    Thanks and best regards,
    Kulwant Singh

    Multi mappings r done in order to split the messages to the number of messages required by the user. So for 1:N mapping, the details about "N" is based on ur requirement. So its not like - when u split, any number of message could get created. The count would be dependent on u.
    Regards,
    Prateek

  • How to get file count in variable?

    dear all,
    how to get file count in variable?
    regards
    Naseer

    Hi Nazeer ,
    It wont take much time .. so simple :- )
    Create one os comand step
    ( for unix) Use
    wc -l filename.txt > someoutputfile.txt
    Now the number of lines in your file will be there in the output file ( someoutputfile.txt )
    Step2 :-
    Now use Cezar's logic to fetch the variable value ( file count ) from the output file .. ( select value for a variable from a file )
    This will not take eeven a second to finish the job.
    Regards,
    Rathish A M

  • How to get Page Count of pdf in Document library in EventHandler

    Hi,
    How to get Page Count of pdf in Document library once uploaded has been done and i would like to update the page count value in document library column of the corresponding file.
    I should achieve it in Event handler.
    Which even should i use, either ItemAdded or "ItemUpdated "?
    Thanks & Regards
    Poomani Sankaran.

    Hello,
    If you are looking for file download or view count then event handler will not work. You need to enable the analytic report to your site. Once you enable it then you can see the report within a browser or you can also create custom webpart to show count
    of specific file.
    http://blogs.msdn.com/b/ecm/archive/2010/05/03/web-analytics-in-sharepoint-2010-insights-into-reports-and-metrics.aspx
    http://sharepoint.stackexchange.com/questions/34611/count-of-files-under-a-folder-in-a-document-library
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • How to convert rows to columns in sql server 2008

    How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

    Lookup the Pivot transformation. From BOL:
    The Pivot transformation makes a normalized data set into a less normalized
    but more compact version by pivoting the input data on a column value. For
    example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
    details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
    single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
    null values.
    When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
    The column is passed through unchanged to the output. Because many input rows
    can result only in one output row, the transformation copies only the first
    input value for the column.
    The column acts as the key or part of the key that identifies a set of
    records.
    The column defines the pivot. The values in this column are associated with
    columns in the pivoted dataset.
    The column contains values that are placed in the columns that the pivot
    creates.
    Paul

  • How to get row number in the fetch row itself in Sql Query ?

    Hi,
    i am fetching some rows from a sql query . Is there any way to get row number as well in each row while all rows are fetched ?
    like this :
    RowNum data1 data2
    1 abc ere
    2 bnh ioi

    Hello
    Ofcourse you can get the rownum inside a query, just keep in mind that the rownum is the number of order in which the records were fetched from the table, so if you do an order by, the rownum will not be sequential, unless you query the information in a subquery first.
    SELECT rown, col1, col1
    FROM table
    Or
    SELECT rownum, col1, col2
    FROM (SELECT col_1, col_2 FROM table ORDER BY col1)
    Regards
    Johan

Maybe you are looking for