1

I'm trying to build a query or a PL/SQL code to both execute a query, as well as return the number of results of this query.

Is this possible in a single query? Right now I feel like I'm being very wasteful: I first wrap the query in a COUNT (without ORDER BY) and then run the same query again (without the COUNT). A difference of a few seconds will probably not change the total number of rows, I can live with that. The DB I'm using is Oracle Enterprise 12.2

2
  • 3
    why don't you use %ROWCOUNT , if you are using PL-SQL Commented Mar 7, 2019 at 13:53
  • Please provide the the primary query. Commented Mar 7, 2019 at 14:02

3 Answers 3

7

An easy SQL way: a test table:

create table testTable(a, b, c) as (
    select 1, 'one',   'XX' from dual UNION ALL
    select 2, 'two',   'YY' from dual UNION ALL
    select 3, 'three', 'ZZ' from dual
)

A simple query:

select a, b, c
from testTable 

         A B     C 
---------- ----- --
         1 one   XX
         2 two   YY
         3 three ZZ

3 rows selected.

The query with the number of records :

select a, b, c, count(*) over (partition by 1) as count
from testTable


         A B     C       COUNT
---------- ----- -- ----------
         1 one   XX          3
         2 two   YY          3
         3 three ZZ          3

3 rows selected.
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. This works great! What does the "1" mean here?
I used 1 to have a constant value, so that data are partitioned by a constant value, that is are not partitioned; you could use whatever constant you want
1

You can try to do something like:

WITH test_query
  AS (SELECT LEVEL just_a_number
        FROM dual
       CONNECT BY level < 101)
SELECT just_a_number
     , COUNT(just_a_number) OVER (ORDER BY 1) total_count
  FROM test_query;

Where COUNT(just_a_number) OVER (ORDER BY 1) will return total number of rows fetched in each row. Note that it may slow down the query.

Comments

1

Typically, when I do something like this, I create a stored procedure that returns 2 values. The first would be the result set as a REF CURSOR, and the other a number(12,0) returning the count. Both would of course require separate queries, but since it is in a single stored procedure, it is only one database connection and command being executed.

You are of course right for having your COUNT query forgo the ORDER BY clause.

To answer your question, you are not being wasteful per se. This is common practice in enterprise software.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.