Fredrik Hases
Fredrik Hases

Reputation: 27

Oracle SQL COUNT in an EXISTS SELECT

I want to create a query where I get all posts from my table INV where the INNUM exists more than 2 times in table INVS. This is my query right now, but it fails with the typical "missing right parenthesis" error. But when I run the EXISTS Query isolated, it works....

SELECT WO.WONUM, WO.DESCRIPTION, INV.INNUM, INV.STATUSDATE
     FROM INV LEFT OUTER JOIN WO ON INV.WOID = WO.WOID
     WHERE EXISTS (
      SELECT COUNT(*) FROM INVS WHERE INVS.INNUM = INV.INNUM and INVS.SITEID='ARZ' GROUP BY INVS.INNUM
      HAVING COUNT(*) > 2 ORDER BY INVS.INNUM
     );

I dont really know why!?

Upvotes: 1

Views: 1729

Answers (2)

Marmite Bomber
Marmite Bomber

Reputation: 21073

You get ORA-00907: missing right parenthesis while using the ORDER BYclause in the subquery.

Remove it and you get a valid syntax

Example

with tab as (select rownum id from dual connect by level <= 5
union all
select 3 from dual union all
select 5 from dual)
select * from tab t
where exists
(select count(*) from tab 
 where id = t.id
 group by id
 having count(*) > 1)
;

        ID
----------
         3
         5
         3
         5

This is not a valid syntax --> ORA-00907: missing right parenthesis

select * from tab t
where exists
(select count(*) from tab 
 where id = t.id
 group by id
 having count(*) > 1 order by id)

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269773

Hmmm . . . use a scalar subquery to calculate the count and compare to "2" in the outer query:

SELECT WO.WONUM, WO.DESCRIPTION, INV.INNUM, INV.STATUSDATE
FROM INV LEFT OUTER JOIN
     WO
     ON INV.WOID = WO.WOID
WHERE (SELECT COUNT(*)
       FROM INVS
       WHERE INVS.INNUM = INV.INNUM AND
             INVS.SITEID = 'ARZ' 
      ) > 2;

Your query is relying on a doubly nested correlation clause which Oracle does not support.

You could also move the subquery to the FROM clause, but this version is more in the spirit of how you have written the query.

Upvotes: 1

Related Questions