Skip to content
Advertisement

IN clause in select query with a subquery

I have a query where I join multiple tables. I would like to filter the results based on the status codes and I also want to get the records that were most recently created. Is the below SQL correct? Meaning – can I use IN clause for the statuscodes, or should it be three different queries, one for each status?

Advertisement

Answer

It’s not perfectly clear what you’re after (see my comments on the question). But my best guess is you can do this with an APPLY:

APPLY is like a correlated subquery/derived table in the SELECT clause, but it can be faster when you might have needed to use multiple subqueries against the same table. This allows us to only visit that table once to get both the DetailStatusCode and CreateTimeStamp columns. In Oracle and Postgresql this is called a LATERAL JOIN. These APPLY/Lateral join operations do not mix well with the old obsolete “A,B” join syntax, and is just one of many reasons not to use that old syntax.

Often the ROW_NUMBER() windowing function can also be used for even better performance, with a condition where the row number equals 1.

Note there was initially no meaningful JOIN condition for the Header table. The explicit JOIN syntax helps make this kind of error more obvious. I also had to infer what fields you needed from DetailStatus. As it was, the table served no purpose in the original query.

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