Patel College Of Science &
Technology, Indore
Department of Computer Science & Engineering
LAB MANUAL
Session: Dec 2024
Semester : 5th sem III Year(REG)
Data Base Management System
(B.Tech IS 501)
SUBMITTED TO: SUBMITTED BY:
Ms. Kiran Thakur
INDEX
S. No Topic Pageno
1 IntroductionSQL-SQL*Plus 1
2 Road waytravelsE-RDiagrams 7
3 VariousDataTypes 12
4 Tables 14
5 MySQLInstallation 16
6 DDLand DMLCommands withExamples 24
7 KeyConstrains-Normalization 32
INTRODUCTION
DatabaseManagementSystem
This model is like a hierarchical tree structure, used to construct a hierarchy of records in
the form of nodes and branches. The data elements present in the structure have Parent-Child
relationship.Closelyrelated information in the parent-child structureisstored together as alogical
unit. A parent unit may have many child units, but a child is restricted to have only one parent.
Thedrawbacksofthismodelare:
Thehierarchicalstructureisnotflexibletorepresentalltherelationshipproportions,
whichoccur inthe real world.
It cannot demonstrate the overall data model for the enterprise because of the non-
availability of actual data at the time of designing the data model.
ItcannotrepresenttheMany-to-Manyrelationship.
NetworkModel
It supports the One-To-One and One-To-Many types only. The basic objects in this model are
Data Items, Data Aggregates, Records and Sets.
It is an improvement on the Hierarchical Model. Here multiple parent-child relationships are
used. Rapid and easy access to data is possible in this model due to multiple access paths to the
data elements.
RelationalModel
Does not maintain physical connection between relations
Data is organized in terms of rows and columns in a table
The position of a rowand/or column in a table is of no importance
The intersection of a row and column must give a single value
Featuresofan RDBMS
The ability to create multiple relations and enter data into them
An attractive query language
Retrievalofinformationstoredinmorethanonetable
An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to be accepted
as a full- fledged RDBMS.
1
RelationalDatabaseManagementSystem
RDBMS is acronym for Relation Database Management System. Dr. E. F. Codd first
introduced the Relational Database Model in 1970. The Relational model allows data to be
represented in a simple row- column. Each data field is considered as a column and each record is
consideredasarow.RelationalDatabaseismoreorlesssimilartoDatabaseManagementSystem. In
relational model there is relation between their data elements. Data is stored in tables. Tables have
columns, rows and names. Tables can be related to each other if each has a column with a
common type of information. The most famous RDBMS packages are Oracle, Sybase and
Informix.
SimpleexampleofRelationalmodelisasfollows:
StudentDetailsTable
Roll_noSnameS_Address
1 Rahul Satelite
2 Sachin Ambawadi
3 Saurav Naranpura
StudentMarksheetTable
Rollno Sub1 Sub2Sub3
1 78 89 94
2 54 65 77
3 23 78 46
Here,bothtablesarebasedonstudentsdetails.CommonfieldinbothtablesisRollno.Sowe can say
both tables are related with each other through Rollno column.
Degreeof Relationship
OnetoOne (1:1)
OnetoManyorManytoOne(1:M/M:1) Many to
Many (M: M)
TheDegreeofRelationshipindicatesthelinkbetweentwoentitiesforaspecifiedoccurrenceof each.
2
OnetoOneRelationship:(1:1) 1
1
StudentHasRollNo.
One student has onlyone Rollno. For oneoccurrence of the first entity, therecanbe, at the most
one related occurrence of the second entity, and vice-versa.
OnetoManyorManytoOneRelationship:(1:M/M:1) 1 M
CourseContainsStudents
As per the Institutions Norm, One student can enroll in one course at a time however, in one
course, there can be more than one student.
For one occurrence of the first entity there can exist many related occurrences of the second
entity and for every occurrence of the second entity there exists only one associated occurrence
of the first.
ManytoManyRelationship:(M:M)
MM
StudentsAppears Tests
The major disadvantage of the relational model is that a clear-cut interface cannot be determined.
Reusability of a structure is not possible. The Relational Database now accepted model on which
major database system are built.
Oracle has introduced added functionality to this by incorporated object-oriented capabilities.Now
it is known is as Object Relational Database Management System (ORDBMS). Object- oriented
concept is added in Oracle8.
Some basic rules have to be followed for a DBMS to be relational. They are known as Codd’s
rules, designed in such a way that when the database is ready for use it encapsulates the
relational theory to its full potential. These twelve rules are as follows.
3
E.F.CoddRules
1. TheInformation Rule
Allinformationmustbestoreintableasdatavalues.
2. TheRuleofGuaranteedAccess
Everyiteminatablemustbelogicallyaddressablewiththehelpofatablename.
3. TheSystematicTreatmentofNullValues
The RDBMS must be taken care of null values torepresentmissingor
inapplicable information.
4. TheDatabaseDescriptionRule
A description of database is maintained using the same logicalstructureswith
which data was defined by the RDBMS.
5. ComprehensiveDataSubLanguage
According to the rule the system must support data definition, view definition, data
manipulation, integrity constraints, authorization and transaction management
operations.
6. TheViewUpdatingRule
Allviewsthataretheoreticallyupdatablearealsoupdatablebythesystem.
7. TheInsertandUpdateRule
Thisruleindicatesthatallthedatamanipulationcommandsmustbeoperational on sets
of rows having a relation rather than on a single row.
8. ThePhysicalIndependenceRule
Application programs must remain unimpaired when any changes are made in storage
representation or access methods.
9. TheLogicalDataIndependenceRule
Thechangesthataremadeshouldnotaffecttheuser’sabilitytoworkwiththe data.The change
can be splitting table into many more tables.
10. TheIntegrityIndependence Rule
Theintegrityconstraintsshouldstoreinthesystemcatalogorinthedatabase.
11. TheDistributionRule
Thesystemmustbeaccessormanipulatethedatathatisdistributedinothersystems.
4
12. TheNon-subversionRule
IfaRDBMSsupportsalowerlevellanguagethenitshouldnotbypassany
integrity constraints defined in the higher level.
ObjectRelationalDatabaseManagementSystem
Oracle8 and later versions are supported object-oriented concepts. A structure once created can be
reused is the fundamental of the OOP’s concept. So we can say Oracle8 is supported Object
Relational model, Object - oriented model both. Oracle products are based on a concept known asa
client-server technology. This concept involves segregating the processing of an application
between two systems. One performs all activities related to the database (server) and the other
performs activities that help the user to interact with the application (client). A client or front-end
database application also interacts with the database by requesting and receiving information from
database server. It acts as an interface between the user and the database.
The database server or back end is used to manage the database tables and also respond to client
requests.
IntroductiontoORACLE
ORACLE is a powerful RDBMS product that provides efficient and effective solutions for major
database features. This includes:
Largedatabasesandspacemanagement control
Many concurrent database users
Hightransactionprocessingperformance
High availability
Controlledavailability
Industry accepted standards
Manageable security
Database enforced integrity
Client/Server environment
Distributed database systems
Portability
5
Compatibility
Connectivity
AnORACLEdatabasesystemcaneasilytakeadvantageofdistributedprocessingbyusingits Client/
Server architecture. In this architecture, the database system is divided into two parts:
Afront-endoraclientportion
The client executes the database application that accesses database information and interacts with
the user.
Aback-endoraserverportion
TheserverexecutestheORACLEsoftwareandhandlesthefunctionsrequiredforconcurrent, shared data
access to ORACLE database.
6
ROADWAYTRAVELS
“RoadwayTravels”isinbusinesssince1977withseveralbusesconnectingdifferent placesin India. Its
main office is located in Hyderabad.
Thecompanywantstocomputerizeitsoperationsinthefollowingareas:
Reservations
Ticketing
Cancellations
Reservations:
Reservationsaredirectlyhandeledbybookingoffice.reservationscanbemade60days in
advance in either cash or credit. In case the ticket is not available,a wait listed ticket is issued to
the customer. This ticket is confirmed against the cancellation.
Cancellationandmodification:
Cancellationsarealsodirectlyhandedatthebookingoffice.Cancellationcharges will be
charged.
Waitlistedticketsthatdonotgetconfirmedarefullyrefunded.
7
AIM:Analyzetheproblemandcomewiththeentitiesinit.IdentifywhatDatahastobe persisted in the
databases.
TheFollowingaretheentities:
1 .Bus
2. Reservation
3. Ticket
4. Passenger
5. Cancellation
TheattributesintheEntities:
Bus:( Entity)
Destination
Source
CouchType
BusNo
Bus
Reservation(Entity)
ContactNo BusNo
No-of-Seats
Journeydate
Address
PNRNO
Reservation
Ticket :(Entity)
Dep-Time
Source
Age
Sex
Journeydate
Destination
Ticket No
BusNo
Ticket
8
Passenger:
ContactNO
Age
Sex
PNRNO
Name
Ticket No
Passenger
Cancellation(Entity)
Journeydate SeatNo
PNRNO ContactNo
Cancellation
9
ConceptdesignwithE-RModel:
10
WhatisSQLandSQL*Plus
Oracle was the first company to release a product that used the English-based Structured Query
Language or SQL. This language allows end users to manipulate information of table(primary
database object). To use SQL you need not to require any programming experience. SQL is a
standard language common to all relational databases. SQL is database language used for storing
and retrieving data from the database. Most Relational Database Management Systems provide
extension to SQL to make it easier for application developer. A table is a primary object of
database used to store data. It stores data in form of rows and columns.
SQL*PlusisanOracletool(specificprogram)whichacceptsSQLcommandsandPL/SQLblocks and
executes them. SQL *Plus enables manipulations of SQL commands and PL/SQL blocks. It also
performs additional tasks such as calculations, store and print query results in the form of reports,
list column definitions of any table, access and copy data between SQL databases andsend
messages to and accept responses from the user. SQL *Plus is a character based interactive tool,
that runs in a GUI environment. It is loaded on the client machine.
TocommunicatewithOracle,SQLsupportsthefollowingcategoriesofcommands:
1. DataDefinitionLanguage
Create,Alter,DropandTruncate
2. DataManipulationLanguage
Insert,Update,DeleteandSelect
3. TransactionControlLanguage
Commit,RollbackandSavepoint
4. DataControlLanguage
GrantandRevoke
Beforewetakealookonabove-mentionedcommandswewillseethedatatypesavailablein Oracle.
OracleInternalDatatypes
When you create a table in Oracle, a few items should be important, not only do you have to give
each table a name(e.g. employee, customer), you must also list all the columns or fields (e.g.
First_name, Mname, Last_name) associated with the table. You also have to specify what type of
information thattable will hold to the database. For example, the column Empno holds numeric
information. An Oracle database can hold many different types of data.
Datatype Description
Char(Size)Storesfixed-lengthcharacterdatatostorealphanumericvalues,witha maximum
size of 2000 bytes. Default and minimum size is 1 byte.
Varchar2(Size)Storesvariable-lengthcharacterdatatostorealphanumericvalues,with maximum
size of 4000 bytes.
char(Size) Stores fixed-length character data of length size characters or bytes, depending
on the choice of national character set. Maximum size if determined by the number of bytes
required storing each character with an upper limit of 2000 bytes. Default and minimum size is 1
character or 1 byte, depending on the character set.
Nvarchar2(Size)Storesvariable-lengthcharacterstringhavingmaximumlengthsize
characters or bytes, depending on the choice of national character set. Maximum size is
determined by the number of bytes required to store each character, with an upper limit
of 4000bytes.
LongStoresvariable-lengthcharacterdataupto2GB(Gigabytes).Itslenthwouldbe
restrictedbasedonmemoryspaceavailableinthecomputer.
Number[p,s] Numberhavingprecisionpandscales.Theprecisionpindicatestotal
numberof digitvariesfrom1to38.Thescalesindicatesnumberofdigitinfractionpart varies
from -84 to 127.
DateStoresdatesfromJanuary1,4712B.C.toDecember31,4712A.D. Oracle
predefineformatofDatedatatypeisDD-MON-YYYY.
12
Raw (Size) Stores binarydata of lengthsize. Maximumsize is 2000 bytes.One must
havetospecifysizewithRAWtypedata,becausebydefaultitdoesnotspecifyanysize. Long
Raw Store binary data of variable length up to 2GB(Gigabytes).
LOBS-LARGEOBJECTS
LOBisusetostoreunstructuredinformationsuchassoundandvideoclips,picturesupto4GB size.
CLOBACharacterLargeObjectcontainingfixed-widthmulti-bytecharacters. Varying-
widthcharactersetsarenotsupported.Maximumsizeis4GB.
NCLOBANationalCharacterLargeObjectcontainingfixed-widthmulti-bytecharacters.
Varying-widthcharactersetsarenotsupported.Maximumsizeis4GB.Stores national
character set data.
BLOBTostoreaBinaryLargeObjectsuchagraphics,videoclipsandsoundfiles.
Maximumsizeis4GB.
BFILEContainsalocatortoalargeBinaryFilestoredoutsidethedatabase.Enables byte
stream I/O access to external LOBs residing on the database server. Maximum
sizeis4GB.Apartfromoracleinternaldatatypes,usercancreatetheirowndatatype,whichis used in
database and other database object. We will discuss it in the later part.
13
Thefollowingaretabularrepresentationoftheaboveentitiesandrelationships
BUS:
COLOUMNNAME DATATYPE CONSTRAINT
BusNo varchar2(10) Primary Key
Source varchar2(20)
Destination varchar2(20)
CouchType varchar2(20)
Reservation:
COLOUMNNAME DATATYPE CONSTRAINT
PNRNo number(9) Primary Key
Journeydate Date
No-of-seats integer(8)
Address varchar2(50)
ContactNo Number(9) Should be equal to 10
numbersandnotallow
otherthan numeric
BusNo varchar2(10) Foreignkey
Seatno Number
14
Ticket:
COLOUMNNAME DATATYPE CONSTRAINT
Ticket_No number(9) Primary Key
Journeydate Date
Age int(4)
Sex Char(10)
Source varchar2(10)
Destination varchar2(10)
Dep-time varchar2(10)
BusNo Number2(10)
Passenger:
COLOUMNNAME DATATYPE CONSTRAINT
PNR No Number(9) Primary Key
TicketNo Number(9) Foreignkey
Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contactno Number(9) Shouldbeequalto10numbers
andnotallowotherthan
numeric
Cancellation:
COLOUMNNAME DATATYPE CONSTRAINT
PNR No Number(9) Foriegn-key
Journey-date Date
Seatno Integer(9)
Contact_No Number(9) Shouldbeequalto10numbers
andnotallowotherthan
numeric
15
AIM:InstallationofMySQLandpracticingDDL&DMLcommands.
1. StepsforinstallingMySQL
Step1 1
Makesureyoualreadydownloadedthe MySQLessential5.0.45win32.msifile.Doubleclick on
the .msi file.
Step2 2
ThisisMySQLServer5.0setupwizard.ThesetupwizardwillinstallMySQLServer5.0 release 5.0.45 on
your computer. To continue, click next.
Step3 3
Choosethesetuptypethatbestsuitsyourneeds.ForcommonprogramfeaturesselectTypical
andit’srecommendedforgeneraluse.Tocontinue,clicknext.
16
Step4 4
Thiswizardisreadytobegininstallation.DestinationfolderwillbeinC:\Program Files\MySQL\
MySQL Server 5.0\. To continue, click next.
Step5 5
Theprogramfeaturesyouselectedarebeinginstalled.Pleasewaitwhilethesetupwizard installs MySQL
5.0. This may take several minutes.
17
Step6
Tocontinue,clicknext.
Step7 7
Tocontinue,clicknext.
18
Step8 8
WizardCompleted.SetuphasfinishedinstallingMySQL5.0. ChecktheconfiguretheMySQL server
now to continue. Click Finish to exit the wizard
d.
Step9 9
TheconfigurationwizardwillallowyoutoconfiguretheMySQLServer5.0server instance.
19
Tocontinue,clicknext.
Step10 10
Selectastandardconfigurationandthiswilluseageneralpurposeconfigurationforthe server that can be
tuned manually. To continue, click next.
Step11 11
20
Checkontheinstall aswindowsservice andincludebindirectoryinwindowspath.To continue,
click next.
Step12 12
Pleasesetthesecurityoptionsbyenteringtherootpasswordandconfirmretypethepassword. continue,
click next.
Step13 13
21
Readytoexecute?Clicksexecutetocontinue.
Step14 14
Processingconfigurationinprogress.
22
Step15 15
Configurationfilecreated.WindowsserviceMySQL5installed.Pressfinishtoclosethe wizard.
23
2. PracticingDDL&DMLCommands
Data Definition Language
The data definition language is used to create an object, alter the structure of an object and also
drop already created object. The Data Definition Languages used for table definition can be
classified into following:
Createtablecommand
Altertablecommand
Truncatetablecommand
Droptablecommand
CreatingofTablesonROADWAY TRAVELS:
Tableisaprimaryobjectofdatabase,usedtostoredatainformofrowsandcolumns.Itis created using
following command:
CreateTable<table_name>(column1datatype(size),column2datatype(size),column(n)
datatype(size));
Example:
SQL>createtableBus(Bus_Novarchar(5),sourcevarchar(20),destination
varchar(20),CouchType varchar2(10),fair number);
Table Created.
createtablefortheobject-relationfeaturewewilldiscussitafterwards.
Desccommand
DescribecommandisexternalcommandofOracle.Thedescribecommandisusedtoviewthe structure of a
table as follows.
Desc<tablename>
SQL>descbus;
Name Null? Type
BUS_NO NOTNULL INTEGER2(5)
SOURCE VARCHAR2(20)
DESTINATION VARCHAR2(20)
COUCH TYPE VARCHAR2(10)
FAIR NUMBER
SQL>Describetheuniversitydatabase
24
Test Outputs:
SignatureofthelabIncharge Date:
Extra:1.CreateatableUniversitiesDB
ReservationTable:
SQL>createtableReservation(PNR_NONumeric(9),No_of_seatsNumber(8),Address
varchar(50), Contact_No Numeric(9), Status char(3));
Tablecreated.
SQL>desc Reservation
Name Null? Type
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
Test Output
Signatureofthelabincharge Date:
Exercise:Projectshaveaprojectnumber,asponsorname(e.g.,NSF),astartingdate,an ending
date, and a budge
CancellationTable:
SQL>createtableCancellation(PNR_NONumeric(9),No_of_seatsNumber(8),Address varchar(50),
Contact_No Numeric(9), Status char(3));
Tablecreated.
SQL>desc Cancellation
Name Null?Type
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
25
Test Output:
Signatureofthelabincharge
Date:
Exercise:GraduatestudentshaveanSSN,aname,anage,andadegreeprogram(e.g., M.S. or
Ph.D.)
AssignmentEvaluation
Signature
0: Not Done 1: Incomplete 2:Late complete
3:Needsimprovement 4:Complete 5:WellDone
Signature of the instructor Date:
26
Ticket Table:
SQL>createtableTicket(Ticket_NoNumeric(9)primarykey,agenumber(4),sexchar(4) Not
null, source varchar(2), destination varchar(20), dep_time varchar(4));
Tablecreated.
SQL>descTicket
Name Null? Type
TICKET_NO NOTNULL NUMBER(9)
AGE NUMBER(4)
SEX NOTNULL CHAR(4)
SOURCE VARCHAR2(2)
DESTINATION VARCHAR2(20)
DEP_TIME VARCHAR2(4)
Test Output:
Signatureofthelabincharge
Date:
Exercise:Eachprojectismanaged as
the project’s principal inves-
tigator).\
Alteration of Table
AdditionofColumn(s)
Additionofcolumnintableisdone usin
Altertable<table_name>add(column1datatype,column2datatype_);
SQL>ALTERTABLEPassengerADDFOREIGNKEY(PNR_NO)REFERENCES
Reservation(PNR_NO);
Table altered.
SQL>ALTERTABLECancellationADDFOREIGNKEY(PNR_NO)REFERENCES
Reservation(PNR_NO);
Table altered.
Test output:
Signatureoflabincharge
Date:
SQL>altertableTicketmodifytiketnonumber(10); Table
altered.
Test ouput
27
Signatureoflabincharge
Date:
DeletionofColumn
Altertable<table_name>dropcolumn<columnname>;
SQL>AlterTableEmp_masterdropcolumn comm;
Test output:
Altertable<table_name>add(column1datatype,column2datatype_);
SQL>ALTERTABLEPassengerADDFOREIGNKEY(PNR_NO)REFERENCES
Reservation(PNR_NO);
Table altered.
SQL>ALTERTABLECancellationADDFOREIGNKEY(PNR_NO)REFERENCES
Reservation(PNR_NO);
Table altered.
Test output:
Signatureoflabincharge
Date:
SQL>altertableTicketmodifytiketnonumber(10); Table
altered.
Test ouput
Signatureoflabincharge
Date:
DeletionofColumn
Altertable<table_name>dropcolumn<columnname>;
SQL>AlterTableEmp_masterdropcolumn comm;
Test output
28
Signatureofthelabincharge
Date:
ModificationinColumn
ModifyoptionisusedwithAltertable_whenyouwanttomodifyanyexistingcolumn. Alter table
<table name> modify (column1 datatype,_);
.
SQL>Altertableemp_mastermodifysalarynumber(9,2);
Table altered.
Test output:
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4:Complete 5:WellDone
Signature of the instructor Date:
29
TruncateTable
Truncatetable<tablename>[ReuseStorage];
Example
SQL>TruncateTableEmp_master;
Or
SQL>TruncateTableEmp_masterReuseStorage; Table
truncated.
Test output:
Signatureoflabincharge
Date:
AIM:ApplyingConstraintsonRoadWayTravelsTables.
Constraints
Domain Integrit y constraints
Entity Integrity constraints
ReferentialIntegrityconstraint
Oracleallowsprogrammerstodefineconstraints
ColumnLevel
TableLevel
Example
SQL>createtableTicket(Ticket_NoNumeric(9),agenumber(4),sexchar(4)Notnull, source
varchar(2), destination varchar(20), dep_time varchar(4));
Tablecreated.
TestOutput:
SignatureoftheIncharge
Date:
30
Exercise:Create tableprofessorbyusingnot nullconstaint
Check Constraint
SQL> create table Reservation(PNR_NO Numeric(9), No_of_seats Number(8), Address
varchar(50), Contact_No Numeric(10) constraint ck check(length(contact_no)=10), Status
char(3));
Tablecreated.
Test Output:
Signatureoftheincharge Date:
Exercise:Create table managebyusingcheck constraints
Checkconstraintwithaltercommand
SQL>altertableTicketaddconstraintcheck_agecheck(age>18); Table
altered.
Test Output:
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4:Complete 5:WellDone Sinature
of the instructor Date:
EntityIntegrityConstraints
Thistypeofconstraintsarefurtherclassifiedinto Unique
Constraint
PrimaryKey Constraint
UniqueConstraint
Example:
31
SQL>createtableTicket(Ticket_NoNumeric(9)unique,agenumber(4),sexchar(4)l,source varchar(2),
destination varchar(20), dep_time varchar(4));
EntityIntegrityConstraints
Thistypeofconstraintsarefurtherclassifiedinto Unique
Constraint
PrimaryKey Constraint
UniqueConstraint
Example:
SQL>createtableTicket(Ticket_NoNumeric(9)unique,agenumber(4),sexchar(4)l,source varchar(2),
destination varchar(20), dep_time varchar(4));
Test Output
Signatureoftheincharge Date
Exercise:CreatetableProfessorbyusingunique constraint
Uniqueconstraintwithaltercommand Example:
SQL>Altertableticketaddconstraintuni1Unique(ticket_no); Table
Altered.
Test Output:
Signatureoftheincharge
Date
Exercise:Altertableprofessorconstraint
Primarykeyconstraintatthecolumnlevel Example:
SQL>createtableTicket(Ticket_NoNumeric(9)constraintpkprimarykey,agenumber(4), sex
char(4) l, source varchar(2), destination varchar(20), dep_time varchar(4));
Table created.
Test Output:
Signatureoftheincharge
Date:
SQL>insertintoticketvalues(1001,26,‘M’,‘KPHB’,’MTM’,’20:00’);
32
1row created.
Test Output
Signatureoftheincharge Date
Primarykeywithaltercommand:
SQL>altertablebusaddconstraintprprimarykey(busno);
Table altered.
C
Exercise:ApplyprimarykeywithaltercommandonprojectnumberofUniversityDatabase
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4:Complete 5:WellDone
Signature of the instructor Date:
ReferentialIntegrityConstraint
Referencesconstraintdefinedatcolumnlevel
Example:
SQL>createtablePassenger(PNR_NONumeric(9)referencesreservation,Ticket_NO Numeric(9)
references ticket, Name varchar(20), Age Number(4), Sex char(10), PPNO varchar(15));
Tablecreated.
Test Output:
33
Signatureoftheincharge Date:
Exercise:ApplyReferencesconstraintUniversityDatabaseDepartmenttable.
ForeignKeyConstraintwithaltercommand
SQL>altertablereservationaddconstraintfk_icodeforeignkey(busno)references bus(bus_no);
Tablealtered.
Test Output:
Signatureoftheincharge
Date:
Exercise:ApplyForeginKeyConstriantwithalteronprofessorSSNwithDepartmentNo
Rememberthatwhenweaddconstraintattablelevelforeignkeykeywordismust. SQL>
delete from bus where bus_no = 2011;
Test output:
Signatureofthelabincharge Date:
34
a) Insert command
Insert into <table name> values(a list of data values);
Insertinto<tablename>(columnlist)values(alistofdata);
SQL>insertintoemp_master(empno,ename,salary)values(1122,‘Smith’,8000);1 row
created.
AddingvaluesinatableusingVariablemethod.
SQL>insertintoPassengervalues(&PNR_NO,&TICKET_NO,'&Name',&Age,'&Sex',
'&PPNO');
Enter value for pnr_no: 1
Entervalueforticket_no:1
Entervalueforname:SACHIN
Enter value for age: 12
Entervalueforsex: m
Entervalueforppno:sd1234
old 1:insertintoPassengervalues(&PNR_NO,&TICKET_NO,'&Name',&Age,'&Sex',
'&PPNO')
new1:insertintoPassengervalues(1,1,'SACHIN',12,'m','sd1234')
1 rowcreated.
SQL>/
SQL>/
SQl>/
SQL>/
SQL>insertintoBusvalues('&Bus_No','&source','&destination');
Enter value for bus_no: 1
Enter value for source: hyd
Entervaluefordestination:ban
old1:insertintoBusvalues('&Bus_No','&source','&destination')
new1: insert into Bus values('1','hyd','ban')
1 rowcreated.
SQL>/
SQL>/
35
SQL>/
SQL>/
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4: Complete 5:Well Done
Signatureof the instructor Date:
b) SimpleSelectCommand
Select<column1>,<column2>,_,<column(n)>from<tablename>;
SQL>select*fromemp_master; Test
Output:
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofDepartment.
SQL>selectempno,ename,salaryfromemp_master;
Test Output:
SQL>select*fromPassenger; Test Output:
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofDepartment.
SQL>selectempno,ename,salaryfromemp_master;
Test Output:
SQL>select*fromPassenger; Test Output
36
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofDepartment.
SQL>selectempno,ename,salaryfromemp_master;
Test Output:
SQL>select*fromPassenger; Test Output:
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofprojecttable
DistinctClause
SQL>selectdistinctdeptnofromemp_master; Test
Output:
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofprojecttablebyusingdistinctclause.
Selectcommandwithwhere clause:
Select<column(s)>from<tablename>where[condition(s)];
Example
SQL>selectempno,enamefromemp_masterwherehiredate=‘1-jan-00’; Test
Output:
Signatureoftheincharge
Date:
SQL>updatePassengersetage='43'wherePNR_NO='2'; Test
Output:
Signatureoftheincharge
Date:
37
Exercise:DisplaytheallcolumnofUniversityDatabaseofprojecttable
DistinctClause
SQL>selectdistinctdeptnofromemp_master; Test
Output:
Signatureoftheincharge
Date:
Exercise:DisplaytheallcolumnofUniversityDatabaseofprojecttablebyusingdistinctclause.
Selectcommandwithwhere clause:
Select<column(s)>from<tablename>where[condition(s)];
Example
SQL>selectempno,enamefromemp_masterwherehiredate=‘1-jan-00’; Test
Output:
Signatureoftheincharge
Date:
SQL>updatePassengersetage='43'wherePNR_NO='2'; Test
Output:
Signatureoftheincharge
Date:
SQL>Select*frompassenger;
Test Output
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4: Complete 5:Well Done
43
38
Signatureof the instructor Date:
DROPTable
SQL>droptableCancellation;
Table dropped.
Test Output:
Signatureoftheincharge
Date:
SelectcommandwithDDLandDML command.
TableCreationwithselectstatement
createtable<tablename>asselect<columnname(s)>from<existingtablename>; Example
InsertdatausingSelectstatement
Syntax:
Inertinto<tablename>(select<columns>from<tablename>);
Example
SQL>insertintoemp_copy(select*fromemp_master); Test
Output:
Signatureoftheincharge
Date:
Example
SQL>insertintoemp_copy(nm)(selectnamefromemp_master); Test
Output:
Signatureoftheincharge
Date:
ChangeTableName
Onecanchangetheexistingtablenamewithanewname.
Syntax
Rename<OldName>To<NewName>; Example:
SQL>Renameemp_master_copy1Toemp_master1;
TableRenamed.
46|Page
Test Output:
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4: Complete 5:Well Done
45
Signatureoftheincharge
Date:
ChangeTableName
Onecanchangetheexistingtablenamewithanewname.
Syntax
Rename<OldName>To<NewName>; Example:
SQL>Renameemp_master_copy1Toemp_master1;
TableRenamed.
Test Output:
AssignmentEvaluation Signature
0: Not Done 1: Incomplete 2: Late complete
3:Needsimprovement 4: Complete 5:Well Done
45
47|Page