Thursday, August 18, 2022

How to get distinct records without using distinct keyword

 In this article we are going to see how to retrieve unique records from the data table without using the distinct keyword in microsoft sql server.

We can get the unique records from table without using distinct keyword by the following ways:-

  • By Group by
  • By Union 
  • By Intersection
  • By CTE and row_number() function  
Now create sample data table in sql server.



Retrieve the data
  
SELECT * from tblDistinct 


Now get distinct records by using the GROUP BY 

select _value from tblDistinct group by _value



Now get unique records by using the UNION

select _value from tblDistinct
union
select _value from tblDistinct

Now get unique records by using the INTERSECT
select _value from tblDistinct
intersect
select _value from tblDistinct


Now get unique records by using the CTE

with cte (_value, _count)
as
(select _value , ROW_NUMBER() over (partition by _value order by _value ) as _count from tblDistinct)
select * from cte where _count=1;

No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...