WmZilla - Webmaster and Marketplace

The Next Generation Webmaster and Trade Forum

Usage of SQL Server Except (Difference) and Intersect (Intersection)

DaySmilEe

New member

0

0%

Status

Offline

Posts

35

Likes

0

Rep

0

Bits

185

3

Months of Service

0%
In our SQL work, we will see the use of Except and Intersect, which are necessary and somewhat mathematical operations. As you may remember from mathematics, these are similar to the concepts of intersection and union in "Sets". For example, let's consider a company with two types of employees: Managers and Workers. However, in this company, there is a situation where "A manager can also work as a worker." Let's try to create a Managers and Workers chart using SQL. Let's have two simple tables. Our first table will be named "Managers" where we will store the names and surnames of the managers working at the company.

Managers Table
```sql
CREATE TABLE [dbo].[Managers] (
[manager_ID] INT PRIMARY KEY NOT NULL IDENTITY(1,1),
[full_name] varchar(100) NULL
)

INSERT INTO [dbo].[Managers] ([full_name]) VALUES ('AHMED SAY');
INSERT INTO [dbo].[Managers] ([full_name]) VALUES ('MURAT PEK');
INSERT INTO [dbo].[Managers] ([full_name]) VALUES ('SERKAN TOY');
INSERT INTO [dbo].[Managers] ([full_name]) VALUES ('VEDAT SAPMAZ');
INSERT INTO [dbo].[Managers] ([full_name]) VALUES ('NIHAT DOGRU');
```

Our second table will be named "Workers" where we will store the names and surnames of the workers working at the company.

Workers Table
```sql
CREATE TABLE [dbo].[Workers] (
[worker_ID] INT PRIMARY KEY NOT NULL IDENTITY(1,1),
[full_name] varchar(100) NULL
)

INSERT INTO [dbo].[Workers] ([full_name]) VALUES ('KENAN SOLAK');
INSERT INTO [dbo].[Workers] ([full_name]) VALUES ('VEYSEL TANIR');
INSERT INTO [dbo].[Workers] ([full_name]) VALUES ('NIHAT DOGRU');
// More INSERT commands...
```

Example 1: Let's find individuals who are both workers and managers. In other words, let's find the intersection set.

Intersection Example Query
```sql
SELECT full_name FROM Workers INTERSECT SELECT full_name FROM Managers
```

Example 2: Let's find individuals who are workers but not managers. In other words, let's find the except set.

Except Example Query
```sql
SELECT full_name FROM Workers EXCEPT SELECT full_name FROM Managers
```

Example 3: Let's find individuals who are managers but not workers. In other words, let's find the except set.

Except Example Query
```sql
SELECT full_name FROM Managers EXCEPT SELECT full_name FROM Workers
```

Hope you have a query-filled day :) Source: [Link](https://www.ontedi.com/sql/sql-server-except-fark-ve-intersect-kesisim-kullanimi)
 

249

6,622

6,642

Top