Skip to content
Advertisement

How do I do this without a subquery?

enter image description here

SELECT COUNT(*) FROM org_type_on_related_genre 
WHERE genre_id = :deletedGenreId 
and org_type_id IN 
(SELECT org_type_id 
 FROM org_type_on_related_genre 
 GROUP BY org_type_id 
 HAVING count(*) > 1)

I need to make the same query, but without a subquery!

I need to get the count of rows in which genre_id is equal to the :deletedGenreId and the org_type_id value of this line in this table is not unique

Advertisement

Answer

There is nothing wrong with sub-query. Sub-query actually can help boost performance and increase code readability if you do it correctly. It is indispensable for complicated logic.

What we generally want to get rid of is correlated sub-query, like the one in your script. The following query implement the same logic as yours without correlated sub-query:

with dup_org_type as (
select org_type_id
  from org_type_on_related_genre
 group
    by org_type_id
having count(0) > 1 
)
select count(0)
  from org_type_on_related_genre otrg
      ,dup_org_type dup
 where otrg.genre_id = :deletedgenreid
   and otrg.org_type_id = dup.org_type_id

If the table is big, there are many different org_type_id, and deletedgenreid is very selective, your script will actually have better performance. It all depends on the volume of data the query needs to touch.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement