0% found this document useful (0 votes)
24 views17 pages

Database

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)
24 views17 pages

Database

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/ 17

DATABASE:

➢ May be defined as a collection of interrelated data stored together to serve multiple


application
➢ It is computer based record keeping system.
➢ It not only allows to store but also allows us modification of data as per requirements

DBMS:
➢ A DBMS refers to Database Management System
➢ It is a software that is responsible for storing, manipulating, maintaining and utilizing
database.
➢ A database along with a DBMS is referred to as a database system.
➢ There are various DBMS software available in the market like :- Oracle, MS SQL Server,
MySQL, Sybase, PostgreSQL, SQLite

Purpose of DBMS:
➢ Reduced Data redundancy –
➢ Control Data Inconsistency
➢ Sharing of data
➢ Ensure data integrity
➢ Enforce standard

Relational Database Model:


➢ In relational database model data is organized into table (i.e. rows and columns).
➢ These tables are also known as relations.
➢ A row in a table represent relationship among a set of values.
➢ A column represent the field/attributes related to relation under which information will be
stored.
➢ For example if we want to store details of students then : Roll, Name, Class, Section, etc.
will be the column/attributes and the collection of all the column information will become
a Row/Record
Sample Tables:
DEPT
DEPTNO DNAME LOC
10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Bostan

Component of a table:
➢ Byte: group of 8 bits and is used to store a character.Data Item: smallest unit of named
data. It represent one type of information and oftenreferred to as a field or column
information
➢ Record : collection of data items which represent a complete unit of information
➢ Table: collection of all Rows and Columns.

Common RDBMS:
➢ Oracle, MS SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase, Adaptive
Server Enterprise, SAP Sybase IQ, Teradata, PostgreSQL, SQLite, etc.
➢ Out of these MySQL, PostgreSQL and SQLite are Open source implementation.

MySQL
➢ Runs on virtually all platforms including Linux, Unix and Windows. Popular for web based
application and online publishing. It is a part of LAMP (Linux, Apache, MySQL, PHP)
stack

SQLite
➢ Relational DBMS but it is not client-server database engine rather, it is embedded into end
program. Arguably the most widely deployed database engine as it is used by several
browsers, OS and embedded systems (Mobiles).

PostgreSQL
➢ General purpose object-relational DBMS.
➢ It is the most advanced open source database system. It is free and open source i.e. source
code is available under PostgreSQL license, a liberal open source license.

Common DBMS Tools for Mobile Devices:


➢ SQL Anywhere, DB2 Everywhere, IBM Mobile Database, SQL Server Compact, SQL
Server Express, Oracle DatabaseLite, SQLite, SQLBase etc.
➢ Out of these SQLite is public domain open source implementation.

RELATIONAL DATA MODEL:-


Data is organized in two-dimensional tables called relations. The tables or relations are
related to each other.

Characteristics of relational database are:-Data is arranged into rows and columns,


➢ Each relation is represented as a table.
➢ Every row in a table represents a single entity.
➢ At any given row or column position, there is one and only one value.

Advantages of a relational model are as follows:


➢ Changes made in the table structure do not affect the data access or other application
programs.
➢ Tabular view also provides easier database design, use, implementation and management.
➢ Built-in query support .
➢ Mathematical operations can be successfully carried out using RDBMS.

The limitations of relational model are:


➢ RDBMS incurs hardware and system software overheads.
➢ The size of database becomes very large.

Various Terms Used in Relational Model: - A relational database is a type of database that
stores and provides access to data points that are related to one another.

Basic Terminologies related to a Relational Database:-


➢ Entity: An entity is something that exists and an object which can be distinctly identified.
For example, student entity, employee entity,
➢ Attribute: The term attribute is also used to represent a column.
➢ Tuple: Each row in a table is known as tuple.
➢ Cardinality of Relation: It is the number of records or tuples in the relation.
➢ Degree of Relation: Number of columns or attributes is known as degree of a relation.
➢ Domain of Relation: It defines the kind of data represented by the attribute.
➢ Body of the Relation: It consists of an unordered set of 0 or more tuples.

Concept of Keys
➢ In relation each record must be unique i.e. no two identical records are allowed in the
Database.
➢ A key attribute identifies the record and must have unique values. There are various types
of Keys:

Primary Key:
➢ A set of one or more attribute that can identify a record uniquely in the relation is called
Primary Key.
➢ There can be only 1 primary key in a table
➢ Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL)
i.e. we cannot left it blank.

Candidate Key
➢ In a table there can be more than one attribute which contains unique values. These
columns are known as candidate key as they are the candidate for primary key.
➢ Among these database analyst select one as a primary key based on requirement like must
contain unique value, compulsory entry and where maximum searching is done etc.

Alternate Key
➢ In case of multiple candidate keys, one of them will be selected as Primary Key and rest
of the column will serve as Alternate Key
➢ A Candidate Key which is not a primary key is an Alternate Key.

Foreign key
➢ Used to create relationship between two tables.
➢ It is a non-key attribute whose value is derived from the Primary key of another table.
➢ Foreign key column will for the value in Primary key of another table, if present then entry
will be allowed otherwise data will be rejected.
➢ Primary Key column table from where values will be derived is known as Primary Table
or Master Table or Parent Table and Foreign key column table will be Foreign Table or
Detail Table or Child table.

From the Above table definition, we can observe that the DEPTNO column of EMPLOYEE table
is deriving its value from DEPTNO of table DEPARTMENT. So we can say that the DEPTNO of
EMPLOYEE table is a foreign key whose value is dependent upon the Primary key column
DEPTNO of table DEPARTMENT.

REFERENTIAL INTEGRITY:
➢ Used to ensure relationship between records in related tables are valid and user don’t
accidentally delete or change the related data.
➢ Referential integrity can be applied when:
➢ The master table’s column is a Primary Key or has a unique index
➢ The related fields have the same data type
➢ Both tables must belong to same database.
➢ When referential integrity is enforced using Foreign Key you must observe the following
rules:
➢ You cannot enter a value in Child Table which is not available in Master Table’s Primary
key column. However you can enter NULL values in foreign key
➢ You cannot delete a record from Master Table if matching record exists in related table.
➢ You cannot modify or change the Primary Key value in Master table if its matching record
is present in related table.
STRUCTURED QUERY LANGUAGE

➢ It is a language that enables you to create and operate on relational databases


➢ It is the standard language used by almost all the database s/w vendors.
➢ Pronounced as SEQUEL
➢ It is portable i.e. it is compatible with most of the database.
➢ It is not a case sensitive language.
➢ It is very easy to learn.

SQL – features
➢ Allows creating/modifying a database’s structure
➢ Changing security settings for system
➢ Permitting users for working on databases or tables
➢ Querying database
➢ Inserting/modifying/deleting the database contents

Classification of SQL
➢ DDL (Data Definition Language)
➢ DML (Data Manipulation Language)
➢ DCL (Data Control Language) or TCL (Transaction Control Language)

Data Definition Language:


➢ It allows to create database objects like creating a table, view or any other database objects.
➢ The information about created objects are stored in special file called DATA
DICTIONARY
➢ DATA DICTIONARY contains metadata i.e. data about data.
➢ The commands of DDL are –
o CREATE – To create a new database object
o ALTER – To modify existing database object
o DROP – To permanently remove existing database object.

Data Manipulation Language:


➢ It allows to perform following operation on data in the table
➢ Retrieval of information stored in table
➢ Insertion of new data in table
➢ Modification of existing data in table
➢ Deletion of existing data from table
➢ DML is of 2 type
➢ Procedural DML (in this we specify what data is needed and how to get it)
➢ Non-Procedural DML (in this we specifywhat data is needed without
specifying how to get it)
➢ The commands of DML are
o SELECT – To retrieve data from the table
o INSERT – To insert new tuple/row in the table
o UPDATE – To update existing tuple/row from the table
o DELETE – To delete existing tuple/row from the table

Data Transaction Language:


➢ The commands here are used for Database Administration such as providing access or
restriction to data/table to users.
➢ Some commands of DCL are
o ROLLBACK
o COMMIT
o GRANT

INTRODUCTION OF MYSQL

Brief history of MySQL:


➢ MySQL is freely available open source RDBMS
➢ It can be downloaded from www.mysql.org
➢ In MySQL information is stored in Tables.
➢ Provides features that support secure environment for storing, maintaining and accessing
data.
➢ It is fast, reliable, scalable alternative to many of the commercial RDBMS today.
➢ It is developed and supported by MySQL AB, a company based in Sweden.
➢ This company is now subsidiary of Sun Microsystems. On April 2009 Oracle Corp.
acquires Sun Microsystems.
➢ The chief inventor of MySQL was Michael Widenius (a.k.a Monty).
MySQL has been named after Monty’s daughter My. The logo of MySQL is dolphin and
name of that dolphin is ‘Sakila’.

MYSQL DATABASE SYSTEM:


➢ MySQL database system refers to the combination of a MySQL server instance and
MySQL database.
➢ It operates using Client/Server architecture in which the server runs on the machine
containing the database and client connects to server over a network
➢ MySQL is a multiuser database system, meaning several users can access the database
simultaneously.

The Server
➢ Listens for client requests coming in over the network and access the database as per the
requirements and provide the requested information to the Client.

The Client
➢ Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-end
programming which connect to server programmatically like connecting to MySQL using
Python Language or Java or any other language.

FEATURES OF MYSQL:
➢ Speed - MySQL runs very fast.
➢ Ease of Use -Can be managed from command line or GUI
➢ Cost Is available free of cost. It is Open Source
➢ Query language Support -Supports SQL
➢ Portability – Can be run on any platform and supported by various compilers
➢ Data Types - supports various data types like Numbers, Char etc.
➢ Security -Offers privileges and password systems that is very flexible and secure.
➢ Scalability and Limits -Can handle large databases. Some of real life MySQL databases
contains millions of records.
➢ Connectivity-Clients can connect to MySQL using drivers
➢ Localization -The server can provide error message to client in many language
➢ Client and Tools -Provides several client and utility programs. Like mysqldump and
mysqladmin. GUI tools like MySQL Administration and Query Browser.
STARTING MYSQL:

Click on Start →All Programs →MySQL → MySQL Server→ MySQL →Command Line Client
To exit from MySQL type exit or quit in front of MySQL prompt.

SQL and MYSQL:


➢ SQL stands for Structured Query Language.
➢ It is a language that enables you to create and operate on relational databases.
➢ MySQL uses SQL in order to access databases.
➢ It is the standard language used by almost all the database s/w vendors.

MYSQL Elements
➢ Literals
➢ Data types
➢ Nulls
➢ Comments

Literals
➢ It means the fixed value or constant value. It may be of character, numeric or date time
type.
➢ Character and date/time literals are always in single quotation marks whereas numeric
literals must be without single quotation marks
➢ For example – ‘Virat’, 12, 12.56, ‘04-20-2018’
➢ Date and time values are always in the format YYYY-MM-DD HH:MI:SS
➢ Special character like quotes are always written be preceding it back-slash(\). For example
if we want to store value as Tom’s Cat then it should be written as Tom\’s Cat
Data Type

➢ Means the type of value and type of operation we can perform on data. For example on
numeric value we can store numbers and perform all arithmetic operations and so on.
➢ Numeric
➢ Date and time
➢ String types

Numeric Data Types


DATA TYPE DESCRIPTION
INT Numbers without decimal. Store up to 11 digits. -2147483648 to 2147483647
TINYINT Small integer value between 0 – 255 (4 digits)
SMALLINT More than TINYINT between -32768 to 32767 (5 digit)
MEDIUMINT Integer values up to 9 digits
BIGINT Very large integer value up to 11 digits
FLOAT(M,D) Real numbers i.e. number with decimal. M specify length of numeric
value including decimal place D and decimal symbol. For example if
it is given as FLOAT(8,2) then 5 integer value 1 decimal symbol and 2
digit after decimal TOTAL – 8. it can work on 24 digits after decimal.
DOUBLE(M,D) Real numbers with more precision up to 53 place after decimal.
DECIMAL It is used to store exact numeric value that preserve exact precision for e.g.
money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D represent no.
of digit after decimal(0-30), for e.g DECIMAL(6,2) means 4 digit before
decimal and 2 digit after decimal. Max will be 9999.99
Date and Time Types
➢ DATE-A date in YYYY-MM-DD format between 1000-01-01 to 9999-12-31.
➢ DATETIME-Combination of date and time. For example to store 4th December 2018 and
time is afternoon 3:30 then it should be written as – 2018-12-04 15:30:00
➢ TIMESTAMP - Similar to DATATIME but it is written without hyphen for example
the above date time is stored as 20181204153000
➢ TIME-To store time in the format HH:MM:SS
➢ YEAR(M) -To store only year part of data where M may be 2 or 4 i.e. year in 2 digit like
18 or 4 digit like 2018.
String Types
➢ CHAR(M)
o Fixed length string between 1 and 255.
o It always occupy M size, irrespective of actual number of characters entered.
o Mostly use in the case where the data to be insert is of fixed size like Grade
(A,B,C,..) or Employee code as E001, E002, etc
➢ VARCHAR(M)
o Variable length string between 1 and 65535 (from MySQL 5.0.3) , earlier it was
255
o It takes size as per the data entered for example with VARCHAR(20) if the data
entered is MOBILE then it will take only 6 byte.
o It is useful for the data like name, address where the number of character to be enter
is not fixed.
➢ Difference between CHAR & VARCHAR
CHAR VARCHAR
Fixed length string Variable length string
Fast, no memory allocation every time Slow, as it take size according to data so every
time memory allocation is done
It takes more memory It takes less space

Simple Queries in SQL

➢ SHOW DATABASES- This command is used to list all databases on MySql Server
➢ USE <DATABASENAME>- This command is used to change/select/open given database
e.g. To open a database named ‘test’
>>> use test
➢ SHOW TABLES – This command will list all the tables from current database. If no database
is selected it will generate error.
➢ SELECT DATABASE () – This command will display the name of current database.
➢ DESC <TABLENAME> OR DESCRIBE <TABLENAME> - This command will be used
to display the structure of the table. For Eg: The above figure display the use of describe
command

➢ CREATE DATABASE <DATABASENAME> - This command is use to create a new


database.
For example – create database mydb will new database mydb
Above command will generate error, if database already exist. To supress the error following
command can be used
create database if not exist mydb
➢ DROP DATABASE <DATABASENAME> - This command is used to remove existing
database.
For example – drop database mydb will permanently delete mydb database.
Above command will generate error, if database already exist. To supress the error following
command can be used
drop database if exist mydb

➢ CREATE TABLE <TABLENAME> - This command / statement is used to create a new


table in a database. The syntax the is
CREATE TABLE table_name
(
column1 datatype[(size)] [constraint] ,
column2 datatype[(Size)] [constraint],
column3 datatypeI[(size)] [constraints] ,
....
);
Here size and constraints are optional.
e. g.
CREATE TABLE PET(
NAME VARCHAR(20),
OWNER VARCHAR(20),
SPECIES VARCHAR(20),
SEX CHAR(1),
BIRTH DATE, DEATH DATE
);

➢ DROP TABLE <TABLENAME> - This command is used to permanently delete the table
from database.
For example, drop table pet; will delete pet table from database
➢ ALTER TABLE <TABLENAME> - This command is used to modify the structure of
existing table such as adding new column, removing existing column, rename or changing data
type, size and constraints.
o Adding new column to exiting table
Syntax :

Alter table <tablename>


Add [column] column_name datatype [(size)];

o Removing new existing column from the table


Syntax:
Alter table <tablename>
drop column <column_name>;

o Changing datatype/size of the column


Systax:
alter table <tablename>modify column <colname> datatype(size);

o Renaming column name


Alter table tablename
Change old_columnname new_column_name datatype (size)

➢ UPDATE <TABLENAME> - This command is used to update data from the table
Syntax:
UPDATE table_name SET column_name=new_value, column2_name=new_value
WHERE condition;
e.g. UPDATE emp set sal=sal+100 where ename =’Scot’

The above query will update salary of Scot by 100.


If where clause is not given, it will update/modify the value of column from each row.

➢ INSERTING INTO TABLE_NAME – This command is used to add new row to the table
Syntax :
INSERT INTO table_name VALUES (list of values)

➢ SELECT DATA FROM TABLE USING SELECT STATEMENT

Syntax:
SELECT */ COLUMN LISTFROM TABLE(S)
WHERE CLAUSE/CONDITION
GROUP BY CLAUSE/COLUMN NAME
HAVING CLAUSE/CONDITION
ORDER BY COLUMN NAME ASC/DESC

➢ Selecting/displaying entire data from the table


Syntax:
SELECT * From tablename;

➢ Selecting/displaying data from specific column


Syntax:
SELECT column1, column2, column3, …. FROM tablename;
➢ Giving descripting name for column using column alias
Syntax:
SELECT */col_name as ‘alias1’ FROM tablename;

➢ Removing duplicate value from the column using distinct clause


Syntax:
DISTINCT column_name FROM tablename;

➢ Display all data from column using all clause


Syntax:
SELECT ALL column_name FROM tablename;

➢ Inserting text in the query


Syntax:
SELECT ‘text’ FROM tablename;

Number of rows in result depend on total number of rows in the table

➢ Performing simple calculation in the query


Syntax:
Select 2+4;
All operation can be perform such as addition (+), subtraction (-), multiplication (*), division
(/) and remainder (%)

Number of row in result depend on total number of rows in the table

➢ Performing calculation on column


Syntax:
SELECT column1 operator value, column2…. FROM Tablename;

➢ Working with null value


Any operation on NULL will result into NULL, MySql provide ifnull() function to work with
null value. If column contain null value, it is replaced by given value, otherwise display
original value.

Syntax:
ifnull(column, value_to_replace’)

➢ Restricting rows using where clause


Where clause in the query will restrict number of rows in the output based on condition.
Syntax:
SELECT */column list
FROM Tablename
where condition ;
Condition (column_name operator expression)

Relational Operator
> greater than
< less than
>= greater than equal to
<= less than equal to
= equal
! = or <> not equal to

Logical Operator
And – evaluated true if all the logical expression is true otherwise false.
Or - evaluated true if any the logical expression is true otherwise false.
Logical operator is used to combine two or more logical expression,

Membership Operator
in –
Not in
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.

➢ Comparing NULL
is null
is not null
NULL (Absence of value) value cannot be compared using Relational operator. The above
statement is used to check whether column contains NULL or not.

➢ Range Operator
Between

➢ Pattern Matching
Like
Not Like

Like clause is used to match pattern using two wild card characters
_ (underscore) – single unknown character
% (modulo) - Zero or more unknown characters
e.g.
words staring with ‘t’ ‘t%’
words ending with ‘t’ ‘%t’
words containing ‘t’ - ‘%t%’
word with ‘t’ as second letter - ‘_t%’
words with ‘t’ as third last character – ‘%t_ _’
words containing four letter and ‘t’ as second letter – ‘_ t_ _’

➢ Ordering data using ORDER BY clause


• ORDER BY clause is used to arrange data in ascending/descending order
• Ordering can be done on more than one column, in this case data is arranged according
first column and then second column and onwards.
• By default data is arranged in ascending order, in no ordering information (asc/desc)
is given.

Syntax:

SELECT */col_list
FROM tablename
ORDER BY col1 asc/desc, col2 asc/desc;
AGGREGATE FUNCTIONS
➢ An aggregate function performs a calculation on multiple values and returns a single value.
➢ These function work on multiple rows collectively return single value.
➢ List of Aggregate functions are
o max() : return maximum value in set of value
o min() – return minimum value from the set of values
o avg() –return average value in set of non-null values
o sum() - Return the summation of all non-NULL values of the set of values.
o count() - Return the number of rows in a group
▪ Count(*) – return number of rows, including rows with NULL
▪ Count(column_name) - return number of rows, excluding rows with NULL
for the given column

▪ Count (distinct column_name) – return number of rows with duplicate


removed
In above example there are 14 row in the EMP table, but distinct clause
only consider unique value.

➢ Group By Clause
o It is used in a SELECT statement to collect data across multiple records and group the
results by one or more columns.
Syntax:
SELECT column_name, aggregate_function
FROM table_name
GROUP BY column_name

In above example salary is grouped on job and maximum salary from each job is
displayed.
o Select clause involving group by clause can contain column present in group by clause,
aggregate function or no column. Otherwise it will return random data from other
column as given below.

➢ Having clause –
o Having clause is used to place condition on aggregate function in conjunction with
group by clause.
o Having clause in placed after where clause in select statement.
Syntax:
SELECT columm_name, aggregate_function(col_name)
FROM table
WHERE condition
GROUP BY column_name
HAVING aggregate_function(column_name) operator expression;

The above query will display deptno, maximum salary and number of employees from
each department.
The query given below display deptno, maximum salary and number of employees from
those department which have maximum salary greater than equal to 3000.

As condition is on aggregate function max(), where clause can’t be used in this case.
CREATE
i) Create the table HOSPITAL with datatypes and constraint as provided
COLUMN NAME DATA LENGTH CONSTRAINT
TYPE
NO Integer 5 PRIMARY KEY
NAME Character 20 NOT NULL
AGE Integer 3
DEPARTMENT Character 20 NOT NULL
DATEOFADM Date
CHARGES Float 7,2 Should not be less than zero
SEX Character 1 Default value if M
DOCTOR_ID Integer 4 References DOCTOR (D_ID)
ii) Create the table DOCTOR with datatypes and constraint as provided
COLUMN D_ID DOCTOR_NAME PHONE DATE_APPOINTMENT
NAME
DATATYPE Integer Character Character Date
LENGTH 3 20 10
CONSTRAINT PRIMARY NOT NULL UNIQUE
KEY
INSERT
i) Write the commands to insert the first two records in the table HOSPITAL
UPDATE
i) Change the Department of ZUBIN to RADIOLOGY
ii) Increase the Charges of Male patients by 5 %
iii) Input the age of ARUN as 26
DELETE
i) Delete the record of SHILPA
ii) Delete the record of all patients who under DOCTORID 104
ALTER
i) Add a new column Contact_Address char(30) to the table HOSPITAL
ii) Increase the column size of name by 10
iii) Add NOT NULL Constraint to Contact_Address column
DROP
i) Drop the table HOSPITAL

GROUP BY
i) Show the number of patients in each Department
ii) Show the average Charges paid by the patients in department ENT and CARDIOLOGY
iii) Show the min DATEOFADM of each Department where
minimum DATEOFADM isgreater than 22-Feb-1998
iv) SQL FUNCTIONS (STRING, MATHS and DATE/TIME)

➢ MATHS FUNCTIONS
Mathematical functions are also called number functions that accept numeric input and return
numeric values.

➢ DATE and TIME FUNCTIONS


Date functions operate on values of the DATE data type:
STRING FUNCTIONS
(a) Case-manipulation Functions These functions convert case for character strings:

JOINS
➢ A relational database consists of multiple related tables linking together using common
columns, which are known as foreign key columns.
➢ It is used retrieve data from multiple tables.
➢ Consider the tables below EMP, DEPT & SALGARDE that stored related information, all
the examples on join will be explained with help of these following three tables
EMP Table
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1993-06-13 800.00 0.00 20
7499 ALLEN SALESMAN 7698 1998-08-15 1600.00 300.00 30
7521 WARD SALESMAN 7698 1996-03-26 1250.00 500.00 30
7566 JONES MANAGER 7839 1995-10-31 2975.00 20
7698 BLAKE MANAGER 7839 1992-06-11 2850.00 30
7782 CLARK MANAGER 7839 1993-05-14 2450.00 10
7788 SCOTT ANALYST 7566 1996-03-05 3000.00 20
7839 KING PRESIDENT 1990-06-09 5000.00 0.00 10
7844 TURNER SALESMAN 7698 1995-06-04 1500.00 0.00 30
7876 ADAMS CLERK 7788 1999-06-04 1100.00 20
7900 JAMES CLERK 7698 2000-06-23 950.00 30
7934 MILLER CLERK 7782 2000-01-21 1300.00 10
7902 FORD ANALYST 7566 1997-12-05 3000.00 20
7654 MARTIN SALESMAN 7698 1998-12-05 1250.00 1400.00 30
DEPT TABLE
DEPTNO DNAME LOCATION
10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Boston

SALGRADE TABLE
GRADE LOSAL HISAL
1 700.00 1200.00
2 1201.00 1400.00
4 2001.00 3000.00
5 3001.00 99999.00
3 1401.00 2000.00
➢ Types of Join
❖ Cartesian Product or Cross join
❖ Equi Join
❖ Natural Join

❖ Non-Equi Join
❖ Self Join
❖ Left Outer Join
❖ Right Outer Join

➢ Cartesian Product or Cross join


❖ The cross join makes a Cartesian product of rows from the joined tables.
❖ The cross join combines each row from the first table with every row from the right
table to make the result set.
➢ If Table1 has degree d1 and cardinality c1 and table2 has degree d2 and cardinalityc2, their
Cartesian Product has degree d=d1+d2 and cardinality c=c1*c2;Equi Join-
❖ It performs a JOIN against equality or matching column(s) values of the associated
tables.
Ven Diagram

Syntax
SELECT * / Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;
OR
SELECT * / Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;

Example: SELECT * FROM emp JOIN dept ON emp.deptno=dept.deptno;


OR
SELECT * FROM emp, dept
WHERE emp.deptno=dept.deptno;

Example 1: Display the employee name, sal and name of department name

Ans: In the above query ename and sal belong to emp table whereas dname belongs to DEPT
table. So, to retrieve data in this we will use join

SELECT emp.ename, emp.sal, dept.dname


FROM emp, dept WHERE emp.deptno=dept.deptno;

Note:
❖ In case of join full qualified (table_name.column_name) name is used to avoid
ambiguity as both table contains common columns as PRIMARY KEY and
FOREIGN KEY.
❖ Table Alias – Like column alias table alias can be used in case of join as given below.
SELECT e.ename, e.sal FROM emp e, dept d WHERE emp.deptno=dept.deptno;
➢ Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.Natural Join
❖ A natural join is a type of join operation that creates an implicit join by combining
tables based on columns with the same name and data type.
❖ It makes the SELECT query simpler with minimal use of conditions.
❖ There is no need to specify the name of common column in the SELECT statement.
❖ Common column is present only once in the output.

Syntax:
SELECT */column_list
FROM Table1 NATURAL JOIN TABLE2;
OR
SELECT * / column_list
FROM TABLE1 join on common_column_name;

Example :
SELECT * FROM emp JOIN dept USING(deptno);
OR
SELECT * FROM emp NATURAL JOIN DEPT;
Output:
Example
Consider the following tables – Bank_Account and Branch:
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current

Table: Branch
ACode City
A01 Delhi
A02 Mumbai
A01 Nagpur

SELECT * FROM Bank_Account NATURAL JOIN Branch;


Acode Name Type City
A01 Amrita Savings Delhi
A01 Amrita Savings Nagpur
A02 Parthodas Current Mumbai

➢ Difference between Equi-Join vs Natural Join

EQUI-JOIN NATURAL JOIN


Join performed on equality of value of the Join is performed on column having common
columns name.
Where clause is used to specify the condition There is no need to use where clause
Both columns from tables are displayed in the Common column is displayed only once
result.

You might also like