14

I need to know how many records were returned in a select in oracle. Currently, I do two queries:

SELECT COUNT(ITEM_ID) FROM MY_ITEMS; SELECT * FROM MY_ITEMS; 

I need to know the COUNT but I hate doing two queries. Is there a way to do:

SELECT * FROM MY_ITEMS 

and then find out how many records are in there?

4 Answers 4

38

Is there a way to do:

SELECT * FROM MY_ITEMS 

and then find out how many records are in there?

If you want it to be in this exact order, you can fetch all records on the client and count their number (almost all client libraries provide a function for that).

You can also do:

SELECT i.*, COUNT(*) OVER () FROM my_items i 

, which will return you the count along with each record.

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

6 Comments

If you want to do this at the database level, I agree with the second suggestion. You can see an example here: download.oracle.com/docs/cd/B28359_01/server.111/b28286/…
Performance wise I think this should be the best solution. Thanks.
what if I need to put where clause inside over(), for example SELECT i.*, COUNT(*) OVER (where prod = 6) FROM my_items i
@user1512999: please post it as a separate question.
Essa é uma das coisas mais lindas que eu já vi! Não sei porque a resposta não foi aceita!
|
4

If you're working in PL/SQL, you can use the SQL%ROWCOUNT pseudo-variable to get the number of rows affected by the last SQL statement. Might save you some effort.

3 Comments

how to evaluate/get this variable value?
An example would be helpful.
@PeitiLi You have to use this pseudo-variable into PL scope. Like this dbms_output.put_line('Last select fetched ' || SQL%ROWCOUNT || ' rows');
2

This ought to do the trick.

WITH base AS ( SELECT * FROM MY_ITEMS ) SELECT (SELECT COUNT(*) FROM base) kount, base.* FROM base 

Comments

0

I'm just unsure about the table aliases, I don't remember in Oracle if they require 'AS' or not. But this should work.

select mt.*, c.Cntr from MyTable mt , (select COUNT(*) as Cntr from MyTable ) c 

1 Comment

The OP specifically requested a method that would not require two queries; munging the two queries into one, that still does exactly the same amount of extra unnecessary work, is not a great answer, IMHO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.