Intersect in SQL server

The functionality of intersect operator is that to get the common data from left and right queries.

Let us create two tables blog1 and blog2.

--------------------------------------------------------------------------------------------------------------------------
Create Table blog1
(
    Id int primary key,
    Name nvarchar(100),
    Gender nvarchar(100)
)
Go

Insert into blog1 values (1, 'sai', 'M')
Insert into blog1 values (2, 'xxx', 'F')
Insert into blog1 values (3, 'dummu', 'M')
Insert into blog1 values (4, 'vijendhar', 'M')
Insert into blog1 values (5, 'yyy', 'F')
Go
-------------------------------------------------------------------------------------------------------------------
Create Table blog2
(
    Id int primary key,
    Name nvarchar(100),
    Gender nvarchar(100)
)
Go

Insert into blog2 values (4, 'vijendhar', 'M')
Insert into blog2 values (5, 'yyy', 'F')
Insert into blog2 values (6, 'sindu', 'F')
Insert into blog2 values (7, 'vinni', 'F')
Insert into blog2 values (8, 'kalyan', 'M')
Go
---------------------------------------------------------------------------------------------------------------------
Now execute both the tables.

select * from blog1
select * from blog2

------------------------------------------------------------------------------------------------------------------


Now execute the following query.

select id, name, gender from blog1
intersect
select id, name, gender from blog2

Now the result will be as follows.




The same thing we can achieve by using the  JOIN concept.

select blog1.id,blog1.name,blog1.gender from blog1 join blog2 on blog1.id=blog2.id


No comments:

Post a Comment

What is Normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help building relational dat...