In today’s article, we will be discussing the Intersect command, which allows us to see the common data present in both tables.
It will be understood better through examples.
First, let’s create our database.
1 | create database okul; |
After creating the database, let’s connect to the database as follows.
1 | \c okul |
If you see the image below after connecting to the database, it means that you are connected correctly.
Let’s create a database named class and course within the school database.
1 2 | create table sinif(ders varchar(50),sinif varchar(10)); create table ogrenci(id int,adi varchar(60),soyadi varchar(60),sinif varchar(10)); |
We have created two tables and now let’s enter data into them:
1 2 3 4 5 6 | insert into ogrenci(id,adi,soyadi,sinif) values (1,'faruk','erdem','10-A'); insert into ogrenci(id,adi,soyadi,sinif) values (2,'nalan','erdem','10-A'); insert into ogrenci(id,adi,soyadi,sinif) values (3,'ayse','sari','11-B'); insert into ogrenci(id,adi,soyadi,sinif) values (4,'aslı','ar','12-B'); insert into sinif(ders,sinif) values ('Matematik','10-A'); insert into sinif(ders,sinif) values ('Fizik','11-B'); |
Assuming you have done everything correctly up to this point, let’s move on to the intersect example.
The intersect command will return records that are the same in both tables.
We will be asked for records whose classes have been opened. To do this, we will use the following command.
1 | select sinif from ogrenci intersect select sinif from sinif; |
As a result of the query, we see that there are 10-A and 11-B. This is because the 10-A and 11-B records are common to both tables.
As a result of this query, we see that 10-A and 11-B are opened, but the class is not opened even though there is a student waiting to enroll in the 12-B class.