Q
Problem solve Get help with specific problems with your technologies, process and projects.

Exactly one row? At least one row? (Part 2)

Here is the rest of Rudy's response. (See part one.)

To summarize, if you want at least some number of rows, use an inequality in the HAVING clause of the IN?(subquery). If you want at least one row, the HAVING clause is redundant, and you should use an EXISTS?(subquery):

select id , loc_numb , loc_prec from item_loc xx where id in ( select id from item_loc where loc_prec = 'S' group by id having count(*) = 1 ) and exists ( select 1 from item_loc where id = xx.id and loc_prec = 'P' )

Note that the EXISTS subquery is correlated. The EXISTS syntax gives the database optimizer a chance to improve performance, since the EXISTS subquery will be true as soon as the first row is found. As soon as the row is found, grouping is not necessary.

In summary, use EXISTS if you are looking for one or more rows. If you want exactly some number, including one, or at least some number where the number is two or more, then grouping is necessary, and you can't use EXISTS.


This was last published in October 2002

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close