You are on page 1of 39

Data

Data is a collection of a distinct small unit of information. It can be used in a


variety of forms like text, numbers, media, bytes, etc. it can be stored in pieces
of paper or electronic memory, etc.

Database

A database is an organized collection of data, so that it can be easily accessed and managed.

You can organize data into tables, rows, columns, and index it to make it easier to find relevant
information.

Database handlers create a database in such a way that only one set of software program provides access
of data to all the users.

The main purpose of the database is to operate a large amount of information by storing, retrieving, and
managing data.

Creating Tables

The SQL CREATE TABLE statement is used to create a new table.

Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows the
CREATE TABLE statement.

Data Types
SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. You can use these data types while
creating your tables. You can choose a data type for a table column based on your
requirement.
SQL Server offers six categories of data types for your use which are listed below −
Exact Numeric Data Types

DATA TYPE FROM TO

bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807

int -2,147,483,648 2,147,483,647

smallint -32,768 32,767

tinyint 0 255

bit 0 1

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1

money -922,337,203,685,477.5808 +922,337,203,685,477.5807

smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types

DATA TYPE FROM TO

float -1.79E + 308 1.79E + 308

real -3.40E + 38 3.40E + 38

Date and Time Data Types

DATA TYPE FROM TO


datetime Jan 1, 1753 Dec 31, 9999

smalldatetime Jan 1, 1900 Jun 6, 2079

date Stores a date like June 30, 1991

time Stores a time of day like 12:30 P.M.

Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.

Character Strings Data Types

Sr.No DATA TYPE & Description


.

char
1
Maximum length of 8,000 characters.( Fixed length non-Unicode characters)

varchar
2
Maximum of 8,000 characters.(Variable-length non-Unicode data).

varchar(max)
3 Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server
2005 only).

text
4
Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

Unicode Character Strings Data Types

Sr.No. DATA TYPE & Description

nchar
1
Maximum length of 4,000 characters.( Fixed length Unicode)

2 nvarchar
Maximum length of 4,000 characters.(Variable length Unicode)

nvarchar(max)
3
Maximum length of 2E + 31 characters (SQL Server 2005 only).( Variable length Unicode)

ntext
4
Maximum length of 1,073,741,823 characters. ( Variable length Unicode )

Binary Data Types

Sr.No. DATA TYPE & Description

binary
1
Maximum length of 8,000 bytes(Fixed-length binary data )

varbinary
2
Maximum length of 8,000 bytes.(Variable length binary data)

varbinary(max)
3
Maximum length of 2E + 31 bytes (SQL Server 2005 only). ( Variable length Binary data)

image
4
Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)

Misc Data Types

Sr.No DATA TYPE & Description


.

sql_variant
1 Stores values of various SQL Server-supported data types, except text, ntext, and
timestamp.

2 timestamp
Stores a database-wide unique number that gets updated every time a row gets updated

uniqueidentifier
3
Stores a globally unique identifier (GUID)

xml
4 Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005
only).

cursor
5
Reference to a cursor object

table
6
Stores a result set for later processing

Authorization
Authorization is a privilege provided by the Database Administer. Users of the database can
only view the contents they are authorized to view. The rest of the database is out of bounds
to them.

The different permissions for authorizations available are:

 Primary Permission - This is granted to users publicly and directly.

 Secondary Permission - This is granted to groups and automatically awarded to a


user if he is a member of the group.

 Public Permission - This is publicly granted to all the users.

 Context sensitive permission - This is related to sensitive content and only granted
to a select users.

The categories of authorization that can be given to users are:


 System Administrator - This is the highest administrative authorization for a user.
Users with this authorization can also execute some database administrator commands
such as restore or upgrade a database.

 System Control - This is the highest control authorization for a user. This allows
maintenance operations on the database but not direct access to data.

 System Maintenance - This is the lower level of system control authority. It also
allows users to maintain the database but within a database manager instance.

 System Monitor - Using this authority, the user can monitor the database and take
snapshots of it.

Structured Query Language (SQL) as we all know is the database language by the use of
which we can perform certain operations on the existing database and also we can use this
language to create a database. SQL uses certain commands like Create, Drop, Insert, etc. to
carry out the required tasks. 

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.

o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.

Here are some commands that come under DDL:

o REATE

o ALTER

o DROP

o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);  

Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB D
ATE);  

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE ;  

Example

1. DROP TABLE EMPLOYEE;  

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;    

To modify existing column in the table:

1. ALTER TABLE MODIFY (COLUMN DEFINITION....);  

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));  
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));  

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.

Syntax:
1. TRUNCATE TABLE table_name;  

Example:

1. TRUNCATE TABLE EMPLOYEE;  

2. Data Manipulation Language

o DML commands are used to modify the database. It is responsible for all form of
changes in the database.

o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT

o UPDATE

o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.

Syntax:

1. INSERT INTO TABLE_NAME    

2. (col1, col2, col3,.... col N)  

3. VALUES (value1, value2, value3, .... valueN);  

Or

1. INSERT INTO TABLE_NAME    

2. VALUES (value1, value2, value3, .... valueN);    

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");  

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:
1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [W
HERE CONDITION]   

For example:

1. UPDATE students    

2. SET User_Name = 'Sonoo'    

3. WHERE Student_Id = '3'  

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];  

For example:

1. DELETE FROM javatpoint  

2. WHERE Author="Sonoo";  

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant

o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USE
R;  

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;  

4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.

These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
Here are some commands that come under TCL:

o COMMIT

o ROLLBACK

o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;  

Example:

1. DELETE FROM CUSTOMERS  

2. WHERE AGE = 25;  

3. COMMIT;  

b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.

Syntax:

1. ROLLBACK;  

Example:

1. DELETE FROM CUSTOMERS  

2. WHERE AGE = 25;  

3. ROLLBACK;  

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;  

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is used to


select the attribute based on the condition described by WHERE clause.
Syntax:

1. SELECT expressions    

2. FROM TABLES    

3. WHERE conditions;  

For example:

1. SELECT emp_name  

2. FROM employee  

3. WHERE age > 20;  

Join Operations in SQL

A SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are:

 INNER JOIN

 LEFT JOIN

 RIGHT JOIN

 FULL JOIN

Consider the two tables below


Student
StudentCourse

 
The simplest Join is INNER JOIN.
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as
the condition satisfies. This keyword will create the result-set by combining all rows from
both the tables where the condition satisfies i.e value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
Example Queries(INNER JOIN)
 This query will show the names and age of students enrolled in different courses.
 SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student

 INNER JOIN StudentCourse


 ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

LEFT JOIN: This join returns all the rows of the table on the left side of the join and
matching rows for the table on the right side of join. The rows for which there is no
matching row on right side, the result-set will contain null. LEFT JOIN is also known as

LEFT OUTER JOIN.Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.

Example Queries(LEFT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the
table on the right side of the join and matching rows for the table on the left side of join.
The rows for which there is no matching row on left side, the result-set will contain null.
RIGHT JOIN is also known as RIGHT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are same.

Example Queries(RIGHT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN
and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows
for which there is no matching, the result-set will contain NULL values.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....

FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.

Example Queries(FULL JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

 Views in SQL

o Views in SQL are considered as a virtual table. A view also contains rows and
columns.

o To create the view, we can select the fields from one or more tables present in the
database.

o A view can either have specific rows based on certain condition or all the rows of a
table.

Sample table:

STU_ID NAME ADDRESS


1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Detail

Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view

A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.

Syntax:

1. CREATE VIEW view_name AS  

2. SELECT column1, column2.....  

3. FROM table_name  
4. WHERE condition;  

2. Creating View from a single table

In this example, we create a View named DetailsView from the table Student_Detail.

Query:

1. CREATE VIEW DetailsView AS  

2. SELECT NAME, ADDRESS  

3. FROM Student_Details  

4. WHERE STU_ID < 4;  

Just like table query, we can query the view to view the data.

1. SELECT * FROM DetailsView;  

Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables

View from multiple tables can be created by simply include multiple tables in the SELECT
statement.

In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.

Query:

1. CREATE VIEW MarksView AS  
2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARK
S  

3. FROM Student_Detail, Student_Mark  

4. WHERE Student_Detail.NAME = Student_Marks.NAME;  

To display data of View MarksView:

1. SELECT * FROM MarksView;  

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

4. Deleting View

A view can be deleted using the Drop View statement.

Syntax

1. DROP VIEW view_name;  

Example:

If we want to delete the View MarksView, we can do this as:

1. DROP VIEW MarksView;  

Specifying Constraints as Assertions and Actions as Triggers

 
In this section, we introduce two additional features of SQL: the CREATE
ASSERTION statement and the CREATE TRIGGER statement. 

CREATE TRIGGER was introduced to specify automatic actions that the database system
will perform when certain events and conditions occur. This type of functionality is generally
referred to as active data-bases. We only introduce the basics of triggers in this chapter, and
present a more complete discussion of active databases.

1. Specifying General Constraints as Assertions in SQL

In SQL, users can specify general constraints by using the CREATE ASSERTION statement


of the DDL. Each assertion is given a constraint name and is specified via a condition similar
to the WHERE clause of an SQL query. For example, to specify the constraint that the salary
of an employee must not be greater than the salary of the manager of the department that the
employee works for in SQL, we can write the following assertion:

CREATE ASSERTION SALARY_CONSTRAINT

CHECK ( NOT EXISTS               ( SELECT     *

FROM                                      EMPLOYEE E, EMPLOYEE M, DEPARTMENT D

 WHERE                                    E.Salary>M.Salary AND E.Dno=D.Dnumber AND


D.Mgr_ssn=M.Ssn ) );

The constraint name SALARY_CONSTRAINT is followed by the keyword CHECK, which


is followed by a condition in parentheses that must hold true on every data-base state for the
assertion to be satisfied. The constraint name can be used later to refer to the constraint or to
modify or drop it. The DBMS is responsible for ensuring that the condition is not violated.
Any WHERE clause condition can be used, but many constraints can be specified using
the EXISTS and NOT EXISTS style of SQL conditions. Whenever some tuples in the
database cause the condition of an ASSERTION statement to evaluate to FALSE, the
constraint is violated. The con-straint is satisfied by a database state if no combination of
tuples in that database state violates the constraint.

The basic technique for writing such assertions is to specify a query that selects any
tuples that violate the desired condition. By including this query inside a NOT
EXISTS clause, the assertion will specify that the result of this query must be empty so that
the condition will always be TRUE. Thus, the assertion is violated if the result of the query is
not empty. In the preceding example, the query selects all employees whose salaries are
greater than the salary of the manager of their department. If the result of the query is not
empty, the assertion is violated.

Note that the CHECK clause and constraint condition can also be used to specify constraints
on individual attributes and domains and on individual tuples. A major difference
between  CREATE ASSER-TION and the individual domain constraints and tuple constraints
is that the CHECK clauses on individual attributes, domains, and tuples are checked in
SQL only when tuples are inserted or updated. Hence, constraint checking can be imple-
mented more efficiently by the DBMS in these cases. The schema designer should
use CHECK on attributes, domains, and tuples only when he or she is sure that the constraint
can only be violated by insertion or updating of tuples. On the other hand, the schema
designer should use CREATE ASSERTION only in cases where it is not possible to
use CHECK on attributes, domains, or tuples, so that simple checks are implemented more
efficiently by the DBMS.

2. Introduction to Triggers in SQL

Another important statement in SQL is CREATE TRIGGER. In many cases it is convenient


to specify the type of action to be taken when certain events occur and when certain
conditions are satisfied. For example, it may be useful to specify a condition that, if violated,
causes some user to be informed of the violation. A manager may want to be informed if an
employee’s travel expenses exceed a certain limit by receiving a message whenever this
occurs. The action that the DBMS must take in this case is to send an appropriate message to
that user. The condition is thus used to monitor the database. Other actions may be specified,
such as executing a specific stored procedure or triggering other updates. The CREATE
TRIGGER  statement is used to implement such actions in SQL. Here we just give a simple
example of how triggers may be used.

Suppose we want to check whenever an employee’s salary is greater than the salary of his or
her direct supervisor in the COMPANY database. Several events can trigger this rule:
inserting a new employee record, changing an employee’s salary, or changing an employee’s
supervisor. Suppose that the action to take would be to call an external stored
procedure SALARY_VIOLATION, which will notify the supervisor. The trigger could then
be written as in R5 below. Here we are using the syntax of the Oracle database system.

CREATE TRIGGER SALARY_VIOLATION

 BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE

FOR EACH ROW WHEN ( NEW.SALARY > ( SELECT SALARY FROM EMPLOYEE

WHERE SSN = NEW.SUPERVISOR_SSN ) )

INFORM_SUPERVISOR(NEW.Supervisor_ssn, NEW.Ssn );

The trigger is given the name SALARY_VIOLATION, which can be used to remove or


deactivate the trigger later. A typical trigger has three components:

              The event(s): These are usually database update operations that are explicitly
applied to the database. In this example the events are: inserting a new employee record,
changing an employee’s salary, or changing an employee’s supervisor. The person who
writes the trigger must make sure that all possi-ble events are accounted for. In some cases, it
may be necessary to write more than one trigger to cover all possible cases. These events are
specified after the keyword BEFORE in our example, which means that the trigger should be
executed before the triggering operation is executed. An alternative is to use the
keyword AFTER, which specifies that the trigger should be executed after the operation
specified in the event is completed.
 

              The condition that determines whether the rule action should be executed: Once the
triggering event has occurred, an optional condition may be evaluated. If no condition is
specified, the action will be executed once the event occurs. If a condition is specified, it is
first evaluated, and only if it evaluates to true  will the rule action be executed. The condition
is specified in the WHEN clause of the trigger.

              The action to be taken: The action is usually a sequence of SQL statements, but it


could also be a database transaction or an external program that will be automatically
executed. In this example, the action is to execute the stored
procedure INFORM_SUPERVISOR.

Triggers can be used in various applications, such as maintaining database consistency,


monitoring database updates, and updating derived data automatically.

Relational Algebra

Relational algebra is a procedural query language. It gives a step by step process


to obtain the result of the query. It uses operators to perform queries.

Types of Relational operation


1. Select Operation:

The select operation selects tuples that satisfy a given predicate.

It is denoted by sigma (σ).

Notation: σ p(r)

Where:

σ is used for selection prediction

r is used for relation

p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >,
≤.

For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000


Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)  

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in the
result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)   

Where

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION


NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)  

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn
3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the
tuples that are either in R or S or both in R & S.

o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S   

A union operation must hold the following condition:

o R and S must have the attribute of the same number.

o Duplicate tuples are eliminated automatically.

Example:
DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO
Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay
Jackson

Curry

Williams

Mayes

4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in both R & S.

o It is denoted by intersection ∩.

1. Notation: R ∩ S   

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
1. Notation: R - S  

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product
o The Cartesian product is used to combine each row in one table with each row
in the other table. It is also known as a cross product.

o It is denoted by X.

1. Notation: E X D  
Example:

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C
3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT  

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing
3 John B B Sales

3 John B C Legal

7. Rename Operation:

The rename operation is used to rename the output relation. It is denoted


by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to


STUDENT1.

1. ρ(STUDENT1, STUDENT)  

Join Operation

Join is a combination of a Cartesian product followed by a selection process. A Join


operation pairs two tuples from different relations, if and only if a given join condition is
satisfied.
We will briefly describe various join types in the following sections.

Theta (θ) Join

Theta join combines tuples from different relations provided they satisfy the theta condition.
The join condition is denoted by the symbol θ.
Notation
R1 ⋈θ R2
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
SID Name Std

101 Alex 10

102 Maria 11

Subjects

Class Subject

10 Math

10 English

11 Music

11 Sports

Student_Detail −
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


Equijoin

When Theta join uses only equality comparison operator, it is said to be equijoin. The above
example corresponds to equijoin.

Natural Join (⋈)

Natural join does not use any comparison operator. It does not concatenate the way a
Cartesian product does. We can perform a Natural Join only if there is at least one common
attribute that exists between two relations. In addition, the attributes must have the same
name and domain.
Natural join acts on those matching attributes where the values of attributes in both the
relations are same.

Courses

CID Course Dept

CS01 Database CS

ME01 Mechanics ME

EE01 Electronics EE

HoD

Dept Head

CS Alex

ME Maya

EE Mira

Courses ⋈ HoD

Dept CID Course Head


CS CS01 Database Alex

ME ME01 Mechanics Maya

EE EE01 Electronics Mira

Outer Joins

Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only
those tuples with matching attributes and the rest are discarded in the resulting relation.
Therefore, we need to use outer joins to include all the tuples from the participating relations
in the resulting relation. There are three kinds of outer joins − left outer join, right outer join,
and full outer join.

Left Outer Join(R   S)

All the tuples from the Left relation, R, are included in the resulting relation. If there are
tuples in R without any matching tuple in the Right relation S, then the S-attributes of the
resulting relation are made NULL.

Left

A B

100 Database

101 Mechanics

102 Electronics

Right

A B
100 Alex

102 Maya

104 Mira

Courses   HoD

A B C D

100 Database 100 Alex

101 Mechanics --- ---

102 Electronics 102 Maya

Right Outer Join: ( R   S )

All the tuples from the Right relation, S, are included in the resulting relation. If there are
tuples in S without any matching tuple in R, then the R-attributes of resulting relation are
made NULL.

Courses   HoD

A B C D

100 Database 100 Alex

102 Electronics 102 Maya

--- --- 104 Mira

Full Outer Join: ( R   S)


All the tuples from both participating relations are included in the resulting relation. If there
are no matching tuples for both relations, their respective unmatched attributes are made
NULL.

Courses   HoD

A B C D

100 Database 100 Alex

101 Mechanics --- ---

102 Electronics 102 Maya

--- --- 104 Mira

Division Operator (÷): 

Division operator A÷B can be applied if and only if:


 Attributes of B is proper subset of Attributes of A.
 The relation returned by division operator will have attributes = (All attributes of A – All
Attributes of B)
 The relation returned by division operator will return those tuples from relation A which
are associated to every B’s tuple.
Consider the relation STUDENT_SPORTS and ALL_SPORTS given in Table 2 and Table 3
above.

To apply division operator as


 STUDENT_SPORTS÷ ALL_SPORTS
 The operation is valid as attributes in ALL_SPORTS is a proper subset of attributes in
STUDENT_SPORTS.
 The attributes in resulting relation will have attributes {ROLL_NO,SPORTS}-
{SPORTS}=ROLL_NO
 The tuples in resulting relation will have those ROLL_NO which are associated with all
B’s tuple {Badminton, Cricket}. ROLL_NO 1 and 4 are associated to Badminton only.
ROLL_NO 2 is associated to all tuples of B. So the resulting relation will be:

ROLL_NO
2

References
1. https://www.javatpoint.com/dbms-tutorial
2. https://www.geeksforgeeks.org/dbms/
3. https://www.tutorialspoint.com/dbms/index.htm
4. Elmasri, R., et al. Fundamentals of Database Systems</Title.
Addison-Wesley</publisher, 2000.
5. Silberschatz, Abraham, Henry F. Korth, and Shashank Sudarshan. Database
system concepts. Vol. 4. New York: Mcgraw-hill, 1997.

You might also like