Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Raja.

Asked: January 11, 2018 - 7:15 pm UTC

Last updated: January 13, 2018 - 3:51 am UTC

Version: oracle 9

Viewed 1000+ times

You Asked

Hi TOM,

First of all, Thank you very much for helping the Oracle community. Well, I write SQL queries, but they are limited to entry level only. My question is related with UNION. Below is my SQL query. It works fine, but I am struggling to find a better solution than using UNION.

--##################################################################################################################################
select * from TEST_TABLE tst_table where tst_table.access = 'PUBLIC' AND tst_table.company='X'
UNION
select * from TEST_TABLE tst_table where tst_table.access = 'PRIVATE' AND tst_table.owner='joe'
UNION
select * from TEST_TABLE tst_table where tst_table.access = 'EXECUTIVE' AND tst_table.role='EXECUTIVE_ROLE' AND tst_table.company='X'
--##################################################################################################################################

access, company, owner, role are columns in TEST_TABLE.

Any better solution with respect to best practice to fetch same results WITHOUT using UNION.

Thank you in advance,
Raj.

and Connor said...

A simple OR should suffice

select * from TEST_TABLE tst_table 
where ( tst_table.access = 'PUBLIC' AND tst_table.company='X' )
or ( tst_table.access = 'PRIVATE' AND tst_table.owner='joe' )
or ( tst_table.access = 'EXECUTIVE' AND tst_table.role='EXECUTIVE_ROLE' AND tst_table.company='X' )


Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Better than UNION

Raja Achanta, January 12, 2018 - 5:24 am UTC

Hi Connor,

Thanks for the reply. It worked well and fetch the results quick. Appreciate your help. Thank you.
Connor McDonald
January 13, 2018 - 3:51 am UTC

glad we could help

Might need a disitinct

Don Thomson, January 12, 2018 - 8:05 am UTC

As it is UNION not UNION ALL the result set will have only distinct rows so depending on the original data you might need a distinct in the answer SQL
Connor McDonald
January 13, 2018 - 3:51 am UTC

good point

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.