views:

231

answers:

3

Which of the following queries are correct

SELECT
 ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
WHERE
 STATUS IN('OPEN','UPDATED')
AND
 ITEM_TYPE IN ('ITEM1','ITEM2')
AND
 CREATED_TIME BETWEEN 'XX' AND 'YY'
AND
 UPDATED_TIME BETWEEN 'XX' AND 'ZZ'

 SELECT
         ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
 WHERE
         STATUS IN('OPEN','UPDATED')
 JOIN

 SELECT
         ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
 WHERE
         ITEM_TYPE IN ('ITEM1','ITEM2')
 JOIN

 SELECT
         ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
 WHERE
         CREATED_TIME BETWEEN 'XX' AND 'YY'
 JOIN

 SELECT
         ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
 WHERE
         UPDATED_TIME BETWEEN 'XX' AND 'ZZ'
A: 

The first is correct, unless you want an exponential explosion of self-joins.

Paul Tomblin
what I heard if UNION will return distinct rows and UNIONALL returns exponential explosin, please correct me if I am wrong
Subbu
You're not doing a UNION, you're doing a JOIN.
Paul Tomblin
I am sorry about the second QUERY, SO if I use union I should get the expected resultsSELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME WHERE STATUS IN('OPEN','UPDATED') UNION SELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME WHERE ITEM_TYPE IN ('ITEM1','ITEM2') UNION SELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME WHERE CREATED_TIME BETWEEN 'XX' AND 'YY' UNION SELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME WHERE UPDATED_TIME BETWEEN 'XX' AND 'ZZ'
Subbu
I very much doubt you'll get what you want. Why won't you just do the first query, if it works?
Paul Tomblin
A: 

The first query is correct, the second would give, well....a LOT of reuslts.

In response to your comment, as SQLMenace pointed out, use OR instead if you want to match any of the conditions:

SELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
WHERE STATUS IN('OPEN','UPDATED')
   OR ITEM_TYPE IN ('ITEM1','ITEM2')
   OR CREATED_TIME BETWEEN 'XX' AND 'YY'
   OR UPDATED_TIME BETWEEN 'XX' AND 'ZZ'

Or, if you wanted to always restrict on the time, but meet either of the first conditions, then use a wrapped OR:

SELECT ID, STATUS, ITEM_TYPE,CREATED_TIME,UPDATED_TIME
WHERE (STATUS IN('OPEN','UPDATED') OR ITEM_TYPE IN ('ITEM1','ITEM2'))
  AND CREATED_TIME BETWEEN 'XX' AND 'YY'
  AND UPDATED_TIME BETWEEN 'XX' AND 'ZZ'
Nick Craver
Thank you for the response, but the problem what I am encountering is if any one condition fails, query does not return any values. for example if there are no matching rows for updated_time no rows are returned even all other conditions are matching
Subbu
In that case use OR not AND
SQLMenace
A: 

the first one

JOINS have to be before the WHERE clause

although you could rewrite the JOINS with EXISTS and then you cut put it in the WHERE clause

SQLMenace
can you please provide an example
Subbu