sql - Should I use Top(1) in a SubQuery -


Example query:

  Join A * from AID = B on ABB. Some evolutions where A.VALUE = "some" and BID = (select ID from B where SOMEVALUE = AID and THISDATE = (where B select the maximum (SOMEDATE) ...))  < / Pre> 

So, if you can read SQL, then you should see that I am doing some correlated subkey to reduce the results of the addition. (And yes, it's too much-simplified).

In some cases, choose the ID from subquery:

  B where SOMEVALUE = AID and THISDATE = (select B to max (SOMEDATE) where ...)  

can return more than 1 value, which causes an error

"value greater than subkey 1. When subquery = =,! =, & Lt;, & lt; =,>,> = or when the subquery is used as an expression it is not allowed.

Which I completely expect This is clearly not a good thing and my The code is (hopefully) preventing these duplicates from going to the first place in the database (i.e. table b should only have one row

  SOMEVALUE = AID and Maximum (SOMEDATE)  

criteria), though the end users are nothing that is not creative. To break the software.

Now for my question:

To change the first bit, choose

 from  would be better than the top 1 * b ...  

sub Ogkrta to stop seeing this error when / if (hopefully never) it comes from does not occur in the case or via error. I am leaning to add the top statement and the error comes, rather let the user see potentially incorrect data. I am thinking that if anyone has any thoughts on best practices in such a situation ...

Think with millions of rows on which you are matching, there is no indication on it, although you are looking for only one line.

SELECT Top1 will mean that as soon as the table prevents the scan as an item.

Without the top 1, the table scan will continue from the end.

Anything involves scanning (or brute force) to search in it. Using the top 1, this should be 50% more than the average not exceeding 1%.

However, depending on the need to return to you, actual performance gains can usually be done using EXISTS.

Instead of typing

  to SELECT *, the table T. WHERE t.id = (Top 1 foreigner above table 2)  

You can use

  Select from the table where it exists (Table 2 WHERE foreignid = SELECT 1 from T.ID)  

Comments