0% found this document useful (0 votes)
19 views40 pages

Unit 2

The document provides an overview of different types of database keys, including candidate keys, super keys, primary keys, composite keys, alternate keys, unique keys, foreign keys, and surrogate keys. It explains their definitions, characteristics, and examples, as well as the integrity constraints that ensure data quality and relationships between tables. The document also highlights the differences between primary keys and foreign keys, emphasizing their roles in maintaining data integrity within a database.

Uploaded by

kartikeykamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views40 pages

Unit 2

The document provides an overview of different types of database keys, including candidate keys, super keys, primary keys, composite keys, alternate keys, unique keys, foreign keys, and surrogate keys. It explains their definitions, characteristics, and examples, as well as the integrity constraints that ensure data quality and relationships between tables. The document also highlights the differences between primary keys and foreign keys, emphasizing their roles in maintaining data integrity within a database.

Uploaded by

kartikeykamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Different Types of Database Keys

Candidate Key
The minimal set of attributes that can uniquely identify a tuple is
known as a candidate key. For Example, STUD_NO in STUDENT
relation.
 It is a minimal super key.
 It is a super key with no repeated data is called a candidate key.
 The minimal set of attributes that can uniquely identify a record.
 It must contain unique values.
 It can contain NULL values.
 Every table must have at least a single candidate key.
 A table can have multiple candidate keys but only one primary key.
 The value of the Candidate Key is unique and may be null for a
tuple.
 There can be more than one candidate key in a relationship.

Example:
STUD_NO is the candidate key for relation STUDENT.

Table STUDENT
STUD_NO SNAME ADDRESS PHONE

1 Shyam Delhi 123456789

2 Rakesh Kolkata 223365796

3 Suraj Delhi 175468965

 The candidate key can be simple (having only one attribute) or


composite as well.
Example:
{STUD_NO, PHONE_NO} is a composite
candidate key for relation STUDENT_COURSE.
Super Key
The set of attributes that can uniquely identify a tuple is known as
Super Key.

For Example, STUD_NO, (STUD_NO, STUD_NAME), etc. A super


key is a group of single or multiple keys that identifies rows in a table.
It supports NULL values.
 Adding zero or more attributes to the candidate key generates the
super key.
 A candidate key is a super key but vice versa is not true.
 Super Key values may also be NULL.

Example:
Consider the table shown above.
STUD_NO+PHONE is a super key.

Relation between Primary Key, Candidate Key, and Super Key


Super Key Candidate Key

Super Key is an attribute (or set of


Candidate Key is a subset of a
attributes) that is used to uniquely identifies
super key.
all attributes in a relation.

But all candidate keys are super


All super keys can’t be candidate keys.
keys.

Various candidate keys together


Various super keys together makes the
makes the criteria to select the
criteria to select the candidate keys.
primary keys.

While in a relation, number of


In a relation, number of super keys is more
candidate keys are less than
than number of candidate keys.
number of super keys.

Super key attributes can contain NULL Candidate key attributes can also
values. contain NULL values.

Primary Key
There can be more than one candidate key in relation out of which one
can be chosen as the primary key.

For Example, STUD_NO, as well as STUD_PHONE, are candidate


keys for relation STUDENT but STUD_NO can be chosen as
the primary key (only one out of many candidate keys).

 It is a unique key.
 It can identify only one tuple (a record) at a time.
 It has no duplicate values, it has unique values.
 It cannot be NULL.
 Primary keys are not necessarily to be a single column; more than
one column can also be a primary key for a table.
Example:

STUDENT table -> Student(STUD_NO, SNAME,


ADDRESS, PHONE) , STUD_NO is a primary key

Table STUDENT
STUD_NO SNAME ADDRESS PHONE

1 Shyam Delhi 123456789

2 Rakesh Kolkata 223365796

3 Suraj Delhi 175468965

The following table highlights the important differences between a Primary


Key and a Candidate Key −

S.
Primary Key Candidate Key
No.
Primary key is a unique and non−null
Candidate key is also a unique key to
1. key which identify a record uniquely in
identify a record uniquely in a table.
table.

Primary key column value cannot be Candidate key column can have
2.
NULL. NULL value.

Primary key is most important part of Candidate key signifies as which key
3.
any relation or table. can be used as Primary Key.

Candidate key may or may not be a


4. Primary Key is a candidate key.
primary key.
A table can have multiple candidate
5. A table can have only one primary key.
keys.
Composite Key
As the name suggests a composite key is a combination of multiple
columns that can uniquely identify tuples.
Example:
PaitentID and AnnualCheckupMonth can be considered together as a
composite key.

Apply Composite Key on multiple columns

CREATE TABLE Patients (


PatientID INT,PatientName VARCHAR(255),Sex VARCHAR(255),
Age VARCHAR(255),MedInsuranceNo VARCHAR(255),
AadharNo INT,PRIMARYKEY(PatientID,MedInsuranceNo)
);

Alternate Key
The candidate key other than the primary key is called an alternate
key .

 All the keys which are not primary keys are called alternate keys.
 It is a secondary key.
 It contains two or more fields to identify two or more records.
 These values are repeated.
 Eg:- SNAME, and ADDRESS is Alternate keys

Example:

Consider the table shown above.


STUD_NO, as well as PHONE both,
are candidate keys for relation STUDENT but
PHONE will be an alternate key
(only one out of many candidate keys).
Primary Key, Candidate Key, and Alternate Key

UNIQUE KEY
The syntax of the SQL UNIQUE is:
CREATE TABLE table_name (
column_name data_type UNIQUE
);

Here,

 table_name is the name of the table to be created


 column_name is the name of the column where the constraint is to be
implemented
 data_type is the data type of the column such as INT, VARCHAR, etc.

UNIQUE

In SQL, the UNIQUE constraint in a column means the column must


have unique values.
Example

-- create a table with unique constraint on college_code column


CREATE TABLE Colleges (
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
Run Code

Here, the values of the college_code column must be unique.

Primary Key vs. Unique Key Comparison Chart

Comparison Primary Key Unique Key


Basis

The primary key is used The unique key is also a unique


Basic as a unique identifier for identifier for records when the primary
each record in the table. key is not present in the table.

We cannot store NULL We can store NULL value in the unique


NULL values in the primary key key column, but only one NULL is
column. allowed.

It enforces entity
Purpose It enforces unique data.
integrity.

Each table supports only A table can have more than one unique
Number of Key
one primary key. key.
We can create a primary
key column in the table
using the below syntax: We can create a unique key column in
the table using the below syntax:

CREATE TABLE CREATE TABLE Person


Syntax
Employee (
( Id INT UNIQUE,
Id INT PRIMARY KEY, name VARCHAR(150),
name VARCHAR(150), address VARCHAR(250))
address VARCHAR(250)
)

Foreign Key
If an attribute can only take the values which are present as values of
some other attribute, it will be a foreign key to the attribute to which it
refers.

The relation which is being referenced is called referenced relation and


the corresponding attribute is called referenced attribute. The
referenced attribute of the referenced relation should be the primary
key to it.

 It is a key it acts as a primary key in one table and it acts as


secondary key in another table.
 It combines two or more relations (tables) at a time.
 They act as a cross-reference between the tables.
 For example, DNO is a primary key in the DEPT table and a non-
key in EMP
Example:

Relation between Primary Key and Foreign Key


CREATE TABLE students (

student_id INT PRIMARY KEY,first_name VARCHA2(50),last_name


VARCHA2(50), email VARCHA2(50),major VARCHA2(50), enrollment_year
INT);

CREATE TABLE courses (


course_id INT PRIMARY KEY, course_name VARCHA2(50),department
VARCHA2(50),
);

CREATE TABLE enrollments (


student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);

Surrogate Key
A surrogate key is an artificial key that is assigned to a record in a database table to
uniquely identify the row data in a table, and is not based on any natural primary
key. A surrogate key column holds usually an integer and the value is generated
before any record is inserted into the table.

Example: In the following table, the Date of Joining is a column that holds a
timestamp that inserts at the time any employee joins, and it is uniquely identified
for each employee. In this example, the Date of Joining is a surrogate key.
Employee_ID Employee_Name Email Mobile Date of Joining

2 Vivek [email protected] 9876543210 2023-01-22


09:30:12

3 Roberts [email protected] 9876543210 2023-01-22


09:50:15

4 Desuza [email protected] 9876543210 2023-01-22


10:00:35
Integrity Constraints

o Integrity constraints are a set of rules. It is used to maintain the


quality of information.
o Integrity constraints ensure that the data insertion, updating, and
other processes have to be performed in such a way that data
integrity is not affected.
o Thus, integrity constraint is used to guard against accidental
damage to the database.

Types of Integrity Constraint

1. Domain constraints

o Domain constraints can be defined as the definition of a valid set


of values for an attribute.
o The data type of domain includes string, character, integer, time,
date, currency, etc. The value of the attribute must be available in
the corresponding domain.
Example:

2. Not null constraints

The NOT NULL constraint is much more focused. It guarantees that


values within a column are not null. While this is a simple constraint, it
is used very frequently.
To mark a column as requiring a non-null value, add NOT NULL after
the type declaration:

CREATE TABLE national_capitals (


country VARCHAR(250) NOT NULL,
capital VARCHAR(250) NOT NULL
);

3. Check constraints

Check constraints are a general purpose constraint that allows you to


specify an expression involving column or table values that evaluates to
a boolean.

The syntax of the SQL CHECK constraint is:


CREATE TABLE table_name (
column_name data_type CHECK(condition)
);

Here,
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

4.The DEFAULT Constraint

it is used to fill a column with a default and fixed value. The value will
be added to all new records when no other value is provided.
Query:
CREATE TABLE Geeks (
ID int NOT NULL,Name varchar(255),
Age int, Location varchar(255) DEFAULT 'Noida');

5. Key constraints

o Keys are the entity set that is used to identify an entity within its
entity set uniquely.
o An entity set can have multiple keys, but out of which one key will
be the primary key. A primary key can contain a unique and null
value in the relational table.
Example:

SQL UNIQUE Constraint


The syntax of the SQL UNIQUE constraint is:

CREATE TABLE table_name (


column_name data_type UNIQUE
);
Here,

 table_name is the name of the table to be created


 column_name is the name of the column where the constraint is to be
implemented
 data_type is the data type of the column such as INT, VARCHAR, etc.

SQL UNIQUE Constraint

In SQL, the UNIQUE constraint in a column means the column must


have unique values.

Example

-- create a table with unique constraint on college_code column


CREATE TABLE Colleges (
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
Run Code

Here, the values of the college_code column must be unique.

5. Entity integrity constraints

o The entity integrity constraint states that primary key value can't
be null.
o This is because the primary key value is used to identify individual
rows in relation and if the primary key has a null value, then we
can't identify those rows.
o A table can contain a null value other than the primary key field.
Example:

6. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.


o In the Referential integrity constraints, if a foreign key in Table 1
refers to the Primary Key of Table 2, then every value of the
Foreign Key in Table 1 must be null or be available in Table 2.

There are three rules of referential integrity:

1. Insert Rule: A new record cannot be added to a child table if the


foreign key does not match an existing value in the parent table.
2. Update Rule: A record in the parent table cannot be updated if it
would create orphaned records(An orphan record is when a child
record with a foreign key points to a parent record of a primary
key field that no longer exists.) in the child table.
3. Delete Rule: A record cannot be deleted from the parent table if
there are matching records in the child table.

Constraints: Similar to foreign keys, these other constraints can


be added to columns:

 ON DELETE CASCADE: Deletes child records if the


parent record is deleted.
 ON UPDATE CASCADE: Updates child records if the
parent record is updated.
Example:

CREATE TABLE students (

student_id INT PRIMARY KEY,first_name VARCHA2(50),last_name


VARCHA2(50), email VARCHA2(50),major VARCHA2(50), enrollment_year
INT);

CREATE TABLE courses (


course_id INT PRIMARY KEY, course_name VARCHA2(50),department
VARCHA2(50),
);

CREATE TABLE enrollments (


student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);
Putting It All Together

CREATE TABLE students (


student_id INT PRIMARY KEY,
first_name VARCHA2(50) NOT NULL,
last_name VARCHA2(50) NOT NULL,
email VARCHA2(50) UNIQUE NOT NULL,
major VARCHA2(50) DEFAULT 'Undeclared',
enrollment_year INT,
CONSTRAINT year_check CHECK (enrollment_year >= 1900),
CHECK (major IN (
'Undeclared',
'Computer Science',
'Mathematics',
'Biology',
'Physics',
'Chemistry',
'Biochemistry'
))
);

Major Difference between Primary Key and Foreign Key

Basis Primary Key Foreign Key

A foreign key establishes a


A primary key is a unique
relationship between tables by
Definition identifier for each record in a
referencing the primary key of
table.
another table.

Establishes relationships and


Ensures uniqueness and data
Basic maintains referential integrity
integrity within a single table.
between tables.

Allows NULL values in the


Does not allow NULL values
NULL foreign key field, indicating a
in the primary key field.
missing or unspecified
relationship.

Multiple foreign keys can exist


Only one primary key can
Count within a table, depending on the
exist per table.
relationships with other tables.

Can contain duplicate foreign


No duplicate primary key
key values, reflecting multiple
Duplication values are allowed within the
records associated with the same
table.
reference.

Deleting a record with a


Deleting a record with a foreign
primary key constraint can
Deletion key constraint can be restricted
affect referential integrity in
or cascade to maintain integrity.
related tables.

The foreign key can reference an


Each new record must have a
existing primary key value or be
Insertion unique primary key value
NULL if the relationship is
assigned.
optional.

Foreign keys can also be applied


Temporary Primary keys can be applied
to temporary tables to establish
table to temporary tables.
relationships.

Primary keys define the basis Foreign keys establish


Relationship for establishing relationships relationships and connect data
with other tables. between related tables.
What is Relational Algebra in DBMS?
Relational Algebra came in 1970 and was given by Edgar F. Codd
(Father of DBMS). It is also known as Procedural Query
Language(PQL) as in PQL, a programmer/user has to mention two
things, "What to Do" and "How to Do".

https://www.scaler.com/topics/dbms/relational-algebra-in-dbms/

Fundamental Operations

The basic operations of relational algebra include:

 Select (σ): This operation is used to select rows from a relation that
satisfy a given predicate.
 Project (π): It is used to select columns from a relation, thereby
reducing the relation to only those columns that are required.
 Union (⋃): This operation combines the tuples of two relations
and removes duplicate tuples.
 Set Difference (-): It yields the tuples that are present in one
relation but not in another.
 Cartesian Product (×): This operation returns a relation that is a
combination of every tuple of one relation with every tuple of
another.

Additional Operations

Beyond the basics, relational algebra also includes:

 Rename (ρ): It allows us to rename the output relation.


 Intersection (∩): This operation yields tuples that are present in
both relations.
 Division (÷): It is used when we need to find tuples in one relation
that are related to all tuples in another relation.
Select operation
It displays the records that satisfy a condition. It is denoted by sigma (σ)
and is a horizontal subset of the original relation.

Syntax

Its syntax is as follows −

σcondition(table name)
Example

Consider the student table given below −

Regno Branch Section

1 CSE A

2 ECE B

3 CIVIL B

4 IT A

Now, to display all the records of student table, we will use the
following command −

σ(student)
In addition to this, when we have to display all the records of CSE
branch in student table, we will use the following command −

σbranch=cse(student)
Hence, the result will be as follows −

RegNo Branch Section

1 CSE A

To display all the records in student tables whose regno>2, we will use
the below mentioned command −

σRegNo>2(student)
The output will be as follows −

RegNo Branch Section

3 CIVIL B

4 IT A

To display the record of ECE branch section B students, use the given
command −

σbranch=ECE ^ section=B(student)
To display the records of section B CSE and IT branch, use the
following command −

σSection=B ^ Branch=cse ∨ branch=IT(student)


Consider the EMPLOYEE TABLE as another example to know about
selection operations.
Example − In order to retrieve the information of those employee whose
salary > 20,000 and working in HOD and Dept no is 20, we can use the
following command −

σ salary > 20,000 ^LOC=HOD ^Deptno=20(emp)

2. Projection(π): It is used to project required column data from a relation.

Example: Consider Table 1. Suppose we want columns B and C from


Relation R.

π(B,C)R will show following columns.

B C

2 4

2 3

3 4

Note: By Default, projection removes duplicate data.

3. Union(U): Union operation in relational algebra is the same as union


operation in set theory.

Example:
FRENCH
Student_Name Roll_Number

Ram 01

Mohan 02

Vivek 13

Geeta 17

GERMAN
Student_Name Roll_Number

Vivek 13

Geeta 17

Shyam 21

Rohan 25

Consider the following table of Students having different optional subjects in


their course
.
π(Student_Name)FRENCH U π(Student_Name)GERMAN
Student_Name

Ram

Mohan

Vivek

Geeta

Shyam

Rohan

Note: The only constraint in the union of two relations is that both relations
must have the same set of Attributes.

4. Set Difference(-): Set Difference in relational algebra is the same set


difference operation as in set theory.

Example: From the above table of FRENCH and GERMAN, Set Difference
is used as follows

π(Student_Name)FRENCH - π(Student_Name)GERMAN

Student_Name

Ram

Mohan
Note: The only constraint in the Set Difference between two relations is that
both relations must have the same set of Attributes.

5. Set Intersection(∩): Set Intersection in relational algebra is the same set


intersection operation in set theory.

Example: From the above table of FRENCH and GERMAN, the Set
Intersection is used as follows

π(Student_Name)FRENCH ∩ π(Student_Name)GERMAN

Student_Name

Vivek

Geeta

Note: The only constraint in the Set Difference between two relations is that
both relations must have the same set of Attributes.
6. Rename(ρ): Rename is a unary operation used for renaming attributes of
a relation.

ρ(a/b)R will rename the attribute 'b' of the relation by


'a'.

7. Cross Product(X): Cross-product between two relations. Let’s say A and


B, so the cross product between A X B will result in all the attributes of A
followed by each attribute of B. Each record of A will pair with every record of
B.
Example:

A
Name Age Sex

Ram 14 M

Sona 15 F

Kim 20 M

B
ID Course

1 DS

2 DBMS

AXB
Name Age Sex ID Course

Ram 14 M 1 DS

Ram 14 M 2 DBMS

Sona 15 F 1 DS
Name Age Sex ID Course

Sona 15 F 2 DBMS

Kim 20 M 1 DS

Kim 20 M 2 DBMS

Note: If A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘ n*m ‘
tuples.

Relational Division

The final relational operation we consider is relational division. Division


of table A by table B is only meaningful if A has more columns than B.

Let's assume that table A has two sets of columns, X and Y, and
table B has a set of columns Y. In other words, X is the set of columns
in A that are not present in B. We'll assume an ordered relation between
the Y columns in A and B so that we know which column
in B corresponds to which column in A.

The result of A ÷ B is formed by restricting the result to those rows


of A where the Y column values in A all the rows of B and then deleting
the Y columns from A. The expression A ÷ B may also be written
as A divide-by B. Figure 12.26 shows a trivial example, where the
attribute domains are denoted by X1, X2, Y1.
As a practical example, suppose the table Speaks(country, language)
stores facts about which countries speak (i.e., use) which languages. A
sample population is shown in the large table within

Figure 12.27. Now consider the query: Which countries speak all the
languages spoken in Canada?
To answer this, we first find all the languages spoken in Canada, using
the expression Speaks where country = ‘Canada’ [language].

This returns the table {English, French}. We then divide the Speaks
table by this result, as shown, to obtain the final answer {Canada,
Dominica}.
Derived Operators
These are some of the derived operators, which are derived from the
fundamental operators.

1. Natural Join(⋈)
2. Conditional Join

Join Operations:
A Join operation combines related tuples from different relations, if and only
if a given join.

1. Natural Join(⋈) or Equi Join: Natural join is a binary operator. Natural


join between two or more relations will result in a set of all combinations of
tuples where they have an equal common attribute.
Example:

EMP
Name ID Dept_Name

A 120 IT

B 125 HR

C 110 Sales

D 111 IT
DEPT
Dept_Name Manager

Sales Y

Production Z

IT A

Natural join between EMP and DEPT with condition :


EMP.Dept_Name = DEPT.Dept_Name

EMP ⋈ DEPT
Name ID Dept_Name Manager

A 120 IT A

C 110 Sales Y

D 111 IT A

2.Theta Join or Conditional Join

Theta Join is used to join two tables based on some conditions. The
condition can be on any attributes of the tables performing Theta join.
Any comparison operator can be used in the condition.
A ⋈θ B where θ is the condition for join.

R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,..
,Bn) such that the attributes don’t have anything in common, that is R1
∩ R2 = Φ.

Theta join can use all kinds of comparison operators.

Student Table:

Name Std
SID
101 Alex 10
102 Maria 11

\
Subjects Table:

Subject
Class
10 Math
10 English
11 Music
11 Sports
STUDENT ⋈Student.Std = Subject.Class SUBJECT

Student_detail
SID Name Std Class Subject
101 Alex 10 10 Math
101 Alex 10 10 English
102 Maria 11 11 Music
102 Maria 11 11 Sports

Self Join :
SQL self join where a table joins with itself, allowing for comparisons
within the same table. It's particularly useful for querying hierarchical
data or comparing rows within the same table. When performing a self
join, SQL treats the single table as if it were two separate tables to
perform the join.

Syntax

To implement a self join, you typically use an INNER JOIN, LEFT


JOIN, or another type of join, but you reference the same table twice
with different aliases to distinguish between the two instances of the
table.

SELECTA.column_name, B.column_name
FROM table_name AS A JOIN table_name AS B
ON A.common_field=B.common_field
WHERE condition;


 table_name: The name of the table you are performing the self
join on.
 A and B: Aliases for the table to distinguish the two instances.
 common_field: The column based on which the join is performed.
 condition: Additional conditions to filter the results.Example

CREATETABLE Employees (
EmployeeID INT,
Name VARCHAR(50),
ManagerID INT
);

Inserting Data into the Table

EmployeeID Name ManagerID

1 John NULL

2 Jane 1

3 Doe 1

4 Smith 2

To find each employee and their manager's name, you would use the
following SQL query:

SELECT E1.Name AS EmployeeName, E2.Name AS ManagerName


FROM Employees AS E1 LEFTJOIN Employees AS E2
ON E1.ManagerID= E2.EmployeeID;

Output:Assuming the Employees table is structured as mentioned, the


output of the above query would be a table showing each employee with
their respective manager's name:
EmployeeName ManagerName

John NULL

Jane John

Doe John

Smith Jane

In this example, the self join allows us to link each employee to their
manager within the same Employees table by using
the ManagerID column to relate employees to each other.

SQL CROSS JOIN



SQL CROSS JOIN returns all the records from the left and right tables.
CROSS JOIN returns a combination of each row in the left table paired
with each row in the right table.

CROSS JOIN in SQL


Cross Join in SQL produces a result set that contains the cartesian
product of two or more tables. Cross join is also called a Cartesian
Join.
When CROSS JOIN is used with a WHERE clause, it behaves
like INNER JOIN, filtering the results based on specific conditions.

CROSS JOIN is the best choice when we need to match each row of one
table to every other row of another table. It is helpful in many
applications where we need to obtain paired combinations of records.
Cross Join B/W Two Sets

Syntax
SELECT * FROM table1
CROSS JOIN table2;

SQL CROSS JOIN Example


Let’s look at some examples of CROSS JOIN statement in SQL to understand it’s
working.Demo SQL Database
In this CROSS JOIN tutorial, we will use the following two tables in examples:

Table 1- Customer
ID NAME AGE PHONE

1 AMIT JAIN 21 98474

2 JATIN VERMA 47 63996


Table 2- Orders
ORDER_ID AMOUNT PLACED_ON

101 999 2023-04-19

102 4999 2023-04-20

To create both these tables on your system, you can write the following code:

CROSS JOIN Example

In this example, we will use the CROSS JOIN command to match the data of the
Customer and Orders table.

Query
SELECT *
FROM CUSTOMER
CROSS JOIN ORDERS;

Output

Cross Join

As we can see, whether the other table matches or not, the CROSS JOIN keyword
returns all similar records from both tables
4. Outer Join:

The outer join operation is an extension of the join operation. It is used


to deal with missing information.

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000


a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R


and S that are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS


table

EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Nehru
Hari Hyderabad TCS 50000
street

M.G.
Ravi Delhi NULL NULL
Street
b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R


and S that are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS


Relation

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Park
Shyam Kolkata Wipro 20000
street

Nehru
Hari Hyderabad TCS 50000
street

Kuber NULL NULL HCL 30000


c. Full outer join:

o Full outer join is like a left or right join except that it contains all
rows from both tables.
o In full outer join, tuples in R that have no matching tuples in S and
tuples in S that have no matching tuples in R in their common
attribute name.
o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS


table

1. EMPLOYEE ⟗ FACT_WORKERS
EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Park
Shyam Kolkata Wipro 20000
street

Nehru
Hari Hyderabad TCS 50000
street

M.G.
Ravi Delhi NULL NULL
Street

Kuber NULL NULL HCL 30000

You might also like