Mysql Notes October 03 2023

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

CLASS XII -COMPUTER SCIENCE (083)

UNIT III - DATABASE MANAGEMENT


Database Concepts
A database management system (DBMS) or database system in short, is
software that can be used to create and manage databases.
DBMS Iets users to create a database, store, manage, update/modify and
retrieve data from that database by users or application programs.
Some examples of open source and commercial DBMS include MysQL, Oracle,
PostgreSQL, SQL Server, Microsoft Access, MongoDB.
The DBMS serves as an interface between the database and end users or
application programs.
Retrieving data from adatabase through special type of commands is called
querying the database.
Databases are widelyused in various fields. Some applications are given in Table
Appllcation Database to maintain data about
Banking customer information, account details, loan details,
transaction details, etc.
Crop Loan kisan credit card data, farmer's personal data, land
area and cultivation data, loan history, repayment
data, etc.
Inventory product details, customer information, order details.
Management delivery data, etc.
Organisation employee records, salary details, department
Resource information, branch locations, etc.
Management
Online items description, user login details, users
Shopping preferences details, etc.

Advantages of Database System


1. Databases reduce Redundancy - It removes duplication of data because data are
kept at one place and all the application refers to the centrally maintained database.
2. Database controls Inconsistency - When two copies of the same data do not agree
to each other, then it is called Inconsistency. By controlling redundancy, the
inconsistency is also controlled.
3. Database facilitates Sharing of Data - Data stored in the database can be shared
among several users.

4. Database ensures Security -Data are protected against accidental or intentional


disclosure to unauthorized person or unauthorized modification.
5. Database maintains Integrity - It enforces certain integrity rules to insure the
validity or correctness of data. Ex. A date can't be like 31/31/2000.
Keyconcepts in DBMS
In order to efficiently manage data using a DBMS, let us understand certain key
terms:

" Database schema is the design of adatabase.


A database constraint is a restriction on the type of data that that can be
inserted into the table.
Database schema and database constraints are stored in database catalog.
The snapshot of the database at anygiven time is the database instance.
and data
A query is a request to a database for information retrieval
manipulation (insertion, deletion or update). It is written in Structured Query
Language (SQL).
Relational Data Model
Relational DBMS (RDBMS) is used to store data in related tables.
Themost commonly used data model is Relational Data Model.
Other types of data models include object-oriented data model, entity
relationship data model, document model and hierarchical data model.
In relational model, Rows and columns of a table are called tuples and
attributes respectively. A table is referred to as relation.

Relatton GUARDIAN
utth 4 attrnbute/
columns

GUD GName GPhone GAddress


444444444444 Amit Ahuja 5711492685 G-35, Ashok Vihar, Delhi
111111111!1 Baichung Bhutia 71l10047 139 Flat no. 5, Darjeeling Appt. Shimla
101010101010 Himanshu Shah 9818184855 26/77, West Patel Nagar, Ahmedabad
333333333333 Danny Dsouza S -13.Ashok Village. Daman
(466444444666 Sujata P. 7802983674 HNO-13, B- block, Preet Vihar, Madurai

Facts about RELATION GUARDLAN


1 Degree tNumber of attrnbutes) 4 Record tuple/rou
2 Cardnal1ry Number of rows/ tuples /re cords 5
3 Relatton is a fiat ile Le,each column has a single value and each record
has same number of columns

Fig:Relation GUARDIAN with its attributes and tuples

Attribute: The columns of a relation are the attributes which are also referred as
fields. For example, GUID, GName, GPhone and GAddress are attributes of relation
GUARDIAN.

Tuple: Each row of data in a relation (table) is called a tuple. In a table with n
columns, a tuple is a relationship between the n related values.
2
Domain: It is a set of values from which an ttribute can take avalue in each row.
Usually,a data type is used to specify domain for an attribute.
Degree: The number of attributes in a relation is calledthe Degree of the relation. for
example, relation GUARDIAN with four attributes is a relation of degree 4,
Cardinality: The number of tuples in arelation is called the Cardinality of the relation.
For example, the cardinality of relation GUARDIAN 0s 5as there are 5 tuples in the
table.

KEYS IN A RELATIONAL DATABASE


Destructions on data stored in a RDBMS is applied by use of keys such as Candidate
Key, Primary Key, Composite Primary Key and Foreign Key.
Candidate Key
" Arelation can have one or more attributes that takes distinct values.
Any of these attributes can be used to uniquely identify the tuples in the
relation.Such attributes are called candidate keys as each of them are
candidates for the primary key.
As shown in Figure , the relation GUARDIAN has four attributes out of which
GUIDand GPhone always take unique values. No two guardians willhave same
phone number or same GUID. Hence, these two attributes are the candidate
keys as they both are candidates for primary key.
Primary Key
Primary key in a relation is used for unique identification of tuples.
The remaining attributes in the list of candidate keys are called the alternate
keys.
In the relation GUARDIAN, Suppose GUID is chosen as primary key, then
GPhone will be called the alternate key.
Composite Primary Key

If nosingle attribute in arelation is able to uniquely distinguish the tuples, then


more than one attribute is taken together as primary key.
" Such primary key consisting of more than one attribute is called Composite
Primary key.
" In relation ATTENDANCE, Roll Number cannot be used as primary key as roll
number of same student will appear in another row for a different date.
Similarly, in relation Attendance, AttendanceDate cannot be used as primary
key because same date is repeated for each roll number. However,
combination of these two attributes RollNumber and AttendanceDate together
3
would always have unique value in ATTENDANCE table as on any working day,
OT astudent would be marked attendance only once. Hence {RollNumber,
AttendanceDate} will make the of ATTENDANCE relation composite primary
key.
Foreign Key
" Aforeign key is usedto represent the relationship between two relations.
A foreign key is an attribute whose value is derived from the primary key of
another relation.
" This means that any attribute of a relation (referencing), which is used to refer
contents from another (referenced) relation, becomes foreign key if it refers to
the primary key of referenced relation.
The referencing relation is called Foreign Relation.
In some cases, foreign key can take NULL value if it is not the part of primary
key of the foreign table.
The relation in which the referenced primary key is defined is called primary
relation or master relation.

STUDENT RollNumber SName SDateofBith GUID

GUARDIANGUID GName GPhone GAddress

ATTENDANCE AttendanceDate RollNumber AttendanceStatus

Fig: STUDENTATTENDANCE database with the primary and foreign keys.


SQL- STRUCTURED QUERY LANGUAGE
Introduction
RDBMS also allowus to store, retrieve and manipulate data on that database
through queries.
There are many RDBMS such as MySQL, Microsoft SQL Server, PostgreSQL,
Oracle, etc. that allowus to create adatabase consisting of relations.
In this chapter, we will learn how to create, populate and query databases
using MySQL.
SQL - Structured Query Language
SQL is easy to learn as the statements comprise of descriptive English words
and are not case sensitive.
We can create and interact with a database using SQL easily.
SQL provides statements for defining the structure of the data, manipulating
data in the database, declaring constraints and retrieving data from the
database in variousways, depending on our requirements.
Installing MysQL
MysQL is an open-source RDBMS software which can be easily downloaded
from the officialwebsite https://dev.mysql.com/downloads.
" After installing MySQL, start MySOQL service.
The appearance of mysql> prompt means that MySQL is ready to accept SQL
statements.
M, I8)(unthand Lue Clhent
Enter password:
Welcome to the HysQL nonitor. Commands end with ; or lg.
Your Hy SQL connectíon id is 43
Server versíon: s.e.9-dmr- log NysQL Conmunity Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a reglstered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
OHners.

Type help;' or '\h' for help. Type '\c' to clear the current ínput statement
nysql> create table temp(id int);
1046 (3De00): No database selected

Fig., MySQL Shell


Following are some important points to be kept in mind while using SQL:
SQL iscase insensitive. For example, the column names 'salary' and 'SALARY'
are the same for SQL.
Alwaysend SQL statements with a semicolon (:).
Toenter multiline SQL statements, we don'twrite "" after the first line. We
press the Enter key to continue on the next line. The prompt mysql> then
5
changes to "->", indicating that statement is continued to the next line. After
the last line, put ";" and press enter.
Data Types in MySQL
can
Data type of an attribute indicates the type of data value that an attribute
that
have. It also decides the operations that can be performed on the data of
attribute.
Commonly used data types in MySQL are,
Data ty Description
any valuc from 0 to
Sprcihes character tvpe data of lcngth n where n could bc
255 CHAR is of fixed length. mcans, declaring CHAR (10) implies to re serve
'city' has
spaces for 10 charactcrs. If data does not have 10 characters (e.g.. padded
four characters). MySÌL Glls the remaining 6 characters with spaces
on the nght
Speifics harctrt tvpe data of lcngth where n could be any value from 0 to
65535 But unlhkr CHAR VARCHARín) is a varialble length data type. That is,
ir laring VARCHAR (301 mcan a maKInun of 30 characteis can be stored but
the a iial allx ated bytrs ill dcpend on the lcngth of cntered string. So 'city
1n VAKCHAR 30) wall cxupy space nccded to store d chaacters only
INT spccifhes an ntger valur Each INT value CCUpies 4 bvtcs of storage. The
Tange of unsigird valuCs alloaed n a 4 byte nteger type are O to 4,294,967,295.
For values larger than that, we have to use BlGINT, which occupies 8 bytes.
IHolds numbera wth dreimal posnts Each FLOAT value orrupies 4 bytes,
The DTE Ype in Usrd for dates in YYYY MM-DD format. YYYY is the 4 digit
vrat, MM in the 2 digt month and DD n the 2 digit date. The supported range
In 1000 01 01 to 999 12-31

Constraints

Constraints are the certain types of restrictions on the data values that an
attribute can have.
They are used to ensure correctness of data.
However, it is not mandatory to define constraints for each attribute of a table.
Commonly used SQL Constraints are,
Constralnt Deseription
Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applcable value
Fnsurcs that all the values in a column arr distinct/unique
Adefault value spec1fed for the column if no value is pronded
The column which can unqucly dentufv cach row /record in atable
The column which refers to value of an attrnbute de fined as prmary key in another
table

Types of SQL Commands


" DDL (Data Definition Language) To create database and table structure
commands like CREATE, ALTER, DROP etc.
" DML (Data Manipulation Language)- Record/rows related operations.
commands like INSERT..,DELETE.., UPDATE.. etc.
" DQL (Data Query Language) -To retrieve data from the tables in a databse.
commands like SELECT.
6
SQL for Data Definition

SQL allows us to write statements for defining, modifying and deleting relation
schemas. These are part of Data Definition Language (DDL).
The Create statement is used tocreate adatabase and its tables (relations).
Before creating a database, we should be clear about the number of tables the
database will have, the columns (attributes) in each table along with the data
type of each column, and its constraint, if any.
CREATE Database

To create a database, we use the CREATE DATABASE Statement as shown in the


following syntax:
CREATE DATABASE databasename;
To create a database called Employee, we will type following command at mysql
prompt.

mysql> CREATE DATABASE Employee;


Query OK, 1 rowaffected (0.02 sec)
" ADBMS can manage multiple databases on one computer.
Therefore, we need toselect the database that we want to use.
To know the names of existing databases, we usethe statement,
SHOW DATABASES.
From the listed databases, we can select the database to be used.
C Once the database is selected, we can proceed with creating tables or
querying data.
In order to use the Employee database, the following SQL statement is
required.
mysql> USE Employee;
Database changed initially; the created database is empty. Itcan be checked
by using the show tables statement that lists names of all the tables within a
database.
mysql> SHOW TABLES;
Emptyset (0.06 sec)
CREATE Table

After creating adatabase Employee, we need to define relations in this


database and specify attributes for each relation along with data type and
constraint (if any) for each attribute.
This is done using the CREATE TABLE statement.
7
Syntax:
constraint,
CREATE TABLE tablename( attributenamel datatype
attributename2 datatype constraint, .....
attributenameN datatype constraint);
to the CREATE TABLE
It is important to observe the following points with respect
statement:

The number of columns in a table defines the degree of that relation, which is
denoted by N.
Attribute name specifies the name of the column in the table.
Datatype specifies the type of datathat an attribute can hold.
Constraint indicates the restrictions imposed on the values of an attribute.

Example:
Create table e1(eid integer, empname varchar(20), dob date, dpmt_id char(10) );
(or)
Create table el(eid integer primary key, empname varchar(20), dob date, dpmt_id
char(10));
Note: "" is used to separate two attributes and each statement terminates with a
semi-colon (;).
Describe Table

" We can view the structure of an already created table using the DESCRIBE
statement or DESC statement.

Syntax:
DESCRIBE tablename;
Ex: mysql> DESCRIBE el;
Field Type Null Key Default Extra
eid int 11) NO PRI NULL
ename varchari 20) YES NULL
dob date YES NULL

guic char10) YES

8
Alter Table
ALTER TABLE statement is used to make changes in the structureof a table like
adding, removing or changing datatype of column(s).
Add an attribute to an existing table
Sometimes, we may need to add an additional attribute in a table. It can be
done using the ADD attribute statement as shown in the following Syntax:
ALTER TABLE table_name ADD attributename DATATYPE,
Ex: mysql> ALTER TABLE e1 ADD salary integer;
Remove an attribute
Using ALTER,we can remove attributes from a table,as shown in the following
syntax: ALTER TABLE table_name DROP attribute;
To remove the attribute dept id from table el, write the following MysQL
statement:

mysql> ALTER TABLE e1 DROP dept_id;


Add primary key to arelation
The following MySQL statement adds a primary key to the el relation:
mysql> ALTER TABLE el ADD PRIMARY KEY (eid);
Remove primary key from the table
Sometime there may be arequirement to remove primary key constraint from
the table.
In that case, alter table command can be used in the following way:
Syntax: ALTER TABLE table_name DROP PRIMARY KEY;
Ex: mysql> ALTER TABLE e1 DROP PRIMARY KEY;
DROP Statement
We can use a DROP statement to remove a database or a table permanently
from the system.
Syntax to drop atable:DROP TABLE table_name;
Syntax to drop a database: DROP DATABASE database_name;
Note: Using the DROP statement toremove adatabase willultimately remove all the
tables within it.
SQL for Data Manipulation
has no data.
When we create a table, only its structure is created but the table
To populate records in the table, INSERT statement is used.
and UPDATE
Also, table records can be deleted or updated using DELETE
statements.
These SQL statements are part of Data Manipulation Language (DML).
INSERTION of Records
INSERT INTO statement is used to insert new records in a table.

Its syntax is: INSERT INTO tablename VALUES(value 1, value 2,....);


Here, value 1 corresponds to attribute 1, value 2 corresponds to attribute 2 and
SO on.

The following insert statement adds the first record in the table:
mysql> INSERT INTOe1 VALUES (1,"Siva" "1998/07/03","A11",25000 );
We can use the SQL statement SELECT * from table name to view the inserted
records.
If we want to insert values only for some of the attributes in a table (supposing
other attributes having NULL or any other default value), then we shall specify
the attribute names in which the values are to be inserted using the following
syntax of INSERT INTO statement.

Syntax: INSERT INTO tablename (column1, column2, ..) VALUES (valuel, value2, ...J.
Ex., insert into el (eid, empname, dob, salary) values (1, "Siva", "1998/07/03",
25000);
SQL for Data Query
SQL provides efficient mechanisms to retrieve data stored in multiple tables in
MysQL database (or any other RDBMS).
The SQL statement SELECT is used to retrieve data from the tables in a
database and is also calledaquery statement.
SELECT Statement

The SQL statement SELECT is used to retrieve data from the tables in a
database and the output is also displayed in tabular form.
Syntax: SELECT attribute1, attribute2, ...FROM table_name WHERE condition;

10
Note:

Here, attribute1, attribute2, ...are the column names of the table table_name
from which we want to retrieve data.
The FROM clause is always written with SELECT clause as it specifies the name
of the table from which data is to be retrieved.
specified
The WHERE clause is optional and is used to retrieve data that meet
condition(s).
statement:
Toselect allthe data available in a table, we use the following select
SELECT * FROM table_name;
Ex., Select * from el;
eid empname dob dept_id salary
1 Siva 1998-07-03 A11 25000

QUERYING using Database OFFICE


(a)Retrieve selected columns - The following query selects employee numbers of all
the employees:
mysql> SELECT eid FROM e1;
eid
1

The following query selects the employee number and employee name of all the
employees, we write:
mysql> SELECT eid, empname FROM e1;
eid empname
1 Siva

(b)Renaming of columns -In case we want to rename any column while displaying
the output, it can be done by using the alias 'As'. The following query selects
empname as ename in the output for allthe employees:
mysql> SELECT empname as ename FROM el;
ename

Siva

11
(c) Distinct Clause

" By default, SQL shows all the data retrieved through query as output.
" However, there can be duplicate values.
" The SELECT statement when combined with DISTINCT clause, returns records
without repetition (distinct records).
For example, while retrieving a dept id from employee relation, there can be
duplicate values as many employees are assigned to the same department.
To select unique department number for all the employees, we use DISTINCT as
shown below:

mysql> SELECT DISTINCT dept id FROM e1;


dept_id
A11

(d) WHERE Clause


" The WHERE clause is used to retrieve data that meet some specified conditions.
In the OFFICE database, more than one employee can have the same salary.
Following query gives distinct salaries of the employees working inthe
department number A11:
mysql> SELECT DISTINCT Salary FROM e1 WHERE dept id='A11';
salary
25000

" In the above example, = operator is used in the WHERE


clause.
Other relational operators (<=, >, >=, !=)can be used to specify such
The logical operators AND, OR, and NOT are used to combine
conditions.
multiple
conditions.
Ex.1, display allthe details of those employees of A11
than 5000. department who earn more
mysql> SELECT * FROM e1 WHERE salary> 5000 AND dept_ id
='A11';
Ex.2, The following query selects records of all the
employees except Siva.
mysql> SELECT * FROM e1 WHERE NOT ename = 'Siva';
Ex.3, The following query selects the name and
who are earning salary between 20000 and 50000 department id of all those employees
(both values inclusive).
12
mysql> SELECT ename, dept_id FROM el WHERE Salary>=20000 AND Salary<=50000;
Ex.4, The query defines arange that can also be checked using a comparison operator
BETWEEN, as shown below:
mysql> SELECT ename, dept id FROM e1 WHERE salaryBETWEEN 20000 AND 50000;
Ex.5, The following query selects details of allthe employeeswho work in the
departments having dept_id A11, B11 or C11.
mysq1> SELECT * FROM el WHERE dept id ='A11'OR dept_id = 'B11' OR dept id =
'C11';
(e) Membership operator IN
The IN operator compares a value with a set of values and returns true if the
value belongs to that set.
" The above query can be rewritten using IN operator as shown below:
mysql> SELECT *FROM e1 WHERE dept_id IN ('A11, 'B11','C11');
(f) ORDER BY Clause

ORDER BY clause is used to display data in an ordered form with respect to a


specified column.
By default, ORDER BY displays records in ascending order of the specified
column's values.
To display the records in descending order, the DESC (means descending)
keyword needs to be written with that column.
Example, the following query selects details of all the employees in ascending
order of their salaries.

mysql> SELECT * FROM e1 ORDER BY salary;


(g) Handling NULL Values
sQL supports aspecial value called NULL to represent a missing or unknown
value.

mysql> SELECT * FROM e1 WHERE Bonus IS NULL;


(H)Substring pattern matching
Many a times we come across situations where we do not want to query by
matching exact text or value.
Rather,we are interested to find matching of only a few characters or values in
column values. For example,to find out names starting with T" or tofind out
pincodes starting with '60'. This is called substring pattern matching.
13
for an
We cannot match such operator as we are not looking
" patterns using =
exact match.

SQL provides a LIKE operator that can


heucod with the WHERE clause to search
for aspecified pattern in a column.
characters:
The LIKE operator makes use of the following two wild card
characters
o % (percent)- used to represent zero, one, or multiple
O_(underscore)- used to represent exactly asingle character
Ex.1, the following query selects details of all those employees whose name starts
with'S',

mysql> SELECT * FROM e1 WHERE ename like S%';


Ex.2, the following query selects details of allthose employees whose name ends
with 'n', and gets a salary more than 45000.
mysql> SELECT * FROM e1 WHERE ename like %n' ANDsalary >45000;
Ex.3, the following query selects details of all those employees whose name consists
ofexactly Sletters and starts with any letter but has 'ANYA' after that.
mysql> SELECT * FROM e1 WHERE ename like_ANYA';
Data Updation and Deletion
Updation and deletion of data are also part of SQL Data Manipulation Language
(DML).
Data Updation
We may needto make changes in the value(s) of one or more columns of
existing records in atable.
For example, we may require some changes in address, phone number or
spelling of name, etc.
The UPDATE statement is used to make such modifications in existing data.
Syntax: UPDATE table_name SET attributel =value1, attribute2 = value2, ... WHERE
condition;
We can then verify the updated data using the statement SELECT * FROM e1.
DataDeletion
" DELETE statement is used to delete/remove one or more records from a table.
Syntax: DELETE FROM tabBe_name WHERE condition;
mysgl> DELETE FROM e1 WHERE eid = 2;

14
Aggregate Functions
Aggregate functions are also called Multiple Rowfunctions.
These functions work on aset of records asSa whole and return asingle value
Tor each column of the records on which the function is
applied.
Function Description Example with output
Max(column) Keturns the largest value mysal> SELECT MAX(salary) FROM el;
from the specified Output: 45000
column
e1;
Min(column) Keturns the largest valuemysgl> SELECT MIN(salary) FROM
from the specified Output: 22000
column
Sum(column) Returns the average of mysql> SELECT SUM(salary) FROM e1;
the values in the Output: 100000
specified column.
AVG(salary) FROM e1;
Avg(column) Returns the average of mysql> SELECT
the values in the
specified column.
Count(column) Returns the number of mysql> SELECT COUNT(salary) FROM
values in the specified e1;
column ignoring the
NULL values.
Count(*) Returns the number of mysql> SELECT COUNT(*)FROM el;
records in a table.
GROUP BY Clause in SQL
GROUP BY function is used to group rows of a table that contain the same
values in aspecified column.
. Wecan use the aggregate functions (COUNT, MAX, MIN, AVG and SUM) to
work on the groupedvalues.
HAVING Clause in SQL isused to specify conditions on the rows with Group By
clause.

Ex., select city, Sum{salary) from emp Group by city;

15
Cartesian product on two tables
Cartesian product operation combines tuples from two relations.
It results in all pairsof rows from the two input relations, regardless of whether
or not they have the same values oncommon attributes.
" It isdenoted as "X'.
" The degree of the resulting relation is calculated as the sum of the degrees of
both the relations under consideration.
The cardinality of the resulting relation is calculatedas the product of the
cardinality of relations on which cartesian product is applied.
Let us use the relations p1 and p2 toshowthe output of cartesian product.
Note that both relations are of degree 3. The cardinality of relations p1and p2
is 2 and 3 respectively.
Applyingcartesian product on these two relations willresult in a relation of
degree 6 and cardinality 6, as shown in Table.
Example,
p1
no
p2
name dept no
1 arun admin
name dept
1 ajay admin
2 siva sales
2 siva sales
3 bala hr
p1 X p2
no name dept no name dept
arun admin 1 ajay admin
2 siva sales 1 ajay admin
1 arun admin 2 siva sales
2 siva sales 2 siva sales
arun admin 3 bala hr
2 siva sales 3 bala hr

We learnt that application of operator cartesian product on two tables results


in a table having allcombinations of tuples from the underlying tables.
When more than one table is to be used in a query, then we must specify the
table names by separating commas in the FROM clause, as shown in Example.
On execution of such a query, the DBMS (MySql) will first apply cartesian
product on specified tables to have a single table.
The following query of example applies cartesian product on the two tables p1
and p2:
16
Example,
a)Display allpossible combinations of tuples of relations p1 and p2.
mysql> SELECT* FROM p1, p2;
As we are using SELECT * in the query, the output will be the Table having degree 6
and cardinality6.
b) From the all-possible combinations of tuples of relations p1 and p2 display only
those rows such that the attribute name in both have the same value.

mysql> SELECT * FROM p1 x, p2y WHERE x.name y. name;


no name dept no name dept
2 siva sales 2 siva sales

JOIN on two tables


from two or more tables
Join is an operation which is used to combine rows
based on one or more commonfields between them.
UName, UColor) and COST (UCode,
Let us create two tables UNIFORM (UCode,
Size,Price) in the EmployeeUniform database.
Size is the Composite Key
UCode is Primary Key in table UNIFORM. UCode and
in table COST.
between the two tables which can be
" Therefore, Ucode is a common attribute
tables.
used to fetch the common data from both
table while creating
Hence, we need to define Ucode as foreign key in the Price
this table.

Uniform Table Cost Table

Ucode Uname Ucolor Ucode Size Price


1 Shirt White 1 580
2 Pant Grey 1 M 500
2 Tie Blue 2 890
M 810
of tables
Example List the UCode, UName, UColor, Size and Price of related tuples
given
UNIFORM and COST. The given query may be written in three different ways as
below.

17
a) Using condition in where clause
mysql> SELECT * FROM UNIFORM U, coST CWHERE U.UCode = C.UCode;
b) Explicit use of JOIN clause
mysql> SELECT * FROM UNIFORMUJOIN CoST C ONU.Ucode=C.Ucode;
c) Explicit use of NATURAL JOIN clause
The output of queries (a) and (b) shown in Table, has a repetitive column Ucode
having exactly the same values.
Thisredundant column provides no additional information.
There isan extension of JOINoperation called NATURAL JOIN which works similar
to JOIN clause in SQL but removes the redundant
attribute.
This operator can be used to join the contents of two tables if there is one
common attribute in both the tables.
Theabove SQL query using NATURAL JOIN is shown below:
mysql> SELECT * FROM UNIFORM NATURAL JOIN COST;
Following are some of the points to be considered while applying JOIN operations on
two or more relations:

If two tables are to be joined on equality condition on the


common attribute,
then one may use JOIN with ON clause or NATURAL JOIN in FROM clause. If
three tables are to be joined on equality condition, then two JOIN or
NATURAL
JOIN are required.
In general, N-1 joinsare needed to combine Ntables on
equality condition.
With JOIN clause, we may use any relational operators to
combine tuples of
two tables.

18

You might also like