Search code examples
sqluniquedistinct

Select DISTINCT or UNIQUE records or rows in Oracle


I want to select distinct or unique records from a database I am querying. How can I do this but at the same time select the entire record instead of just the column that I am distinguishing as unique? Do I have to do unruly joins?


Solution

  • If you want only one column out of several to be unique and you have joins that might include multiple records, then you have to determine which of the two or more values you want the query to provide. This can be done with aggregate functions, with correlated sub-queries or derived tables or CTEs (In SQL Server not sure if Oracle has those).

    But you have to determine which value you want before you write the query. Once you know that then you probably know how to get it.

    Here are some quick examples (I used SQL Server coding conventions but most of this should make sense in Oracle as it is all basic SQL, Oracle may have a different way of declaring a parameter):

    select a.a_id, max (b.test) , min (c.test2)
    from tablea a 
    join tableb b on a.a_id = b.a_id
    join tablec c on a.a_id = c.a_id
    group by a.a_id
    order by b.test, c.test2
    
    Select a.a_id, (select top 1 b.test from tableb b where a.a_id = b.a_id order by test2),
    (select top 1 b.test2 from tableb b where a.a_id = b.a_id order by test2),
    (select top 1 c.test3 from tablec c where a.a_id = c.a_id order by test4)
    from tablea a   
    
    declare @a_id int
    set @a_id = 189
    select a.a_id , b.test, b.test4
    from tablea a 
    join tableb b on a.a_id = b.a_id
    join (select min(b.b_id) from tableb b where b.a_id = @a_id order by b.test3) c on c.b_id = b.b_id
    where a.a_id = @a_id