Search code examples
mysqlsqloracle-databasesybase

How to replace UNION in sql query


I have a table: attb

------------------------------------------------
Id | Name | Code | Attribute | Amount 
------------------------------------------------
1  | AV   | 123  | Alpha     | 233
------------------------------------------------
2  | TV   | 122  | Beta      | 235
------------------------------------------------
3  | TV   | 123  | Gama      | 238
------------------------------------------------
4  | CD   | 122  | Beta      | 239
------------------------------------------------
5  | TP   | 122  | Beta      | 240
------------------------------------------------
6  | RX   | 123  | Alpha     | 241
------------------------------------------------

I'm querying it as:

select id,name, code, attribute, amount
from attb
where code = 123 and attribute='Alpha'
UNION
select id,name, code, attribute, amount
from attb
where code = 122;

It return the following


Id | Name | Code | Attribute | Amount 
------------------------------------------------
1  | AV   | 123  | Alpha     | 233
------------------------------------------------
2  | TV   | 122  | Beta      | 235
------------------------------------------------
4  | CD   | 122  | Beta      | 239
------------------------------------------------
5  | TP   | 122  | Beta      | 240
------------------------------------------------
6  | RX   | 123  | Alpha     | 241
------------------------------------------------

Is there a way I can combine two queries instead of using UNION operator? or Any better implementation?


Solution

  • Just put both where clauses into one query:

    select id,name, code, attribute, amount
    from attb
    where (code = 123 and attribute='Alpha') 
       or code = 122;
    

    Output:

    id  name  code  attribute  amount
    1   AV    123   Alpha      233 
    2   TV    122   Beta       235 
    4   CD    122   Beta       239 
    5   TP    122   Beta       240 
    6   RX    123   Alpha      241 
    

    SQLFiddle demo