Xii-Unit III-dbms Complete Notes
Xii-Unit III-dbms Complete Notes
COMPUTERSCIENCE(083)
UNIT-III DATABASEMANAGEMENTSYSTEM
Page1
CHAPTER-9DATABASEMANAGEMENTSYSTEM(DBMS)
INTRODUCTION:
DBMSisacollectionofinterrelateddatainarrangedformandsetofprogramsusedto access
those data.
AdvantagesofDBMS:
Controlofdata redundancy
Data consistency
Sharingofdata
Data Integrity
Data isolation
Privacyand Security
DATAMODELS:
Datamodelsdescribethestructureofthedatabase.Therearefourdatamodelsin DBMS:
1. RelationalDataModel
2. HierarchicalDataModel
3. NetworkModel
4. ObjectOrientedDataModel
1. RelationalDataModel:Thisdatabaseconsistsofacollectionoftable.Thesetables
arecalledrelations.Arowinatablerepresentsarelationshipamongasetofvalues.
Relation:Arelationisatablewithcolumnsandrows.
Tuple:Arowofarelation ORarowofa table.
Domain:Asetofvaluesforthe columns.
Attribute:Columnnameofarelation.
Degree:Numberofattributesinatable.
Cardinality:NumberoftuplesORNumberofrowsinatable.
View:Avirtualtablethatdoesnotexistsbutitisderivedfromother table.
Page2
Roll_No. St_Name Fname Marks Percentage
2. HierarchicalDataModel:Inthismodelthedataarerepresentedbycollectionand
relationship between data are represented by links. In this model the collection of
data are organized as tree.
4. Object Oriented Data Model: In this model the data and its operations are
represented by objects.
NOTE:Some Definitions:-
Record:Collectionofattributes
File:Collectionofrecords
KEYS:
1. PrimaryKey
2. CandidateKey
3. AlternateKey
4. ForeignKey
1. Primary Key:A primary key is a set of one or more attributes that can uniquely
identify tuples within the relation. This key does not have duplicate values in the
relation. There must be any value for this key, it cannot be NULL.
Page3
PrimaryKey
Table:STUDENT
2. CandidateKey:Allattributescombinationinsidearelationthatcanserveasa primary
key, is called candidate key.
{Name,F_Name} CandidateKey
{Name,DOB}
3. Alternate Key: A candidate key that is not the primary key is called an
alternatekey.
4. Foreign Key: A non-key attribute whose values are derived from the primary key
of some other table, is known as foreign key in its current table.
Primarykeyofparenttablebecomestheforeignkeyforthechild table.
Page4
INTRODUCTIONTOMySQL:
Introduction:
MySQLstandsforMyStructuredQueryLanguage.
MySQL is freely available, Open source Relational Database Management
System (RDBMS).
Featuresof MySQL:
a. Cost:Freelyavailable
b. Performance:MySQLis fast.
c. Simplicity:MySQLiseasytoinstall.
d. HighPerformance
e. DataSecurity:Inhaspowerfulmechanismfor ensuringonlyauthorizedusershave
access the data.
f. Flexibility
STARTINGMySQL:
Page5
FirstyouhavetoinstallMySQLonyoursystem.Thenclickon
SQL:-
SQLstandsforStructuredQueryLanguage.
Thisisnon-proceduralLanguage.
Thisisthecommonlanguageforrelationaldatabase.Meansthislanguageisused in
MySQL.
DifferencebetweenSQLand MySQL:
SQL MySQL
Thisisthelanguagethatusedin database.
Thisistheopensourcedatabase.
Page6
SQLElements:
TherearefourbasicelementsofSQL:
1. Literal
2. DataTypes
3. Nulls
4. Comments
1. Literal:Aliteralisafixeddatavalue.Thisfixvaluemaybenumericor character.
Integer Literal(75,+23,-765,34)
Float,Real,doubleLiteral
(-2300, -23E2, 0.1256)
Character Literal: All character literals are enclosed in single quotation mark or double
quotation marks.
Forexample:-„a‟,“yogesh”,„5‟,“xyz5”
2. Data Types:- Data types are rules that define what data maybe stored in a column
andhowthatdataisactuallystored.DatatypesusedinMySQLcategorizedintofour
categories:
(i) Numeric
(ii) String
(iii) DateandTime
(iv) Binary
Page7
(i) Numeric:Thisdatatypestoresnumbers.
Int Normalsizeintegerthatcanbesignedorunsigned.Width
upto11 digits.
TinyInt Averysmallintegerthatcanbesignedorunsigned.Width
upto4digits.
SmallInt Asmallintegerthatcanbesignedorunsigned.Widthupto
5digits.
MediumInt Amediumsizeintegerthatcanbesignedorunsigned.
Widthupto9digits.
BigInt Alargeintegerthatcanbesignedorunsigned.
Float(M,D) Afloatingpointnumber.
M:-Lengthoftotalnumber D
:- Number of decimals Ex.-
Float(10,2)
10isthetotalnumberofdigitsand2isthenumberof decimals.
DOUBLE(M,D) Adoubleprecisionfloatingpointnumber.
Decimal(M,D) Floatingpointvalueswithvaryinglevelsofprecision.
(ii) String:
Char(M) Afixlengthstringbetween1to255characters.
M :-Length
Varchar(M) Avariablelengthstringbetween1to255characters.
Enum Acceptsoneofapredefinedsetofstrings.
Text Variablelengthtextwithamaximumsizeof64K.
TinyTEXT Sameastext,butwith amaximumsizeof255 bytes.
MediumTEXT Sameastext,butwith amaximumsizeof 16K.
LongTEXT Sameastext,butwith maximumsizeof 4GB.
TIME StoresthetimeinHH:MM:SSformat.
YEAR(M) Storesayearina2digitsor4-digits. M :-
Length
Example:YEAR(2)means98
YEAR(4)means1998
Page8
(iv) Binary Data Type: Stores the data in binary objects, such as graphics, images,
multimedia etc.
BLOB StandsforBinaryLarge Objects.
MaximumLength=64K
TINYBLOB Maximumlength=255bytes.
MEDIUMBLOB MaximumLength=16MB
LONGBLOB Maximumlength= 4GB
3. NULL values: If a column in a row has no value, then column is said to be
null.NULLs can appear in a column if the column is not restricted by NOT NULL
orPrimary Key. You should use a null value when the actual value is not
known.Null and Zero is not equivalent. Any arithmetic expression containing a
nullalways evaluates to null.
Example:7+null=null
7+0=7 Differencebetweennullandzero.
4. Comments:Commentisatextthatisnotexecuted.Therearetwotypesofcomments that
we use in MySQL.
(i) Single line Comment: Beginning with two hyphens (--) OR beginning
with # symbol.
(ii) MultiLineComment: /*………………………………………..
…………………………………….*/
Differencebetweencharand varchar:
Char Varchar
1.Fixedlengthcharacterstring. Variablelengthcharacterstring.
2.Whenacolumnisgivendatatype as
Each value that is stored in this
char(N). If a value is shorter
columnstoresexactlyasyouspecify
thanthislengthNthenblanksare
it.Noblanksareadded,if thelength is
added,butthesizeofvalue
shorter than maximum length N.
remainsN byte.
3.Fastertoaccess. Takeslessdiskspace.
Page9
ClassificationofSQLcommands:
SQLcommandsarecategorizedintofoursublanguages:
(i) DataDefinitionLanguage(DDL)
(ii) DataManipulationLanguage(DML)
(iii) TransactionControlLanguage(TCL)
(iv) DataControlLanguage(DCL)
(i) DataDefinitionLanguage(DDL):Itconsistthecommandstocreateobjectssuch as
tables, views, indexes etc. in the database.
COMMANDS:CREATE,ALTER,DROP,RENAME,TRUNCATE
(ii) Data Manipulation Language (DML): It is used for queries. It allows you to
performdatamanipulatione.g.retrieval,insertion,deletion,modificationofdata
stored in database.
COMMANDS:SELECT,INSERT,UPDATE,DELETE
(iii) Transaction Control Language (TCL): This language allows you to manage
and control the transaction.
COMMANDS:COMMIT,ROLLBACK
NOTE:-SavepointisalsousedinTCL.
(iv) DataControlLanguage(DCL):Thislanguageisusedtocontroldataandaccess to
the databases. It is used for protecting the data from unauthorized access.
COMMANDS: GRANT, REVOKE
SQLQUERIES:
In MySQL, to create new tables or query, the user must specify the database. This
database is called current database.
TochecktheavailabledatabaseinMySQL:-
SHOWdatabases;
Syntax:- USEdatabase-name;
Page10
Adatabasehastables.Tableshaverowsand columns.
Toshowtheavailabletablesinthedatabase:-
SHOWtables;
CREATINGDATABASE:InMySQLwecancreatethedatabasesusingCREATEDATABASE
statement.
Syntax:CREATEDATABASE<database-name>;
Example:CREATEDATABASEBank;
OPENINGDATABASE:
Syntax: USE<database-name>;
Example:USE Bank;
Syntax:DROPDATABASE<database-name>;
Example:DROPDATABASEBank;
CreatingTablesinMySQL:
TablesarecreatedusingCTREATETABLEcommand.
A table has rows and columns. The column name must be specified along the data type.
Each table must have at least one column.
Syntax:
CREATETABLE<table-name>(<column-name><data-type>(size),<column-name>
<data-type>(size),<column-name><data-type>(size) );
Example:
Page11
CREATE TABLE EMPLOYEE(Ecode int(6), Ename varchar(30), Dept varchar(30), city
varchar(25), sex char(1), DOB Date, salary float(12,2) );
Fig.:EMPLOYEE
Viewing a table
structure:DESC <table-
name>;
Example:DESCEMPLOYEE;
Orwe canwrite
DESCRIBEEMPLOYEE;
Insertingdatainto table:
Therows(tuples)areaddedtorelations(tables)usingINSERTcommand.
Syntax:
The into clause specifies the target table and the value clause specifies the data to
be added to the new row of the table.
Whileinsertingdataintotables,followingpointsshouldbetakencareof:
Characterdatashouldbeenclosedwithinsinglequotes.
NULLvaluesaregivenasNULL,withoutanyquotes.
Page12
If no data is available for all the columns then the column list must be included,
following the table name. Example: INSERT INTO EMPLOYEE(Ecode, Ename,
salary) VALUES(1001, „Amit‟, 20000.00);
Afterinsertingthedata,wecreatedthefollowing table:
CONSTRAINTS:
A constraint is a condition on a field or on set of fields. There are six types of constraints
that we use in MySQL:-
(i) NOTNULL
(ii)DEFAULT
(iii) UNIQUE
(iv) CHECK
(v) PRIMARYKEY
(vi) FOREIGNKEY
(i) NOTNULLConstraint:ThisconstraintensuresthatacolumncannothaveNULL
value.Bydefault,acolumncanholdNULL.IfyouaddaNOTNULLconstrainton a
column it cannot hold a NULL.
Page13
HowtoapplyNOTNULL constraint:-
CREATETABLEEMPLOYEE(Ecodeint(6)NOTNULL,Ename
varchar(30)NOTNULL,Deptvarchar(25));
NowEcodeandEnamecolumnscannotincludeNULL.
(b) AddNOTNULLconstraintinaexistingtablecolumn:
Example:-
Howtoapplydefaultconstraint:-
(a) Whilewearecreatingatable:-
Example:-
CREATETABLEEMPLOYEE(Ecodeint(6),Enamevarchar(30),Salary float(12,2)
DEFAULT25000.00);
(b) AddDEFAULTconstraintinanexistingtablecolumn:-
Example:-
ALTERTABLEEMPLOYEE
MODIFYSalaryfloat(12,2)DEFAULT25000.00;
(iii) UNIQUEConstraint:-Itensuresthatallvaluesinacolumnaredifferent.
Howtoapplyuniqueconstraints:-
(a) Whilewearecreatingatable:-
Page14
Example:-
CREATETABLEEMPLOYEE(Ecodeint(6)UNIQUE,Ename
varchar(30),Deptvarchar(25));
(b) Adduniqueconstraintinanexistingtablecolumn:
Example:-
ALTER TABLE EMPLOYEE
MODIFYEcodeint(6)UNIQUE;
(iv) CHECKconstraint:-Itmakesurethatallthevaluesinacolumnsatisfycertain
criteria.
Howtoapplycheckconstraint:-
(a) Whilewearecreatingatable:-
Example:-
CREATETABLEEMPLOYEE(Ecodeint(11)CHECK(Ecode>0),Ename
varchar(30));
(b) Addcheckconstraintonanexistingtablecolumn:-
Example:-
ALTERTABLEEMPLOYEE
ADD CHECK(Ecode>0);
(v) PrimaryKeyConstraint:-Thisisusedtouniquelyidentifyarowinatable.
Howtoapplyprimarykey constraint:-
(a) Whilecreatingatable:-
Example:-
CREATETABLEEMPLOYEE(Ecodeint(6)PRIMARYKEY,Ename
varchar(30),cityvarchar(30));
(b) Addprimarykeyconstraintonanexistingtablecolumn:-
Example:-
ALTER TABLE EMPLOYEE
ADDPRIMARYKEY(Ecode);
Page15
(vi) Foreign Key Constraint:-Whenever two tables are related by a common
column, then the related column in the parent table should be either declared a
PRIMARY KEY or UNIQUE KEY and the related column in the child table
should have FOREIGN KEY constraint.
Syntax:-
Foreignkey(<column-to-be-designated-as-foreign-key>)referencesparent-table
(<primary-key-of parent table>);
Primarykeyofparenttablebecomestheforeignkeyforthechild table.
(a) Whilecreatingatable:-
Example:-
CREATETABLEORDERS(Order_no int PRIMARYKEY, Order_Date Date,
Cust_ID integer, Amount double, foreign key(cust_ID) references
CUSTOMER(cust_ID));
(b) AddforeignkeyconstraintthroughALTERtable:-
Example:-
ALTERTABLEORDERS
ADDforeignkey(cust_ID)referencesCUSTOMER(cust_ID);
Page16
Droppinga constraint:-
Thesyntaxis:-
ALTERTABLEtable-name
DROPconstraint<constraint-name>;
Example:
Toremoveprimarykeyconstraint:-
ALTERTABLEEMPLOYEE DROP
PRIMARY KEY;
Toremoveforeignkeyconstraint:-
DROPFOREIGNKEYfk1;
Inthisquerytablenameistable1andforeignkeyconstraintisfk1.
ADDINGNEWCOLUMNINATABLE:-
Syntax:-
ALTERTABLEtable-name
ADDcol-namedata-type(size);
Example:Addanewcolumn addressinemployeetable.
ALTERTABLEEMPLOYEE
ADDaddressvarchar(50);
MODIFYINGATABLECOLUMN:
(i) Tochangethedata-typeandsizeofthecolumn,weusetheMODIFY
command.
(ii) Tochangethenameofthecolumn,weusetheCHANGEcommand.
Page17
(i) Tochangethedata-typeandsizeofthecolumn,weusetheMODIFY
command:-
Thesyntaxis:-
ALTERTABLEtable-name
MODIFY(Col_namenewdatatype(newsize));
Example:
ALTERTABLEEMPLOYEE
MODIFYcitychar(30);
ALTERTABLE<table-name>
CHANGEoldcolumnnamenewcolumnnamecol-definition;
Example:
ALTERTABLEEMPLOYEE
CHANGEDeptDepartmentvarchar(30);
DROPPINGATABLE:
Toremovetheentirestructureofthetablecompletely,weusetheDROPTABLE command.
Syntax:
DROPTABLE<table-name>;
Example:
DROPTABLEEMPLOYEE;
Page18
MANIPULATINGDATAOFATABLE:-
(i) Retrievingdata:SELECTcommand
(ii) Insertingdata:INSERTcommand
(iii) Deletingdata :DELETEcommand
(iv) Modification :UPDATEcommand
syntax is:
DELETEFROM<table-name>
WHERE<condition>;
Example:-Deletethoserowswhosedepartmentisproduction.
Solution: DELETEFROMEMPLOYEE
WHEREdept=‟production‟;
Example:-DeletealltherecordsofEMPLOYEEtablehavingsalarylessthan 35000.
Solution: DELETEFROMEMPLOYEE
WHERE Salary<35000;
Page19
Example:-ChangethesalaryofVikramto36000.
Solution:UPDATEEMPLOYEE
SET
salary=36000WHEREEna
me=‟Vikram‟;
Example:- Increaseeveryemployeesalaryby10%.
Solution:UPDATE EMPLOYEE
SETsalary=salary+(salary*0.1);
MAKINGSIMPLEQUERIES:-
InSQLqueries,weusethreeclausesmostly:-
(i) SELECT:-
ASELECTcommandisusedtoretrieveinformationfromatable.
Ifyouwanttoselecttheallcolumnsfromatable,thenweusethe
asterisk(*) in SELECT clause.
Example:- SELECT * FROMEMPLOYEE;
Todisplayspecificcolumnsofthetablebyspecifyingthecolumnnames,
separated by commas.
Example: - SELECTEcode,Ename,salary
FROM EMPLOYEE;
(ii) FROM:-
AFROMclause,specifiesthetablenamethatcontainsthecolumns.
(iii) WHERE:-
AWHEREclause,specifiesthecondition.
Syntax:-SELECTcolumn_name
FROMtable_name
WHEREcondition;
Page20
SOMEIMPORTANATPOINTS:-
SQLstatementsarenotcasesensitive.
ToendtheSQLcommand,wewritethesemicolon(;)attheendofalinefollowed by
<ENTER>.
SelectingAllColumns:-Toselectallthecolumns,weuseasterisk(*)inSELECT
statement.
Example:- SELECT *
FROM EMPLOYEE;
Eliminatingredundantdata:-TheDISTINCTkeywordeliminatesduplicaterows
from the results. DISTINCT is used in SELECT statement.
Example:- SELECT DISTINCT(Dept)
FROM EMPLOYEE;
ALLkeyword:-
SQLallowsustousethekeywordALLtospecifyexplicitlythatduplicatesarenot removed.
FROM EMPLOYEE;
ArithmeticOperations:-
TheSELECTclausemayalsocontainarithmeticexpressionsinvolvingtheoperators+,-
,*and/operatingonconstantsor attributes.
Example:-Findthenewsalaryofeveryemployeeincreasedby25%.
SELECTEname,salary,salary*0.25
FROMEMPLOYEE;
Page21
COLUMN ALIAS:- Youcanchangeacolumnheadingbyusingacolumnalias.
FROM EMPLOYEE;
ExamplesofQueries:-
1. Listthenameanddepartmentofthoseemployees wheredepartmentisproduction.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE Dept=‟production‟;
2. Findthenameandsalaryofthoseemployeeswhosesalaryismorethan20000.
Solution:- SELECT Ename, salary
FROM EMPLOYEE
WHERE salary> 20000;
3. DisplaythenameofthoseemployeeswholiveinNewDelhi.
Solution:- SELECT Ename, city
FROM EMPLOYEE
WHERE city=‟NewDelhi‟;
4. ListthenameoffemaleemployeesinEMPLOYEEtable.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE sex=‟F‟;
5. Displaythenameanddepartmentofthoseemployeeswhoworkinsuratandsalary is
greater than 25000.
Solution:- SELECT Ename,Dept
FROM EMPLOYEE
WHERE city=‟surat‟andsalary>25000;
Orwecanwritethisqueryinanotherway:
Solution:- SELECT Ename,Dept
FROM EMPLOYEE
WHERE city=‟surat‟&&salary>25000;
6. DisplaythenameofthosefemaleemployeeswhoworkinMumbai.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE sex=‟F‟andcity=‟Mumbai‟;
7. DisplaythenameofthoseemployeeswhosedepartmentismarketingorRND.
Page22
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Dept=‟marketing‟ORDept=‟RND‟;
8. Listthenameofemployeeswhoarenot males.
Solution:- SELECT Ename,Sex
FROM EMPLOYEE
WHERE sex!=‟M‟;
QUERIESFORSPECIALOPERATORS:-
(i) BETWEEN:-
Example:-Findthenameandsalaryofthoseemployeeswhosesalaryis
between 35000 and 40000.
Solution:-
SELECT Ename,salary
FROM EMPLOYEE
WHERE salaryBETWEEN35000and40000;
Orwecanwritethisqueryinanotherway:
SELECT Ename,salary
FROM EMPLOYEE
WHERE salary>35000andsalary<40000;
(ii) IN :-
Example:-Findthenameofthoseemployeeswholiveinguwahati,surator jaipur
city.
Solution:-
SELECT Ename, city
FROM EMPLOYEE
WHERE cityIN(„Guwahati‟,‟Surat‟,‟Jaipur‟);
Page23
(iii) LIKE:-
%:-Itrepresentsanysequenceofzeroormore characters.
_ :-Representsanysinglecharacter.
Example:- Displaythenameofthoseemployeeswhosenamestartswith„M‟.
Solution:-
SELECT Ename
FROM EMPLOYEE
WHERE EnameLIKE „M%‟;
Example:-Displaythenameofthoseemployeeswhosedepartmentnameendswith „a‟.
Solution:-
SELECT Ename
FROM EMPLOYEE
WHERE DeptLIKE„%a‟;
Solution:-
SELECT Ename
FROM EMPLOYEE
WHERE EnameLIKE„_e%‟;
(iv) ISNULL:-
Example:- Listthenameofemployeesnotassignedtoanydepartment.
Solution:-
SELECT Ename
FROM EMPLOYEE
WHERE DeptISNULL;
IFNULL()function:-
Ifyouwanttosubstitutenullwithavalueintheoutput,youcanuseIFNULL()function.
Syntax:-
IFNULL(<column-name>,valuetobesubstitute)
Page24
Example:-
SELECT Ename,IFNULL(salary,“5000”)
FROM EMPLOYEE;
ORDERBYclause:-
You can sort theresult in aspecificorderusing ORDERBYclause.Thesorting can
be done either in ascending or descending order. The default order is ascending.
Example:- Displaythelistofemployeesindescendingorderofemployeecode.
Solution:-
SELECT *
FROM EMPLOYEE
ORDERBY ecodeDESC;
Example:- Displaytheemployeecode,nameinascendingorderofsalary.
Solution:-
SELECT Ecode,Ename,salary
FROM EMPLOYEE
ORDERBY salaryasc;
SupposethatwewishtolisttheentireEMPLOYEErelationindescendingorderofsalary.
Ifseveralemployeeshavethesamesalary,weordertheminascendingorderbyemployee code.
We express this query in SQL as follows:-
SELECT *
FROM EMPLOYEE
ORDERBY salarydesc,Ecodeasc;
AGGREGATEFUNCTIONS:
Aggregatefunctionsarefunctionsthattakeacollectionofvaluesasinputandreturna single
value. SQL offers five types of aggregate functions:-
Page25
NOTE:-Theinputtosum()andavg()mustbeacollectionofnumbers,buttheother functions can
operate on non-numeric data types e.g.string.
Findtheaveragesalaryoftheemployeesinemployee table.
SELECT avg(salary)
FROM EMPLOYEE;
Insomecircumstance,wewouldliketoapplytheaggregatefunctionnotonlytoasingle set of
tuples, but also to a group of sets of tuples. We specify this wish in SQL using the
group by clause.
Theattributesgiveninthegroupbyclauseareusedtoformgroups.
Example:-Findtheaveragesalaryateach department.
Solution: - SELECT Dept,avg(salary)
FROM EMPLOYEE
group by Dept;
Dept Avg(salary)
Production 38000.00
Marketing 35410.00
RND 40016.66
FindtheminimumsalaryinEMPLOYEEtable.
Solution:-
SELECT min(salary)
FROM EMPLOYEE;
FindtheminimumsalaryofafemaleemployeeinEMPLOYEEtable.
Solution:-
SELECT Ename,min(salary)
FROM EMPLOYEE
WHERE sex=‟F‟;
FindthemaximumsalaryofamaleemployeeinEMPLOYEEtable.
Solution:-
SELECT Ename,max(salary)
FROM EMPLOYEE
WHERE sex=‟M‟;
Page26
FindthetotalsalaryofthoseemployeeswhoworkinGuwahati city.
Solution:-
SELECT sum(salary)
FROM EMPLOYEE
WHERE city=‟Guwahati‟;
FindthetotalsalaryofallemployeesinEMPLOYEErelation.
Solution:-
SELECT sum(salary)
FROM EMPLOYEE;
FindthenumberoftuplesintheEMPLOYEE relation.
Solution:-
SELECT count(*)
FROM EMPLOYEE;
CountthenumberofemployeeswhoworkinRNDdepartment.
Solution:-
SELECT count(*)
FROM EMPLOYEE
WHERE Dept=‟RND‟;
JOINS:
Considertwotables,CUSTOMERandORDERS:
TABLE: CUSTOMER
CUST_ID CUST_NAME GENDER CITY
101 Rahul M DELHI
105 Sushil M GOA
206 Sunita F MUMBAI
517 Gaurav M VADODARA
TABLE: ORDERS
ORDER_ID CUST_ID ORDER_DATE AMOUNT
14578 105 10/04/2016 1850.50
25685 517 15/03/2015 8569.00
89632 222 01/01/2016 5362.20
78451 105 30/05/2015 450.00
Page27
TypesofJoins:
1. CartesianProduct
2. EquiJoin
3. NaturalJoin
1. Cartesianproduct:Itisknownascrossjoin.Thenumberoftuplesinnewrelation
isequaltoproductofnumberoftuplesofthetwotablesonwhichCartesianproduct is
performed.
SELECTName,Amount
FROMCUSTOMER,BORROWER;
**Cartesianproductisformedwhennojoinconditionsexist.
2. EquiJoin:Columnsarecomparedforequality.
a. INNERJOIN
b. LEFTJOIN
c. RIGHTJOIN
d. FULLJOIN
a. INNER JOIN: Returns all rows when there is at least one match in BOTH tables.
This joining is known as simple join. You can use JOIN keyword also in the place
of INNER JOIN. Both will give same result.
Syntax:
SELECTcolumn_name(s)
FROMtable1
INNERJOINtable2
ONtable1.column_name=table2.column_name;
Example: OUTPUT
SELECTCUST_NAME,ORDER_ID
CUST_NAME ORDER_ID
FROM CUSTOMER
SHUSHIL 14578
INNER JOIN ORDERS
SHUSHIL 78451
ON
GAURAV 25685
CUSTOMER.CUST_ID=ORDER.CUST_ID;
Page28
b. LEFT JOIN: Return all rows from the left table, and the matched rowsfrom
theright table
c. RIGHTJOIN:Returnallrowsfromtherighttable,andthematchedrowsfromthe left
table
d. FULLJOIN:ReturnallrowswhenthereisamatchinONEofthe tables
3. NaturalJoin:Onlyoneoftheidenticalcolumnsexists.
**TheequijoinandNaturalJoinareequivalentexceptthatduplicatecolumnsareeliminated in the
Natural Join.
MySQLdatabaseconnectivitywithPython:
Installpython
InstallMySQL
InstallMySQLDriverusingfollowingcommand:(InCommandPrompt):
pipinstallmysql-connector
Note:Makesureyourcomputerisconnectedwithinternet.
Ifthecommandsuccessfullyruns(withoutanyerror),thentheMySQLconnectoris successfully
installed.
Now, open MySQL and check the current user, by typing the following command
in MySQL:
SELECTcurrent_user();
Page29
Connect MySQL database with python. For this, open Python IDLE and write the
following code in python file.
CODE:
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="computer")
print(demodb)
Ifyougetthefollowingoutput,thentheconnectionmadesuccessfully.
OUTPUT:
AftermakingsuccessfulconnectionbetweenpythonandMySQL,nowcreatea database
in MySQL through python. For that, write the following code in python:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="computer")
democursor=demodb.cursor( )
democursor.execute("CREATEDATABASEEDUCATION")
Page30
After successful execution of the following code, check in MySQL, whether
EDUCATION database has been created or not. for that, write the following
command in MySQL:
Ifyouwanttocheckthecreateddatabasethroughpython,writethefollowingpython code
to show the present databases in MySQL.
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="computer")
democursor=demodb.cursor()
democursor.execute("SHOWDATABASES")
for i in democursor:
print(i)
OUTPUT:
Here,wecanseethatEDUCATIONdatabasehasbeen created.
CODE:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
snamevarchar(30),genderchar(1),DOBdate,streamvarchar(15),marksfloat(4,2))")
Page31
Toverifythetablecreatedornot,writethefollowingcodeinpython:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
democursor = demodb.cursor( )
democursor.execute("showtables") for
i in democursor:
print(i)
OUTPUT:
Insertthedatainthetable:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insertintostudentvalues(%s,%s,%s,%s,%s,%s)",(1245, 'Arush',
'M','2003-10-04', 'science', 67.34))
demodb.commit()
Fetchthedatafromtable:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
Page32
democursor=demodb.cursor( )
democursor.execute("select*fromstudent") for
i in democursor:
print(i)
OUTPUT:
Updatetherecord:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("updatestudentsetmarks=55.68whereadmn_no=1356")
demodb.commit( )
Deletearecord:
importmysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("deletefromstudentwhereadmn_no=1356")
demodb.commit( )
Page33