HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Get distinct of two columns

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
distincttwogetcolumns

Problem

I want to get distinct of two columns from an SQL table. Can I optimize this query?

create TABLE #Temporary_tbl
(                              
    ProductColour VARCHAR(50),
    ProductSize VARCHAR(20),
)

insert into #Temporary_tbl (ProductColour)
select distinct productcolour
from shoptransfer

insert into #Temporary_tbl (ProductSize)
select distinct ProductSize
from shoptransfer

select * from #Temporary_tbl

Solution

This will give you the same result as your sql.

select distinct ProductColour, null as ProductSize
from shoptransfer

union all

select distinct null as ProductColor, ProductSize
from shoptransfer


You don't actually need the "as" clause on the second select, but I find it good for readability.

Ultimatly, sql server will mostly be doing the same thing, but by removing the explicit temporary table and putting it all into one command, you give sql server a better chance of doing the two selects in parallel.

Code Snippets

select distinct ProductColour, null as ProductSize
from shoptransfer

union all

select distinct null as ProductColor, ProductSize
from shoptransfer

Context

StackExchange Code Review Q#1703, answer score: 5

Revisions (0)

No revisions yet.