Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour...

188
Prepared by: Deepak Gour Prepared by: Deepak Gour Lecturer-IT, SCT Lecturer-IT, SCT 1 INTRODUCTION TO INTRODUCTION TO DATABASE DATABASE Prepared by Deepak Gour Prepared by Deepak Gour Lecturer-IT Lecturer-IT Salalah College of Salalah College of Technology Technology

Transcript of Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour...

Page 1: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

11

INTRODUCTION TO INTRODUCTION TO DATABASEDATABASE

Prepared by Deepak GourPrepared by Deepak Gour

Lecturer-ITLecturer-IT

Salalah College of TechnologySalalah College of Technology

Page 2: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

22

Definition of DataDefinition of DataData is a raw fact which can be any number, Data is a raw fact which can be any number,

figure, or image. figure, or image. For exampleFor example 45 is a data as 45 is a number but does not 45 is a data as 45 is a number but does not

give any information.give any information. 45 may be house number.45 may be house number. 45 may be marks of the student in DBMS.45 may be marks of the student in DBMS. 45 may be salary of any worker.45 may be salary of any worker. 45 may be average age of employee in 45 may be average age of employee in

Salalah College of Technology.Salalah College of Technology.

Page 3: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

33

Definition of InformationDefinition of Information

Information is processed data instead of raw Information is processed data instead of raw fact. It will surely give meaning full fact. It will surely give meaning full information about any event, person, etc.information about any event, person, etc.

For example:For example: The average age of employee in Salalah The average age of employee in Salalah

College of Technology is 45.College of Technology is 45. Marks of Abdul in DBMS are 45.Marks of Abdul in DBMS are 45. House number of Abdullah is 45.House number of Abdullah is 45.

Page 4: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

44

Definition of DatabaseDefinition of Database

Database is a collection of Database is a collection of INTERRELATEDINTERRELATED data. Interrelated means all the data must data. Interrelated means all the data must have the same nature and must have a have the same nature and must have a relationship about the common entity.relationship about the common entity.

For Example:For Example: Data 1 belongs to student.Data 1 belongs to student. Data 2 belongs to hospital.Data 2 belongs to hospital. Data 3 belongs to reservation status.Data 3 belongs to reservation status.

Page 5: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

55

Definition of Database (contd..)Definition of Database (contd..)Here the collection of data1, data2, and data3 is not referred Here the collection of data1, data2, and data3 is not referred

as database (as the data is not related) since as database (as the data is not related) since database is database is not the collection of data but it is the collection of not the collection of data but it is the collection of INTERRELATED data only.INTERRELATED data only.

For Example:For Example: Data 1 belongs to student.Data 1 belongs to student. Data 2 belongs to student.Data 2 belongs to student. Data 3 belongs to student.Data 3 belongs to student.

Here the collection of data1, data2, and data3 will surely refer Here the collection of data1, data2, and data3 will surely refer as database as all the data belong to the same entity as as database as all the data belong to the same entity as student.student.

Page 6: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

66

Definition of Database (contd..)Definition of Database (contd..)

Example of student database:Example of student database:

Student ID

Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT Logic Design 2.9

1003 Abdullah IT Networks 3.1

Page 7: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

77

Definition of DBMS Definition of DBMS

A database management system consists of A database management system consists of the collection of interrelated data & a set of the collection of interrelated data & a set of programs to access those data elements. programs to access those data elements.

The collection of data, usually referred to as The collection of data, usually referred to as the database, contains information about the database, contains information about one particular enterprise. one particular enterprise.

Page 8: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

88

Definition of DBMS (contd..)Definition of DBMS (contd..)

The primary goal of a database The primary goal of a database management system is to provide an management system is to provide an environment, which is convenient & efficient environment, which is convenient & efficient to use in retrieving and storing database to use in retrieving and storing database information.information.

The database system must provide for the The database system must provide for the safety of the information stored, despite safety of the information stored, despite system crashed or any attempts to system crashed or any attempts to unauthorized access.unauthorized access.

Page 9: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

99

Disadvantages of File processing Disadvantages of File processing SystemSystem

Data redundancy & inconsistency.Data redundancy & inconsistency. Difficulty in accessing or retrieving the Difficulty in accessing or retrieving the

data.data. Data integrity problemData integrity problem Atomicity problems.Atomicity problems. Concurrent access problemsConcurrent access problems Problems related to the security of dataProblems related to the security of data

Page 10: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1010

Advantages of DBMS (Database Advantages of DBMS (Database Management System) Management System)

Controlling redundancy (data duplication)Controlling redundancy (data duplication) Restricting unauthorized accessRestricting unauthorized access Providing persistent storage for Program ObjectsProviding persistent storage for Program Objects Providing storage structure for efficient query Providing storage structure for efficient query

programmingprogramming Providing backup & recovery mechanismProviding backup & recovery mechanism Providing Multiple User InterfaceProviding Multiple User Interface Representing complex relationship among data Representing complex relationship among data

itemsitems

Page 11: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1111

Advantages of DBMS (Database Advantages of DBMS (Database Management System) (contd..)Management System) (contd..)

Enforcing integrity constraintsEnforcing integrity constraints Providing flexibility in report generationProviding flexibility in report generation Reduced application development timeReduced application development time Economic compare to conventional Economic compare to conventional

method, if the size of database is method, if the size of database is significantly largesignificantly large

Availability of up to dateAvailability of up to date Modification is simple compare to Modification is simple compare to

conventional file system conventional file system

Page 12: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1212

View of DataView of Data

A major purpose of a database system is to A major purpose of a database system is to provide users with an abstract view of the provide users with an abstract view of the data. That is, the system hides certain detail data. That is, the system hides certain detail of how the data are stored and maintained.of how the data are stored and maintained.

Page 13: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1313

View of Data (contd..)View of Data (contd..)

Page 14: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1414

Data AbstractionData Abstraction

Data Abstraction represents the view of the Data Abstraction represents the view of the data and hides all the unnecessary details data and hides all the unnecessary details from the user of the database management from the user of the database management system. In other words, data abstraction system. In other words, data abstraction only passes relevant information to the only passes relevant information to the concerned user and hides all the concerned user and hides all the unnecessary details from the user.unnecessary details from the user.

Page 15: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1515

Data Abstraction (contd..)Data Abstraction (contd..)

Three Level of AbstractionThree Level of Abstraction

Physical Level (Lowest level of abstraction)Physical Level (Lowest level of abstraction)

Logical level (Middle level of abstraction)Logical level (Middle level of abstraction)

View level (Highest level of abstraction)View level (Highest level of abstraction)

Page 16: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1616

Data Abstraction (contd..)Data Abstraction (contd..)

Physical Level:Physical Level:

The lowest level of Abstraction describes how The lowest level of Abstraction describes how the data are actually stored. At this level, the data are actually stored. At this level, complex low-level data structures are complex low-level data structures are described in detail.described in detail.

Page 17: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1717

Data Abstraction (contd..)Data Abstraction (contd..)

Logical Level:Logical Level:

The next higher level of abstraction describes The next higher level of abstraction describes what data are stored in the database, and what what data are stored in the database, and what relationship exists among those data.relationship exists among those data.

The entire database is described in terms of a The entire database is described in terms of a small number of relatively simple structures. small number of relatively simple structures. Database Administration (DBA), who must decide Database Administration (DBA), who must decide what information is to be kept in the database, what information is to be kept in the database, uses the logical level of abstraction.uses the logical level of abstraction.

Page 18: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1818

Data Abstraction (contd..)Data Abstraction (contd..)

View Level:View Level:

The highest level of Abstraction describes The highest level of Abstraction describes only part of the entire database. Many were only part of the entire database. Many were of database system will not be concerned of database system will not be concerned with the complexity of database. Instead, with the complexity of database. Instead, such users need to access only a part of the such users need to access only a part of the database. So that there interaction with the database. So that there interaction with the system is simplified.system is simplified.

Page 19: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

1919

Instances of SchemasInstances of Schemas

The collection of information stored in the The collection of information stored in the database at a particular moment or time is database at a particular moment or time is called an instance of the database. The called an instance of the database. The overall design of the database is called the overall design of the database is called the database Schema.database Schema.

Page 20: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2020

Instances of Schemas (contd..)Instances of Schemas (contd..)

Database System has several schemasDatabase System has several schemas

Physical Schema (Lowest level of schema)Physical Schema (Lowest level of schema)

Logical Schema (Intermediate level of Logical Schema (Intermediate level of schema)schema)

Subschema (Highest level)Subschema (Highest level)

Page 21: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2121

Instances of Schemas (contd..)Instances of Schemas (contd..)

At the Lowest level is the physical schema, At the Lowest level is the physical schema, at the intermediate level is the logical at the intermediate level is the logical schema; and at the highest level is a schema; and at the highest level is a subschema.subschema.

In general, database system supports one In general, database system supports one physical Schema, one logical Schema, and physical Schema, one logical Schema, and several sub Schemas.several sub Schemas.

Page 22: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2222

Instances of Schemas (contd..)Instances of Schemas (contd..)

Page 23: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2323

Data IndependenceData Independence

The ability to modify a schema definition in The ability to modify a schema definition in one level without affecting a schema one level without affecting a schema definition in the next higher level is called definition in the next higher level is called Data IndependenceData Independence..

Two types of data independence are Two types of data independence are present as:present as:

Physical Data IndependencePhysical Data Independence Logical Data Independence Logical Data Independence

Page 24: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2424

Data Independence (contd..)Data Independence (contd..)

Physical Data Independence iPhysical Data Independence is the ability s the ability to modify the physical Schema without to modify the physical Schema without causing application programs to be causing application programs to be rewritten. Modifications at the physical level rewritten. Modifications at the physical level are necessary to improve performance.are necessary to improve performance.

Page 25: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2525

Data Independence (contd..)Data Independence (contd..)

Logical Data IndependenceLogical Data Independence is the ability to is the ability to modify the logical Schema without changing the modify the logical Schema without changing the low level data structures. Modification at the low level data structures. Modification at the logical level is necessary whenever the logical logical level is necessary whenever the logical structure of the database is altered.structure of the database is altered.

Logical data independence is more difficult to Logical data independence is more difficult to achieve than is physical data independence, since achieve than is physical data independence, since application programs are heavily dependent on the application programs are heavily dependent on the logical structure of the data that they access.logical structure of the data that they access.

Page 26: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2626

Types of usersTypes of users

Database administrator (DBA)Database administrator (DBA)

Database designer (DBD)Database designer (DBD)

System Analyst and Application System Analyst and Application ProgrammerProgrammer

End usersEnd users

Page 27: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2727

Types of users (contd..)Types of users (contd..)

Database Administrator:Database Administrator:

– Is responsible for authorizing access to the Is responsible for authorizing access to the database.database.

– Co-coordinating & monitoring of database.Co-coordinating & monitoring of database.– Acquiring software & hardware resources, this Acquiring software & hardware resources, this

is needed for efficient working of database is needed for efficient working of database system.system.

Page 28: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2828

Types of users (contd..)Types of users (contd..)

Database Designer (DBD)Database Designer (DBD)

The Database Designer is responsible for The Database Designer is responsible for identifying the data to be stored in the identifying the data to be stored in the database and for choosing appropriate data database and for choosing appropriate data structures to represent and store the data.structures to represent and store the data.

Page 29: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

2929

Types of users (contd..)Types of users (contd..)

System Analyst and Application System Analyst and Application ProgrammerProgrammer

System analyst is responsible to conduct System analyst is responsible to conduct the system study for the further the system study for the further development of the system. Application development of the system. Application programmer is responsible to develop the programmer is responsible to develop the applications according to the user applications according to the user requirements. User requirements also be requirements. User requirements also be collected by the system analyst and then collected by the system analyst and then also checked for the feasibility. also checked for the feasibility.

Page 30: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3030

Types of users (contd..)Types of users (contd..)

End UsersEnd Users End users are the users who work on the End users are the users who work on the

applications and software’s developed by applications and software’s developed by the application programmers and the the application programmers and the system analyst.system analyst.

End Users have several sub categories End Users have several sub categories as:as:

– Sophisticated end users. Sophisticated end users. – Standalone end usersStandalone end users

Page 31: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3131

Types of users (contd..)Types of users (contd..)

Sophisticated End Users:Sophisticated End Users: These users work on the specially designed These users work on the specially designed

applications as whether forecasting applications as whether forecasting applications, banking systems, library applications, banking systems, library systems and all these applications are systems and all these applications are custom build according to their specific custom build according to their specific requirements.requirements.

Page 32: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3232

Types of users (contd..)Types of users (contd..)

Standalone End Users:Standalone End Users: These users work on the available software These users work on the available software

or applications packages. These packages or applications packages. These packages are not custom build according to their are not custom build according to their requirements as Data entry operator in any requirements as Data entry operator in any organization who uses word processing organization who uses word processing applications, accounts manager who user applications, accounts manager who user financial management applications etc.financial management applications etc.

Page 33: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3333

Overall System StructureOverall System Structure

The database System is partitioned into The database System is partitioned into modules that deal with each of the modules that deal with each of the responsibilities of the overall system. The responsibilities of the overall system. The computer’s OS may provide some at the computer’s OS may provide some at the functions of the database system.functions of the database system.

The functional components of a DBMS can The functional components of a DBMS can be broadly divided into Query Processors & be broadly divided into Query Processors & Storage Manager components.Storage Manager components.

Page 34: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3434

Overall System Structure (contd..)Overall System Structure (contd..)

QUERY PROCESSOR COMPONENTSQUERY PROCESSOR COMPONENTS

DML CompilerDML Compiler Embedded DML Pre-CompilerEmbedded DML Pre-Compiler DDL InterpreterDDL Interpreter Query Evaluation EngineQuery Evaluation Engine

Page 35: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3535

Overall System Structure (contd..)Overall System Structure (contd..)

Storage manager ComponentsStorage manager Components

Authorization & integrity managersAuthorization & integrity managers Transaction ManagerTransaction Manager File ManagerFile Manager Buffer ManagementBuffer Management

Page 36: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3636

Overall System Structure (contd..)Overall System Structure (contd..)

In addition, several data structuresIn addition, several data structures

Data filesData files Data DictionaryData Dictionary IndicesIndices Statistical dataStatistical data

Page 37: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3737

Overall System Structure (contd..)Overall System Structure (contd..)

Page 38: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3838

Data Base LanguageData Base Language

DDL - DDL - to specify the database Schema.to specify the database Schema.

DML - DML - to express database queries and to express database queries and updates.updates.

DCLDCL – Data Control Language – Data Control Language

Page 39: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

3939

Data Base Language (contd..)Data Base Language (contd..)

DDL:DDL: - - A database scheme is specified by a A database scheme is specified by a set of definition expressed by a special set of definition expressed by a special language called DDL (Data Definition language called DDL (Data Definition language). The result at compilation of DDL language). The result at compilation of DDL statements is a set of tables that is stored in statements is a set of tables that is stored in a special file called data dictionary.a special file called data dictionary.

Page 40: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4040

Data Base Language (contd..)Data Base Language (contd..)DML:DML: - by data manipulation language, we - by data manipulation language, we

meanmean The retrieval of information stored in the The retrieval of information stored in the

database.database. The insertion of new information into the The insertion of new information into the

database.database. The deletion of information from the The deletion of information from the

database.database. The modification of information stored in the The modification of information stored in the

database.database.

Page 41: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4141

Data Base Language (contd..)Data Base Language (contd..)

DML is a language that enables users to DML is a language that enables users to access as manipulate data as organized by access as manipulate data as organized by the appropriate data model.the appropriate data model.

Procedural DMLProcedural DML (require by user to specify (require by user to specify what data are needed and how to get those what data are needed and how to get those data)data)

Non-procedural DMLNon-procedural DML (require by user to (require by user to specify what data are needed without specify what data are needed without specifying how to get those data)specifying how to get those data)

Page 42: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4242

Data Base Administrator (Basic Data Base Administrator (Basic functions)functions)

Schema DefinitionSchema Definition Storage structure & Access – method Storage structure & Access – method

definitiondefinition Schema & physical organization Schema & physical organization

modificationmodification Granting of authorization for data accessGranting of authorization for data access Integrity – constraint specificationIntegrity – constraint specification

Page 43: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4343

Data Base Administrator (Basic Data Base Administrator (Basic functions) (contd..)functions) (contd..)

Schema DefinitionSchema Definition The DBA creates the original The DBA creates the original database schema by combining a set of definition database schema by combining a set of definition that is translated by the DDL compiler to a set of that is translated by the DDL compiler to a set of tables that is stored permanently in the data tables that is stored permanently in the data dictionary.dictionary.

Storage structure & Access – method Storage structure & Access – method definitiondefinition The DBA creates appropriate storage The DBA creates appropriate storage structure and access methods by writing a set of structure and access methods by writing a set of definition, which is translated by the data-storage definition, which is translated by the data-storage and data – definition – language compiler.and data – definition – language compiler.

Page 44: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4444

Data Base Administrator (Basic Data Base Administrator (Basic functions) (contd..)functions) (contd..)

Granting of authorization for data accessGranting of authorization for data access The granting of different types of The granting of different types of organization allows the database organization allows the database administrator to regulate which parts of the administrator to regulate which parts of the database various user can access. The database various user can access. The authorization is kept in a special system authorization is kept in a special system structure that is consulted by the database structure that is consulted by the database system whenever access to the data is system whenever access to the data is attempted in the system.attempted in the system.

Page 45: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4545

Data Base Administrator (Basic Data Base Administrator (Basic functions) (contd..)functions) (contd..)

Integrity – constraint specificationIntegrity – constraint specification The The data values stored in the database must data values stored in the database must satisfy certain consistency constraints, must satisfy certain consistency constraints, must be specified by the DBA the integrity be specified by the DBA the integrity constraints are kept in a special system constraints are kept in a special system structure that is consulted by a database structure that is consulted by a database system whenever updates takes place in the system whenever updates takes place in the system.system.

Page 46: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4646

DATA MODELSDATA MODELS

Data Model is a collection of conceptual tools Data Model is a collection of conceptual tools for describing data, data relationships, data for describing data, data relationships, data semantics, and consistency constraints.semantics, and consistency constraints.

Two Major categories of data Models are:Two Major categories of data Models are: Logical ModelLogical Model Physical ModelPhysical Model

Page 47: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4747

DATA MODELS (contd..)DATA MODELS (contd..)

Logical Model can be further subdivided into Logical Model can be further subdivided into two categories as:two categories as:

Object-Based logical model Object-Based logical model

Record based logical modelRecord based logical model

Page 48: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4848

Object based Logical Model Object based Logical Model

Object based logical models are used in Object based logical models are used in describing data at the logical & view level. describing data at the logical & view level. They are characterized by the fact that they They are characterized by the fact that they provide fairly flexible structuring capabilities provide fairly flexible structuring capabilities and allow data. Constraints to be specified and allow data. Constraints to be specified explicitly in Object based logical models.explicitly in Object based logical models.

Page 49: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

4949

Object based Logical Model (contd..)Object based Logical Model (contd..)

Object based logical model can be further Object based logical model can be further subdivided into four categories as:subdivided into four categories as:

The E-R modelThe E-R model The O-O modelThe O-O model The semantic ModelThe semantic Model The functional data modelThe functional data model

Page 50: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5050

The E-R ModelThe E-R Model

This model is based on a perception of a This model is based on a perception of a real world that consists of a collection of real world that consists of a collection of basic objects, called entities, and of basic objects, called entities, and of relationship among these objects.relationship among these objects.

Entities are described in a database by a set Entities are described in a database by a set of attribute. A set of all entities of the same of attribute. A set of all entities of the same type, and the set of all relationship of the type, and the set of all relationship of the same type are referred as entity set and same type are referred as entity set and relationship set.relationship set.

Page 51: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5151

The E-R Model (contd..)The E-R Model (contd..)

In addition to entities & relationships, the E-R model In addition to entities & relationships, the E-R model represents certain Constraint to which the content of the represents certain Constraint to which the content of the database must contain.database must contain.

The overall logical structure of a database can be expressed The overall logical structure of a database can be expressed graphically by an E-R diagram, which is built up from the graphically by an E-R diagram, which is built up from the following component:following component:

Rectangles –Rectangles – which represent entity set which represent entity set Ellipse –Ellipse – which represent attributes which represent attributes Diamonds –Diamonds – which represent relationship among entity set which represent relationship among entity set Line –Line – which link attributes to entity set and Entity set to which link attributes to entity set and Entity set to

relationship. relationship.

Page 52: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5252

The (min,max) notation

(1,1)(0,1)

(1,N)(1,1)

Page 53: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5353

SUMMARY OF ER-DIAGRAM SUMMARY OF ER-DIAGRAM NOTATION FOR ER SCHEMASNOTATION FOR ER SCHEMAS

MeaningMeaning

ENTITY TYPEENTITY TYPE

WEAK ENTITY TYPEWEAK ENTITY TYPE

RELATIONSHIP TYPERELATIONSHIP TYPE

IDENTIFYING RELATIONSHIP TYPEIDENTIFYING RELATIONSHIP TYPE

ATTRIBUTEATTRIBUTE

KEY ATTRIBUTEKEY ATTRIBUTE

MULTIVALUED ATTRIBUTEMULTIVALUED ATTRIBUTE

COMPOSITE ATTRIBUTECOMPOSITE ATTRIBUTE

DERIVED ATTRIBUTEDERIVED ATTRIBUTE

TOTAL PARTICIPATION OF ETOTAL PARTICIPATION OF E22 IN R IN R

CARDINALITY RATIO 1:N FOR ECARDINALITY RATIO 1:N FOR E11:E:E2 2 IN RIN R

STRUCTURAL CONSTRAINT (min, max) ON STRUCTURAL CONSTRAINT (min, max) ON PARTICIPATION OF E IN RPARTICIPATION OF E IN R

Symbol

E1 R E2

E1 R E2

R(min,max)

E

N

Page 54: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5454

ER DIAGRAM – Entity Types are:ER DIAGRAM – Entity Types are:EMPLOYEE, DEPARTMENT, PROJECT, DEPENDENTEMPLOYEE, DEPARTMENT, PROJECT, DEPENDENT

Page 55: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5555

COMPANY ER Schema DiagramCOMPANY ER Schema Diagram using (min, max) notation using (min, max) notation

Page 56: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5656

Designing an ER DiagramDesigning an ER Diagram

Consider the following set of requirements for a University database. Design an ER Consider the following set of requirements for a University database. Design an ER diagram for this application:diagram for this application:

The university keeps track of each student's name, student number, social security The university keeps track of each student's name, student number, social security number, current address and phone number, permanent address and phone number, current address and phone number, permanent address and phone number, birthdate, sex, class (freshman, graduate), major department, minor number, birthdate, sex, class (freshman, graduate), major department, minor department (if any), degree program (B.A., B.S., ... Ph.D.).  Some user department (if any), degree program (B.A., B.S., ... Ph.D.).  Some user applications need to refer to the city, state, and zip code of the student's applications need to refer to the city, state, and zip code of the student's permanent address and to the student's last name.  Both social security number permanent address and to the student's last name.  Both social security number and student number are unique for each student. All students will have at least a and student number are unique for each student. All students will have at least a major department.major department.

Each department is described by a name, department code, office number, office Each department is described by a name, department code, office number, office phone, and college.  Both the name and code have unique values for each phone, and college.  Both the name and code have unique values for each department. department.

Each course has a course name, description, course number, number of credits, Each course has a course name, description, course number, number of credits, level and offering department.  The course number is unique for each course. level and offering department.  The course number is unique for each course.

Each section has an instructor, semester, year, course, and section number.  The Each section has an instructor, semester, year, course, and section number.  The section number distinguishes sections of the same course that are taught during section number distinguishes sections of the same course that are taught during the same semester/year; its value is an integer (1, 2, 3, ... up to the number of the same semester/year; its value is an integer (1, 2, 3, ... up to the number of sections taught during each semester). sections taught during each semester).

A grade report must be generated for each student that lists the section, letter A grade report must be generated for each student that lists the section, letter grade, and numeric grade (0,1,2,3, or 4) for each student and calculates his or her grade, and numeric grade (0,1,2,3, or 4) for each student and calculates his or her average GPA. average GPA.

Page 57: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5757

University ER DiagramUniversity ER Diagram

Student

Class

StudentID SSN

Sex

Zip

Degree

City

Birth date

State

Name

Address

Department

DName DCode OfficeNumber

OfficePhone

College

Course

CName

CourseDesc

CNumber

Credits

Section

Instructor Year

SemesterSectionNumber

GPA

Numeric Grade

Letter Grade

Grade_Report

Belong_To

Offer

Minor In

Major In

Page 58: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5858

ER DIAGRAM FOR A BANK ER DIAGRAM FOR A BANK DATABASEDATABASE

© The Benjamin/Cummings Publishing Company, Inc. 1994, Elmasri/Navathe, Fundamentals of Database Systems, Second Edition

Page 59: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

5959

FIGURE 3.17FIGURE 3.17An ER An ER

diagram for diagram for an AIRLINE an AIRLINE

database database schema.schema.

Page 60: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6060

The E-R Model (contd..)The E-R Model (contd..)

An algorithm for an ER diagramAn algorithm for an ER diagram Read the problem carefully.Read the problem carefully. Identify the meaningful entity. Identify the meaningful entity. Identify the basic attributes.Identify the basic attributes. Associated each & every entity.Associated each & every entity. Identify the relationship among the previously Identify the relationship among the previously

identifying entities.identifying entities. Connect attributes to there respective entities & Connect attributes to there respective entities &

establish a relationship with the help of linker.establish a relationship with the help of linker.

Page 61: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6161

The E-R Model (contd..)The E-R Model (contd..)

Example of schema in the entity-relationship Example of schema in the entity-relationship modelmodel

Page 62: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6262

The E-R Model (contd..)The E-R Model (contd..)

E-R model of real worldE-R model of real world– Entities (objects) Entities (objects)

E.g. customers, accounts, bank branchE.g. customers, accounts, bank branch

– Relationships between entitiesRelationships between entities E.g. Account A-101 is held by customer JohnsonE.g. Account A-101 is held by customer Johnson Relationship set Relationship set depositordepositor associates customers with accounts associates customers with accounts

Widely used for database designWidely used for database design– Database design in E-R model usually converted to Database design in E-R model usually converted to

design in the relational model (coming up next) which is design in the relational model (coming up next) which is used for storage and processingused for storage and processing

Page 63: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6363

The Object-Oriented Model The Object-Oriented Model

This is based on a collection of objects. An This is based on a collection of objects. An object contains Values stored in instance object contains Values stored in instance variable with in the object. An object also variable with in the object. An object also contains bodies of code that operate on the contains bodies of code that operate on the object. These bodies of code are collect object. These bodies of code are collect methods.methods.

Page 64: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6464

The Object-Oriented Model (contd..)The Object-Oriented Model (contd..)

Objects that contain the same types of Objects that contain the same types of values and the same methods grouped values and the same methods grouped together into classes. A class may be together into classes. A class may be viewed as a type definition for objects.viewed as a type definition for objects.

The only way in which are object can The only way in which are object can access the data of another object is by access the data of another object is by invoking a method of that other object. This invoking a method of that other object. This action is called sending a message to the action is called sending a message to the object.object.

Page 65: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6565

Record Based Logical Model Record Based Logical Model

These models are used in describing data at the These models are used in describing data at the logical & view level. In contrast to object based logical & view level. In contrast to object based data models, they are used both to specify the data models, they are used both to specify the overall logical structure of the database and to overall logical structure of the database and to provide a higher-level description of the provide a higher-level description of the implementation.implementation.

The main models under this category areThe main models under this category are Relational ModelRelational Model Network ModelNetwork Model Hierarchical ModelHierarchical Model

Page 66: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6666

Relational Model Relational Model

The relational model uses a collection of The relational model uses a collection of tables to represent both data and the tables to represent both data and the relationships among those data. Each table relationships among those data. Each table has multiple columns, and each column has has multiple columns, and each column has a unique name.a unique name.

Page 67: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6767

Network Model Network Model

Data in the network model are represented Data in the network model are represented by collection of records, and relationships by collection of records, and relationships among data are represented by links, which among data are represented by links, which can be viewed as pointers. The records in can be viewed as pointers. The records in the database are organized as collection of the database are organized as collection of arbitrary graphs.arbitrary graphs.

Page 68: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6868

Hierarchical Model Hierarchical Model

The Hierarchical model is similar to the The Hierarchical model is similar to the Network model in the sense that data and Network model in the sense that data and relationship among data are represented by relationship among data are represented by record and links, respectively. It differs from record and links, respectively. It differs from the network model in that the records are the network model in that the records are organized as collection trees rather than organized as collection trees rather than arbitrary graphs.arbitrary graphs.

Page 69: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

6969

Differences among the ModelsDifferences among the Models

The relational model differs from the The relational model differs from the network & hierarchical model in that it does network & hierarchical model in that it does not have pointers as links. Instead, the not have pointers as links. Instead, the relational model relates records by the relational model relates records by the values that they contain.values that they contain.

Page 70: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7070

Physical Data ModelPhysical Data Model

This is used to describe data at the lowest This is used to describe data at the lowest level. In contrast to logical data models, level. In contrast to logical data models, there are few physical data models in use.there are few physical data models in use.

Unifying ModelUnifying Model

Frame memory model.Frame memory model.

Page 71: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7171

Relational ModelRelational Model

A particular way of structuring data (using A particular way of structuring data (using relations)relations)

SimpleSimple Mathematically basedMathematically based

– Expressions (Expressions ( queriesqueries) can be analyzed by DBMS) can be analyzed by DBMS– Queries are transformed to equivalent expressions Queries are transformed to equivalent expressions

automatically (automatically (query optimizationquery optimization)) Optimizers have limits (=> programmer needs to know how Optimizers have limits (=> programmer needs to know how

queries are evaluated and optimized)queries are evaluated and optimized)

Page 72: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7272

Relation InstanceRelation Instance

Relation is a set of tuplesRelation is a set of tuples– Tuple ordering immaterialTuple ordering immaterial– No duplicatesNo duplicates– CardinalityCardinality of relation = number of tuples of relation = number of tuples

All tuples in a relation have the same structure; All tuples in a relation have the same structure; constructed from the same set of attributesconstructed from the same set of attributes– Attributes are named (ordering is immaterial)Attributes are named (ordering is immaterial)– Value of an attribute is drawn from the attribute’s Value of an attribute is drawn from the attribute’s

domaindomain There is also a special value There is also a special value nullnull (value unknown or (value unknown or

undefined), which belongs to no domainundefined), which belongs to no domain– ArityArity of relation = number of attributes of relation = number of attributes

Page 73: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7373

Relation Instance (Example)Relation Instance (Example)

Id Name Address Status11111111 John 123 Main freshman

12345678 Mary 456 Cedar sophmore

44433322 Art 77 So. 3rd senior

87654321 Pat 88 No. 4th sophmore

Page 74: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7474

Relation SchemaRelation Schema

Relation nameRelation name Attribute names & domainsAttribute names & domains Integrity constraints like Integrity constraints like

– The values of a particular attribute in all tuples The values of a particular attribute in all tuples are uniqueare unique

– The values of a particular attribute in all tuples The values of a particular attribute in all tuples are greater than 0 are greater than 0

Default valuesDefault values

Page 75: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7575

Relational DatabaseRelational Database

Finite set of relationsFinite set of relations Each relation consists of a schema and an Each relation consists of a schema and an

instanceinstance Database schemaDatabase schema = set of relation = set of relation

schemas constraints among relations (schemas constraints among relations (inter-inter-relationalrelational constraints) constraints)

Database instanceDatabase instance = set of (corresponding) = set of (corresponding) relation instancesrelation instances

Page 76: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7676

Database Schema (Example)Database Schema (Example)

StudentStudent ((IdId: : INTINT, , NameName: : STRINGSTRING, , AddressAddress: : STRINGSTRING, ,

StatusStatus: : STRINGSTRING)) Professor (Professor (IdId: : INTINT, , NameName: : STRINGSTRING, , DeptIdDeptId: : DEPTSDEPTS)) Course (Course (DeptIdDeptId: : DEPTSDEPTS, , CrsNameCrsName: : STRINGSTRING, , CrsCodeCrsCode: : COURSESCOURSES)) Transcript (Transcript (CrsCodeCrsCode: : COURSESCOURSES, , StudIdStudId: : INTINT,, GradeGrade: : GRADESGRADES, , SemesterSemester: :

SEMESTERSSEMESTERS)) Department(Department(DeptIdDeptId: : DEPTSDEPTS, , NameName: : STRINGSTRING))

Page 77: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7777

CODD’S RULES CODD’S RULES

Rule 0 Rule 0 For a system to qualify as RELATIONAL DATABASE For a system to qualify as RELATIONAL DATABASE

MANAGEMENT system, that system must use its MANAGEMENT system, that system must use its relational facilities (exclusively) to MANAGE the relational facilities (exclusively) to MANAGE the DATABASE.DATABASE.

Rule 1. The Information representation ruleRule 1. The Information representation ruleThe information rule simply requires all information in The information rule simply requires all information in

the database to be represented in one and only the database to be represented in one and only one way, namely by values in column positions one way, namely by values in column positions within rows of tables.within rows of tables.

Page 78: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7878

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 2. The guaranteed access ruleRule 2. The guaranteed access rule This rule is essentially a restatement of the This rule is essentially a restatement of the

fundamental requirement for primary keys. It fundamental requirement for primary keys. It says that every individual scalar value in the says that every individual scalar value in the database must be logically addressable by database must be logically addressable by specifying the name of the containing table, specifying the name of the containing table, the name of the containing column and the the name of the containing column and the primary key value of the containing row.primary key value of the containing row.

Page 79: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

7979

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 3. Systematic treatment of null values.Rule 3. Systematic treatment of null values. The DBMS is required to support a representation The DBMS is required to support a representation

of “missing information and inapplicable of “missing information and inapplicable information” that is systematic, distinct from all information” that is systematic, distinct from all regular values (for example, “distinct from zero or regular values (for example, “distinct from zero or any other number,” in the case of numeric values), any other number,” in the case of numeric values), and independent of data type. It is also implied and independent of data type. It is also implied that such representations must be manipulated by that such representations must be manipulated by the DBMS in a systematic way.the DBMS in a systematic way.

Page 80: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8080

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 5. Active on line catalog based on the relational Rule 5. Active on line catalog based on the relational model.model.

The system must support a least one relational language The system must support a least one relational language thatthat

Has a linear syntax.Has a linear syntax. Can be used interactively and within application programs, Can be used interactively and within application programs,

and and Supports data definition operations (including view Supports data definition operations (including view

definitions), data manipulation operations (update as well definitions), data manipulation operations (update as well as retrieval), security and integrity constraints, and as retrieval), security and integrity constraints, and transaction management operations (begin, commit, and transaction management operations (begin, commit, and rollback.)rollback.)

Page 81: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8181

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 6. The view-updating ruleRule 6. The view-updating rule All views that are theoretically updateable All views that are theoretically updateable

must be updateable by the system.must be updateable by the system.

Rule 7. High-level Insert, Update, and Rule 7. High-level Insert, Update, and Delete.Delete.

The system must support set-at-a-time The system must support set-at-a-time INSERT, UPDATE, & DELETE operators.INSERT, UPDATE, & DELETE operators.

Page 82: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8282

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 8. Physical data IndependenceRule 8. Physical data Independence Self-explanatory.Self-explanatory.

Rule 9. Logical data independence Rule 9. Logical data independence Self-explanatorySelf-explanatory

Page 83: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8383

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 10. Integrity IndependenceRule 10. Integrity Independence Integrity constraints must be specified Integrity constraints must be specified

separately from application programs and separately from application programs and stored in the catalog. It must be possible to stored in the catalog. It must be possible to change such constraints as and when change such constraints as and when appropriate without unnecessarily affecting appropriate without unnecessarily affecting existing applications.existing applications.

Page 84: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8484

CODD’S RULES (contd..)CODD’S RULES (contd..)

Rule 11. Distribution Independence Rule 11. Distribution Independence Existing applications should continue to operate Existing applications should continue to operate

successfullysuccessfully (a)(a) When a distributed version of the DBMS is first When a distributed version of the DBMS is first

introduced.introduced. (b)(b) When existing distributed data is redistributed a When existing distributed data is redistributed a

around the system.around the system.Rule 12. The non-subversion ruleRule 12. The non-subversion rule If the system provides a low-level (record-at-a-time) If the system provides a low-level (record-at-a-time)

interface, then that interface cannot be used to subvert the interface, then that interface cannot be used to subvert the system (e.g.) bypassing a relational security or integrity system (e.g.) bypassing a relational security or integrity constraint.constraint.

Page 85: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8585

SQL DATA TYPESSQL DATA TYPESData Type Description

Char(L) For fixed length text entries. Each column value using the CHAR contains the maximum numbers of characters (L) even if the actual length is shorter. Most DBMS have an upper limit on the length (L) such as 255.

VARCHAR(L) For variable-length text. Column value using VARCHAR contains only the actual number of characters not the maximum length as for the CHAR column. Most DBMS have an upper limit on the length (L) such as 255.

FLOAT(P) For columns containing numeric data with a floating precision. The precision parameter P indicates the number of significant digits.

BOOLEAN For columns containing data with two values such as true/false or yes/no.

Page 86: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8686

SQL DATA TYPES (contd..)SQL DATA TYPES (contd..)Data Type Description

DATE/TIME For columns containing dates and times.

DECIMAL(W,R) For column containing numeric data with a fixed precision. The W value indicates the total number of digits and the R value indicates the number of digits to the right of the decimal point. This data type is also called NUMERIC in some systems.

INTEGER For column containing the whole numbers (i.e. numbers without the decimal point)

Page 87: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8787

CREATE TABLE StatementCREATE TABLE Statement

A create table A create table statement can be used statement can be used to define the heading to define the heading part of a table. Create part of a table. Create Table is a statement in Table is a statement in the SQL.the SQL.

Example of student Example of student database:database:

Std ID Name Dept Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT LD 2.9

1003 Abdullah IT Network

3.1

Page 88: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8888

CREATE TABLE Statement CREATE TABLE Statement (contd..)(contd..)

CREATE TABLE StudentCREATE TABLE Student

(( Student_IDStudent_ID INTEGER,INTEGER,

NameName VARCHAR(30),VARCHAR(30),DeptDept CHAR(4),CHAR(4),

CourseCourse VARCHAR(30),VARCHAR(30),

GradeGrade DECIMAL(5,2)DECIMAL(5,2) ))

Page 89: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

8989

Connections among TablesConnections among Tables

To understand the relational database, To understand the relational database, connections or relationships among tables connections or relationships among tables also must be understood. The rows in a also must be understood. The rows in a table are usually related to rows in other table are usually related to rows in other tables. Matching (identical) values show tables. Matching (identical) values show relationships between tables.relationships between tables.

Page 90: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9090

Connections among Tables Connections among Tables (contd..)(contd..)

Consider the three tables as Consider the three tables as StudentStudent EnrollmentEnrollment OfferingOffering

Page 91: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9191

Connections among Tables Connections among Tables (contd..)(contd..)

Std_No Std_Last_Name

1001 Abdul

Std_No OfferNo

1001 1234

OfferNo CourseNo

1234 IS320

Student Table

Enrollment Table

Offerring Table

Here in the above example, the three tables are related to each other. Table 1 and Table 2 are related with the Std_No whereas Table 2 and table 3 are related with OfferNo.

Page 92: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9292

Integrity RulesIntegrity Rules

Entity IntegrityEntity Integrity means that each table means that each table must have a column or combination of must have a column or combination of columns with unique keys. Unique columns with unique keys. Unique means that no two rows of a table have means that no two rows of a table have the same value.the same value.

Page 93: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9393

Integrity Rules (contd..)Integrity Rules (contd..)

Referential IntegrityReferential Integrity means that the values means that the values of column in one table must match the of column in one table must match the values of columns in other table. For values of columns in other table. For example, the value of Std_No I each row of example, the value of Std_No I each row of the Enrollment Table must match the value the Enrollment Table must match the value of Std_No in some row of the Student Table. of Std_No in some row of the Student Table. Referential integrity ensures that a database Referential integrity ensures that a database contains valid connections.contains valid connections.

Page 94: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9494

Integrity Rules (contd..)Integrity Rules (contd..)

Superkey:Superkey: a column or combination of a column or combination of columns containing unique values for each columns containing unique values for each row. The combination of every column in a row. The combination of every column in a table is always a superkey because rows in table is always a superkey because rows in a table must be unique.a table must be unique.

Candidate key:Candidate key: a minimal superkey. A a minimal superkey. A superkey is minimal if removing any superkey is minimal if removing any columns makes it no longer unique.columns makes it no longer unique.

Page 95: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9595

Integrity Rules (contd..)Integrity Rules (contd..)

Null Value:Null Value: a special value that represents the a special value that represents the absence of actual value.absence of actual value.

Primary Key:Primary Key: a specially designated candidate a specially designated candidate key. The primary key for a table cannot contain key. The primary key for a table cannot contain null values.null values.

Foreign key:Foreign key: a column or combination of columns a column or combination of columns in which the values must match those of candidate in which the values must match those of candidate key, a foreign must have the same data type as its key, a foreign must have the same data type as its associated candidate key.associated candidate key.

Page 96: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9696

Applying the Integrity RulesApplying the Integrity Rules

Example of Primary Key:Example of Primary Key:

CREATE TABLE StudentCREATE TABLE Student(( Student_IDStudent_ID INTEGER,INTEGER,

NameName VARCHAR(30),VARCHAR(30),DeptDept CHAR(4),CHAR(4),CourseCourse VARCHAR(30),VARCHAR(30),GradeGrade DECIMAL(5,2),DECIMAL(5,2),CONSTRAINT PKStudent PRIMARY KEY CONSTRAINT PKStudent PRIMARY KEY

(Student_Id)(Student_Id) ))

Page 97: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9797

Applying the Integrity Rules Applying the Integrity Rules (contd..)(contd..)

Example of Primary key and Unique Key:Example of Primary key and Unique Key:

CREATE TABLE CourseCREATE TABLE Course

(( CourseNoCourseNo CHAR(6),CHAR(6),CrsDescCrsDesc VARCHAR(250),VARCHAR(250),

CrsUnitsCrsUnits INTEGER,INTEGER,

CONSTRAINT PKCourse PRIMARY CONSTRAINT PKCourse PRIMARY KEY (CourseNo),KEY (CourseNo),

CONSTRAINT UniqueCrsDesc UNIQUE CONSTRAINT UniqueCrsDesc UNIQUE (CrsDesc)(CrsDesc) ))

Page 98: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9898

Applying the Integrity Rules Applying the Integrity Rules (contd..)(contd..)

Example of Primary key and Foreign Key:Example of Primary key and Foreign Key:CREATE TABLE EnrollmentCREATE TABLE Enrollment

(( OfferNoOfferNo INTEGER,INTEGER,Student_IdStudent_Id INTEGER,INTEGER,EnrGradeEnrGrade DECIMAL(3,2),DECIMAL(3,2),CONSTRAINT PKEnrollment PRIMARY KEY CONSTRAINT PKEnrollment PRIMARY KEY

(OfferNo, (OfferNo, Student_Id),Student_Id),CONSTRAINT FKOfferNoCONSTRAINT FKOfferNo FOREIGN KEY (OfferNo) FOREIGN KEY (OfferNo) REFERENCES Offerrings,REFERENCES Offerrings,CONSTRAINT FKSdutent_Id FOREIGN KEY CONSTRAINT FKSdutent_Id FOREIGN KEY

(Student_Id) REFERENCES Student (Student_Id) REFERENCES Student ))

Page 99: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

9999

Delete and Update actions for Delete and Update actions for Referenced RowsReferenced Rows

For each referential integrity constraint, you For each referential integrity constraint, you should carefully consider actions on should carefully consider actions on referenced rows in parent table of 1-M referenced rows in parent table of 1-M relationships. A row is referenced if there relationships. A row is referenced if there are rows in a child table with foreign key are rows in a child table with foreign key values identical to the primary key value of values identical to the primary key value of the parent table row. the parent table row.

Page 100: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

100100

Delete and Update actions for Delete and Update actions for Referenced Rows (contd..)Referenced Rows (contd..)

Deleting a referenced row:Deleting a referenced row: What happens to What happens to related rows (that is, rows in the child table with related rows (that is, rows in the child table with the identical foreign key value) when the the identical foreign key value) when the referenced row in the parent table is deleted?referenced row in the parent table is deleted?

Updating the primary key of a referenced row:Updating the primary key of a referenced row: What happens to related rows when the primary What happens to related rows when the primary key of the referenced row in the parent table is key of the referenced row in the parent table is updated?updated?

Actions on referenced rows are important when Actions on referenced rows are important when changing the rows of the database.changing the rows of the database.

Page 101: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

101101

Delete and Update actions for Delete and Update actions for Referenced Rows (contd..)Referenced Rows (contd..)

Possible Actions:Possible Actions: There are several possible actions in There are several possible actions in

response to the deletion of a referenced row response to the deletion of a referenced row or the update of the primary key of a or the update of the primary key of a referenced row. The appropriate action referenced row. The appropriate action depends on the tables involved. The depends on the tables involved. The following list describes the actions and following list describes the actions and provides examples of usage.provides examples of usage.

Page 102: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

102102

Delete and Update actions for Delete and Update actions for Referenced Rows (contd..)Referenced Rows (contd..)

Restrict:Restrict: Do not allow the action on the Do not allow the action on the referenced row.referenced row.

Cascade:Cascade: Perform the same action (Cascade the Perform the same action (Cascade the action) to related rows.action) to related rows.

Nullify:Nullify: Set the foreign key of the related rows to Set the foreign key of the related rows to NULLNULL. The nullify actions is not permitted (or valid) . The nullify actions is not permitted (or valid) if the foreign key does not allow if the foreign key does not allow NULLNULL values. values.

Default:Default: Set the foreign key of related rows to its Set the foreign key of related rows to its default values.default values.

Page 103: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

103103

Delete and Update actions for Delete and Update actions for Referenced Rows (contd..)Referenced Rows (contd..)

The delete and update actions can be specified in The delete and update actions can be specified in SQL using the SQL using the ON DELETEON DELETE and and ON UPDATEON UPDATE clause. These clauses are added as part of the clause. These clauses are added as part of the foreign key constraints. For example the revised foreign key constraints. For example the revised CREATE TABLECREATE TABLE statement for the statement for the Enrollment Enrollment TableTable shows shows ON DELETEON DELETE and and ON UPDATEON UPDATE clauses for the clauses for the Enrollment Table.Enrollment Table. The The RESTRICTRESTRICT keyword means restrict (the first possible action). keyword means restrict (the first possible action). The keyword The keyword CASCADE, SET NULL,CASCADE, SET NULL, and and SET SET DEFAULTDEFAULT can be used to specify the second can be used to specify the second through fourth options, respectively.through fourth options, respectively.

Page 104: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

104104

Example on Delete and Update Example on Delete and Update actions for Referenced Rowactions for Referenced Row

CREATE TABLE EnrolmentCREATE TABLE Enrolment(( OfferNoOfferNo INTEGER NOT NULL,INTEGER NOT NULL,

StdSSNStdSSN CHAR(11) NOT NULL,CHAR(11) NOT NULL,EnrGradeEnrGrade DECIMAL(3,2),DECIMAL(3,2),CONSTRAINT PKEnrollment PRIMARY KEY CONSTRAINT PKEnrollment PRIMARY KEY

(OfferNo, (OfferNo, StdSSN),StdSSN),CONSTRAINT FKOfferNo FOREIGN KEY (OfferNo) CONSTRAINT FKOfferNo FOREIGN KEY (OfferNo)

REFERENCES Offering REFERENCES Offering ON DELETE RESTRICTON DELETE RESTRICTON UPDATE CASCADE,ON UPDATE CASCADE,CONSTRAINT FKStdSSN FOREIGN KEY (StdSSN) CONSTRAINT FKStdSSN FOREIGN KEY (StdSSN)

REFERENCES Student REFERENCES Student ON DELETE RESTRICTON DELETE RESTRICTON UPDATE CASCADE)ON UPDATE CASCADE)

Page 105: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

105105

Operators of Relational AlgebraOperators of Relational Algebra

Restrict (Select) and Project OperatorsRestrict (Select) and Project Operators Extended Cross Product OperatorExtended Cross Product Operator Join Operator (Natural Join and Outer Join Operator (Natural Join and Outer

Join)Join) Union, Intersection and Difference Union, Intersection and Difference

OperatorOperator

Page 106: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

106106

Restrict and Project operatorRestrict and Project operator

The restrict and project operators produce subsets of The restrict and project operators produce subsets of a table. They produce an output table that is a a table. They produce an output table that is a subset of an input table. Restrict produces a subset of an input table. Restrict produces a subsets of rows, while project produces a subsets subsets of rows, while project produces a subsets of columns. Restrict uses a condition or logical of columns. Restrict uses a condition or logical expression to indicate what rows should be expression to indicate what rows should be retained in the output. Project uses a list of column retained in the output. Project uses a list of column names to indicate what columns to retain in the names to indicate what columns to retain in the output.output.

Restrict and Project is often used together because Restrict and Project is often used together because tables can have many rows and columns.tables can have many rows and columns.

Page 107: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

107107

Extended Cross Product OperatorExtended Cross Product Operator

The extended cross product operator can The extended cross product operator can combine any two tables. Other table combine any two tables. Other table combining operators have conditions about combining operators have conditions about the tables to combine. The product of two the tables to combine. The product of two tables is a new table consisting of all tables is a new table consisting of all possible combinations of rows from the two possible combinations of rows from the two input tables.input tables.

Page 108: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

108108

Extended Cross Product Operator Extended Cross Product Operator (contd..)(contd..)

Facssn111-11-1111222-22-2222333-33-3333

Stdssn444-44-4444555-55-5555666-66-6666

Facssn Stdssn

111-11-1111 444-44-4444

111-11-1111 555-55-5555

111-11-1111 666-66-6666

222-22-2222 444-44-4444

222-22-2222 555-55-5555

222-22-2222 666-66-6666

333-33-3333 444-44-4444

333-33-3333 555-55-5555

333-33-3333 666-66-6666

Faculty Table Student Table

Faculty PRODUCT Student

Page 109: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

109109

Natural Join OperatorNatural Join Operator Join is the most widely used operator for Join is the most widely used operator for

combining tables. Because most databases have combining tables. Because most databases have many tables, combining table is important. Join many tables, combining table is important. Join differs from cross product because join requires a differs from cross product because join requires a matching condition on rows of two tables. matching condition on rows of two tables.

The natural join operator, a specialized kind of The natural join operator, a specialized kind of join, is the most common join operation. In a join, is the most common join operation. In a natural join operation, the join condition is equality, natural join operation, the join condition is equality, one of the join columns is removed, and the join one of the join columns is removed, and the join columns have the same unqualified name.columns have the same unqualified name.

Page 110: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

110110

Natural Join Operator (contd..)Natural Join Operator (contd..)

Facssn Facname

111-11-1111 A

222-22-2222 B

333-33-3333 C

Offerno Facssn

1111 111-11-1111

2222 222-22-2222

3333 111-1-1111

Facssn Facname Offerno

111-11-1111 A 1111

222-22-2222 B 2222

111-11-1111 A 3333

Faculty Table Offering Table

Faculty NATURAL JOIN Ofering Table

Page 111: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

111111

Outer Join OperatorOuter Join Operator

The result of the join operation includes the The result of the join operation includes the rows matching on the join condition. rows matching on the join condition. Sometimes it is useful to include both Sometimes it is useful to include both matching and non matching rows. The outer matching and non matching rows. The outer join operator provides the ability to preserve join operator provides the ability to preserve non matching rows in the result as well as to non matching rows in the result as well as to include the matching rows.include the matching rows.

Page 112: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

112112

Outer Join Operator (contd..)Outer Join Operator (contd..)

Facssn Facname

111-11-1111 A

222-22-2222 B

333-33-3333 C

Offerno Facssn

1111 111-11-1111

2222 222-22-2222

3333 111-1-1111

Facssn Facname Offerno

111-11-1111 A 1111

222-22-2222 B 2222

111-11-1111 A 3333

333-33-3333 C --------

Faculty Table Offering Table

Faculty OUTER JOIN Offering Table

Page 113: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

113113

Union, Intersection, and Union, Intersection, and Difference OperatorsDifference Operators

A union operation retrieves all the rows in A union operation retrieves all the rows in either table. An intersection operation either table. An intersection operation retrieves just the common rows. A difference retrieves just the common rows. A difference operation retrieves the rows in the first table operation retrieves the rows in the first table but not in the second table. but not in the second table.

Page 114: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

114114

Example of UNION OperatorExample of UNION OperatorStd ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT Logic Design

2.9

1003 Abdullah

IT Networks

3.1

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1004 Deepak BUSS HR 2.9

1005 Pankaj ENGG POWER 3.1

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT Logic Design 2.9

1003 Abdullah IT Networks 3.1

1004 Deepak BUSS HR 2.9

1005 Pankaj ENGG POWER 3.1

Table 1 UNION Table 2

Page 115: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

115115

Example of INTERSECTION Example of INTERSECTION OperatorOperator

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT Logic Design

2.9

1003 Abdullah

IT Networks

3.1

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1004 Deepak BUSS HR 2.9

1005 Pankaj ENGG POWER 3.1

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

Table 1 INTERSECTION Table 2

Page 116: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

116116

Example of DIFFERENCE OperatorExample of DIFFERENCE Operator

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1002 Salim IT Logic Design

2.9

1003 Abdullah

IT Networks

3.1

Std ID Name Dept. Course Grade

1001 Abdul IT DBMS 3.0

1004 Deepak BUSS HR 2.9

1005 Pankaj ENGG POWER 3.1

Std ID Name Dept. Course Grade

1002 Salim IT Logic Design 2.9

1003 Abdullah IT Networks 3.1

Table 1 DIFFERENCE Table 2

Page 117: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

117117

SQL - A Relational Database LanguageSQL - A Relational Database Language

1 Data Definition in SQLData Definition in SQL2 Retrieval Queries in SQLRetrieval Queries in SQL

2.1 Simple SQL Queries2.1 Simple SQL Queries2.2 Aliases, * and DISTINCT, Unspecified WHERE-clause2.2 Aliases, * and DISTINCT, Unspecified WHERE-clause2.3 Set Operations, Nesting of Queries, Set Comparisons2.3 Set Operations, Nesting of Queries, Set Comparisons2.4 The EXISTS function, NULLs, Explicit Sets2.4 The EXISTS function, NULLs, Explicit Sets2.5 Aggregate Functions and Grouping2.5 Aggregate Functions and Grouping2.6 Sub-string Comparisons, Arithmetic, ORDER BY2.6 Sub-string Comparisons, Arithmetic, ORDER BY2.7 Summary of SQL Queries2.7 Summary of SQL Queries

3 Specifying Updates in SQLSpecifying Updates in SQL4 Relational Views in SQLRelational Views in SQL5 Creating Indexes in SQLCreating Indexes in SQL6 Embedding SQL in a Programming LanguageEmbedding SQL in a Programming Language7 Recent Advances in SQLRecent Advances in SQL

Page 118: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

118118

1 1 Data Definition in SQLData Definition in SQL

Used to CREATE, DROP, and ALTER the Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database.descriptions of the tables (relations) of a database.

CREATE TABLE:CREATE TABLE: Specifies a new base relation by giving it a name, Specifies a new base relation by giving it a name,

and specifying each of its attributes and their data and specifying each of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), VARCHAR(n)).VARCHAR(n)).

A constraint NOT NULL may be specified on an A constraint NOT NULL may be specified on an attribute.attribute.

Page 119: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

119119

Example:Example: CREATE TABLE DEPARTMENTCREATE TABLE DEPARTMENT

(( DNAMEDNAME VARCHAR(10) VARCHAR(10) NOT NULLNOT NULLDNUMBERDNUMBER INTEGER INTEGER NOT NULLNOT NULL

MGRSSNMGRSSN CHAR(9) CHAR(9)MGRSTARTDATE CHAR(9) );MGRSTARTDATE CHAR(9) );

One important constraint One important constraint missingmissing from the CREATE from the CREATE TABLE command is that of specifying the primary key TABLE command is that of specifying the primary key attributes, secondary keys, and referential integrity attributes, secondary keys, and referential integrity constraints (foreign keys).constraints (foreign keys).

Key attributes can be specified via the CREATE Key attributes can be specified via the CREATE UNIQUE INDEX command.UNIQUE INDEX command.

More recent SQL systems can specify primary keys More recent SQL systems can specify primary keys and referential integrity constraints.and referential integrity constraints.

Page 120: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

120120

DROP TABLE:DROP TABLE: Used to remove a relation (base table) and its definition.Used to remove a relation (base table) and its definition. The relation can no longer be used in queries, updates, or any other The relation can no longer be used in queries, updates, or any other

commands since its description no longer exists.commands since its description no longer exists.

Example:Example:– DROP TABLE DEPENDENT;DROP TABLE DEPENDENT;

ALTER TABLEALTER TABLE:: Used to add an attribute to one of the base relations.Used to add an attribute to one of the base relations. The new attribute will have NULLs in all the tuples of the relation The new attribute will have NULLs in all the tuples of the relation

right after the command is executed; hence, the NOT NULL right after the command is executed; hence, the NOT NULL constraint is not allowed for such an attribute.constraint is not allowed for such an attribute.

Example:Example:– ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);

The database users must still enter a value for the new attribute JOB The database users must still enter a value for the new attribute JOB for each EMPLOYEE tuple. This can be done using the UPDATE for each EMPLOYEE tuple. This can be done using the UPDATE command.command.

Page 121: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

121121

22 Retrieval Queries in SQL Retrieval Queries in SQL

SQL has one basic statement for retrieving information SQL has one basic statement for retrieving information from a database; the SELECT statement.from a database; the SELECT statement.

This is This is not the same asnot the same as the SELECT operation of the the SELECT operation of the relational algebra.relational algebra.

Important distinction between SQL and the formal Important distinction between SQL and the formal relational model; SQL allows a table (relation) to have relational model; SQL allows a table (relation) to have two or more tuples that are identical in all their attribute two or more tuples that are identical in all their attribute values.values.

Hence, an SQL relation (table) is a Hence, an SQL relation (table) is a multi-setmulti-set (sometimes (sometimes called a bag) of tuples; it called a bag) of tuples; it is notis not a set of tuples. a set of tuples.

SQL relations can be constrained to be sets by using SQL relations can be constrained to be sets by using the CREATE UNIQUE INDEX command, or by using the CREATE UNIQUE INDEX command, or by using the DISTINCT option.the DISTINCT option.

Page 122: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

122122

Basic form of the SQL SELECT statement is called a Basic form of the SQL SELECT statement is called a mappingmapping or a or a SELECT-FROM-WHERE block.SELECT-FROM-WHERE block.SELECTSELECT <attribute list><attribute list>

FROMFROM <table list><table list>

WHEREWHERE <condition><condition> <attribute list> is a list of attribute names whose values are to <attribute list> is a list of attribute names whose values are to

be retrieved by the query.be retrieved by the query. <table list> is a list of the relation names required to process <table list> is a list of the relation names required to process

the query.the query. <condition> is a conditional (Boolean) expression that identifies <condition> is a conditional (Boolean) expression that identifies

the tuples to be retrieved by the query.the tuples to be retrieved by the query.

Page 123: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

123123

2.12.1 Simple SQL Queries Simple SQL Queries

Basic SQL queries correspond to using the SELECT, Basic SQL queries correspond to using the SELECT, PROJECT, and JOIN operations of the relational algebra.PROJECT, and JOIN operations of the relational algebra.

All subsequent examples use the COMPANY database.All subsequent examples use the COMPANY database. Example of a simple query on Example of a simple query on oneone relation. relation.

Query 0Query 0: Retrieve the birthdate and address of the employee : Retrieve the birthdate and address of the employee whose name is ‘John B. Smith’.whose name is ‘John B. Smith’.

Q0: SELECT BDATE, ADDRESSQ0: SELECT BDATE, ADDRESS FROM EMPLOYEEFROM EMPLOYEE WHERE FNAME=‘John’ AND MINIT=‘B’ AND LNAME=‘Smith’WHERE FNAME=‘John’ AND MINIT=‘B’ AND LNAME=‘Smith’

Similar to a SELECT-PROJECT pair of relational algebra Similar to a SELECT-PROJECT pair of relational algebra operations; the SELECT-clause specifies the operations; the SELECT-clause specifies the projection attributesprojection attributes and the WHERE-clause specifies the and the WHERE-clause specifies the selection conditionselection condition..

However, the result of the query However, the result of the query may containmay contain duplicate tuples. duplicate tuples.

Page 124: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

124124

Query 1Query 1: Retrieve the name and address of all employees : Retrieve the name and address of all employees who work for the ‘Research’ department.who work for the ‘Research’ department.

Q1: SELECT FNAME, LNAME, ADDRESSQ1: SELECT FNAME, LNAME, ADDRESS FROMFROM EMPLOYEE, DEPARTMENT EMPLOYEE, DEPARTMENT WHERE DNAME=‘Research’ AND DNUMBER=DNOWHERE DNAME=‘Research’ AND DNUMBER=DNO

Similar to a SELECT-PROJECT-JOIN sequence of Similar to a SELECT-PROJECT-JOIN sequence of relational algebra operations.relational algebra operations.

(DNAME=‘Research’) is a (DNAME=‘Research’) is a selection conditionselection condition (corresponds (corresponds to a SELECT operation in relational algebra).to a SELECT operation in relational algebra).

(DNUMBER=DNO) is a (DNUMBER=DNO) is a join conditionjoin condition (corresponds to a (corresponds to a JOIN operation in relational algebra.JOIN operation in relational algebra.

Page 125: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

125125

Query 2Query 2: For every project located in ‘Stafford’ list the : For every project located in ‘Stafford’ list the project number, the controlling department number, and the project number, the controlling department number, and the department manager’s last name, address, and birthdate.department manager’s last name, address, and birthdate.

Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESSQ2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROMFROM PROJECT, DEPARTMENT, EMPLOYEE PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN ANDWHERE DNUM=DNUMBER AND MGRSSN=SSN AND

PLOCATION=‘Stafford’PLOCATION=‘Stafford’

In Q2, there are In Q2, there are twotwo join conditions. join conditions. The join condition DNUM=DNUMBER relates a project to The join condition DNUM=DNUMBER relates a project to

its controlling department.its controlling department. The join condition MGRSSN=SSN relates the controlling The join condition MGRSSN=SSN relates the controlling

department to the employee who manages that department to the employee who manages that department.department.

Page 126: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

126126

2.2 2.2 Aliases, *and DISTINCT, Unspecified WHERE-Aliases, *and DISTINCT, Unspecified WHERE-clauseclause

In SQL, we can use the same name for two (or more) In SQL, we can use the same name for two (or more) attributes as long as the attributes are in attributes as long as the attributes are in different relationsdifferent relations..

A query that refers to two or more attributes with the same A query that refers to two or more attributes with the same name must name must qualifyqualify the attribute name with the relation name the attribute name with the relation name by by prefixing prefixing the relation name to the attribute name.the relation name to the attribute name.

ExampleExample: EMPLOYEE.LNAME or DEPARTMENT.DNAME: EMPLOYEE.LNAME or DEPARTMENT.DNAME

ALIASESALIASES:: Some queries need to refer to the same relation twice.Some queries need to refer to the same relation twice. In this case, aliases are given to the relation name.In this case, aliases are given to the relation name.

Page 127: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

127127

Query 8Query 8: For each employee, retrieve the employee’s : For each employee, retrieve the employee’s name, and the name of his or her immediate name, and the name of his or her immediate supervisor.supervisor.

Q8: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEQ8: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E SFROM EMPLOYEE E S WHERE E.SUPERSSN=S.SSNWHERE E.SUPERSSN=S.SSN

In Q8, the alternate relation names E and S are called In Q8, the alternate relation names E and S are called aliasesaliases for the EMPLOYEE relation for the EMPLOYEE relation

We can think of E and S as We can think of E and S as two differenttwo different copies of the copies of the EMPLOYEE relation; E represents employees in the role of EMPLOYEE relation; E represents employees in the role of superviseessupervisees and S represents employees in the role of and S represents employees in the role of supervisorssupervisors..

Aliasing can also be used in any SQL query for Aliasing can also be used in any SQL query for convenience.convenience.

Page 128: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

128128

UNSPECIFIED WHERE-clauseUNSPECIFIED WHERE-clause

A A missing WHERE-clausemissing WHERE-clause indicates no condition; indicates no condition; hence hence all tuplesall tuples of the relations in the FROM-clause of the relations in the FROM-clause are selected.are selected.

This is equivalent to the condition WHERE TRUE.This is equivalent to the condition WHERE TRUE.

Query 9Query 9: Retrieve the SSN values for all employees.: Retrieve the SSN values for all employees.

Q9: SELECT SSNQ9: SELECT SSN FROMFROM EMPLOYEE EMPLOYEE

If more than one relation is specified in the FROM-If more than one relation is specified in the FROM-clause clause andand there is no join condition, then the there is no join condition, then the CARTESIAN PRODUCT of tuples is selected.CARTESIAN PRODUCT of tuples is selected.

Page 129: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

129129

ExampleExample::

Q10: SELECT SSN,DNAMEQ10: SELECT SSN,DNAME FROM EMPLOYEE, DEPARTMENTFROM EMPLOYEE, DEPARTMENT

It is extremely important not to overlook specifying any It is extremely important not to overlook specifying any selection and join conditions in the WHERE-clause; selection and join conditions in the WHERE-clause; otherwise, incorrect and very large relations may result.otherwise, incorrect and very large relations may result.

Page 130: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

130130

USE OF *:USE OF *:

To retrieve all the attribute values of the selected tuples, To retrieve all the attribute values of the selected tuples, a * is used, which stands for a * is used, which stands for all the attributesall the attributes..

ExamplesExamples::

Q1C: SELECT *Q1C: SELECT * FROMFROM EMPLOYEE EMPLOYEE WHERE DNO=5WHERE DNO=5

Q1D: SELECT *Q1D: SELECT * FROMFROM EMPLOYEE, DEPARTMENT EMPLOYEE, DEPARTMENT WHEREWHERE DNAME=‘Research’ AND DNO=DNUMBER DNAME=‘Research’ AND DNO=DNUMBER

Page 131: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

131131

USE OF DISTINCT:USE OF DISTINCT:

SQL does not treat a relation as a set; duplicate SQL does not treat a relation as a set; duplicate tuples can appear.tuples can appear.

To eliminate duplicate tuples, the keyword To eliminate duplicate tuples, the keyword DISTINCTDISTINCT is used.is used.

For example, the result of Q11 may have duplicate For example, the result of Q11 may have duplicate SALARY values whereas Q11A does not have any SALARY values whereas Q11A does not have any duplicate values.duplicate values.

Q11:Q11: SELECT SALARY SELECT SALARY FROM EMPLOYEEFROM EMPLOYEE

Q11A: SELECT DISTINCT SALARYQ11A: SELECT DISTINCT SALARY FROM EMPLOYEEFROM EMPLOYEE

Page 132: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

132132

2.3 2.3 Set Operations, Nesting of Queries, Set Set Operations, Nesting of Queries, Set ComparisonsComparisons

SET OPERATIONSSET OPERATIONS SQL has directly incorporated some set operations.SQL has directly incorporated some set operations. There is a union operation (There is a union operation (UNIONUNION), and in ), and in somesome

versions of SQL there are set differences (versions of SQL there are set differences (MINUSMINUS) ) and intersection (and intersection (INTERSECTINTERSECT) operations.) operations.

The resulting relations of these set operations are The resulting relations of these set operations are sets of tuples; sets of tuples; duplicate tuples are eliminated from duplicate tuples are eliminated from the resultthe result..

The set operations apply only to The set operations apply only to union compatible union compatible relationsrelations; the two relations must have the same ; the two relations must have the same attributes and the attributes must appear in the same attributes and the attributes must appear in the same order.order.

Page 133: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

133133

Query 4Query 4: Make a list of all project numbers for projects : Make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’ that involve an employee whose last name is ‘Smith’ as a worker or as a manager of the department that as a worker or as a manager of the department that controls the project.controls the project.

Q4: (SELECT PNAMEQ4: (SELECT PNAME FROMFROM PROJECT, DEPARTMENT, EMPLOYEE PROJECT, DEPARTMENT, EMPLOYEE

WHEREWHERE DNUM=DNUMBER AND MGRSSN=SSN DNUM=DNUMBER AND MGRSSN=SSN AND LNAME=‘Smith’)AND LNAME=‘Smith’)

UNIONUNION (SELECT PNAME(SELECT PNAME FROMFROM PROJECT, WORKS_ON, EMPLOYEE PROJECT, WORKS_ON, EMPLOYEE

WHEREWHERE PNUMBER=PNO AND ESSN=SSN AND PNUMBER=PNO AND ESSN=SSN AND LNAME=‘Smith’)LNAME=‘Smith’)

Page 134: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

134134

NESTING OF QUERIES:NESTING OF QUERIES:

A complete SELECT query, called a A complete SELECT query, called a nested querynested query, , can be specified within the WHERE-clause of another can be specified within the WHERE-clause of another query, called the query, called the outer queryouter query..

Many of the previous queries can be specified in an Many of the previous queries can be specified in an alternative form using nesting.alternative form using nesting.

Query 1Query 1: Retrieve the name and address of all : Retrieve the name and address of all employees who work for the ‘Research’ department.employees who work for the ‘Research’ department.

Q1: SELECTQ1: SELECT FNAME, LNAME, ADDRESSFNAME, LNAME, ADDRESS FROMFROM EMPLOYEEEMPLOYEE WHEREWHERE DNO IN ( SELECTDNO IN ( SELECT DNUMBERDNUMBER

FROMFROM DEPARTMENTDEPARTMENT WHEREWHERE DNAME=‘Research’ )DNAME=‘Research’ )

Page 135: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

135135

The nested query selects the number of the The nested query selects the number of the ‘Research’ department. ‘Research’ department.

The outer query select an EMPLOYEE tuple if its The outer query select an EMPLOYEE tuple if its DNO value is in the result of either nested query.DNO value is in the result of either nested query.

The comparison operator The comparison operator ININ compares a value v with compares a value v with a set (or multi-set) of values V, and evaluates to a set (or multi-set) of values V, and evaluates to TRUETRUE if v is one of the elements of V. if v is one of the elements of V.

In general, we can have several levels of nested In general, we can have several levels of nested queries.queries.

A reference to an A reference to an unqualified attributeunqualified attribute refers to the refers to the relation declared in the relation declared in the innermost nested queryinnermost nested query..

In this example, the nested query is In this example, the nested query is not correlatednot correlated with the outer query.with the outer query.

Page 136: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

136136

CORRELATED NESTED QUERIESCORRELATED NESTED QUERIES

If a condition in the WHERE-clause of a If a condition in the WHERE-clause of a nested querynested query references an attribute of a relation declared in the references an attribute of a relation declared in the outer outer queryquery, the two queries are said to be , the two queries are said to be correlatedcorrelated..

The result of a correlated nested query is The result of a correlated nested query is different from different from eacheach tuple ( tuple (or combination of tuplesor combination of tuples) ) of the relationof the relation((s) ofs) of the the outer query.outer query.

Query 12Query 12: Retrieve the name of each employee who has a : Retrieve the name of each employee who has a dependent with the same first name as the employee.dependent with the same first name as the employee.

Q12: SELECT E.FNAME, E.LNAMEQ12: SELECT E.FNAME, E.LNAME FROM EMPLOYEE EFROM EMPLOYEE E WHERE E.SSN IN ( SELECTWHERE E.SSN IN ( SELECT ESSNESSN

FROMFROM DEPENDENTDEPENDENT WHEREWHERE ESSN=E.SSN ANDESSN=E.SSN AND

F.NAME=DEPENDENT_NAME )F.NAME=DEPENDENT_NAME )

Page 137: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

137137

In Q12, the nested query has a different result In Q12, the nested query has a different result for each for each tupletuple in the outer query. in the outer query.

A query written with nested SELECT…FROM…A query written with nested SELECT…FROM…WHERE… blocks and using the = or IN comparison WHERE… blocks and using the = or IN comparison operators can operators can alwaysalways be expressed as a single block be expressed as a single block query. For example, Q12 may be written as in Q12A.query. For example, Q12 may be written as in Q12A.

Q12A: SELECT E.FNAME, E.LNAMEQ12A: SELECT E.FNAME, E.LNAME FROM EMPLOYEE E, DEPENDENT DFROM EMPLOYEE E, DEPENDENT D WHERE E.SSN=D.ESSN ANDWHERE E.SSN=D.ESSN AND

E.FNAME=D.DEPENDENT_NAMEE.FNAME=D.DEPENDENT_NAME

Page 138: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

138138

The original SQL as specified for SYSTEM R also had a The original SQL as specified for SYSTEM R also had a CONTAINSCONTAINS comparison operator, which is used in comparison operator, which is used in conjunction with nested correlated queries.conjunction with nested correlated queries.

This operator was dropped from the language, possibly This operator was dropped from the language, possibly because of the difficulty in implementing it efficiently.because of the difficulty in implementing it efficiently.

Most implementations of SQL Most implementations of SQL do notdo not have this operator. have this operator. The CONTAINS operator compares two The CONTAINS operator compares two sets of valuessets of values, ,

and returns TRUE if one set contains all values in the and returns TRUE if one set contains all values in the other set.other set.

Query 3Query 3: Retrieve the name of each employee who works on : Retrieve the name of each employee who works on allall the projects controlled by department number 5. the projects controlled by department number 5.

Page 139: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

139139

Q3: SELECT FNAME, LNAMEQ3: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE WHEREWHERE ( (SELECT ( (SELECT PNOPNO

FROMFROM WORKS_ONWORKS_ON WHEREWHERE SSN=ESSN)SSN=ESSN)

CONTAINSCONTAINS (SELECT(SELECT PNUMBERPNUMBER FROMFROM PROJECTPROJECT WHEREWHERE DNUM=5) )DNUM=5) )

In Q3, the second nested query, which is not In Q3, the second nested query, which is not correlated with the outer query, retrieves the project correlated with the outer query, retrieves the project numbers of all projects controlled by department 5.numbers of all projects controlled by department 5.

The first nested query, which is correlated, retrieves The first nested query, which is correlated, retrieves the project numbers on which the employee works, the project numbers on which the employee works, which is different which is different for each employee tuplefor each employee tuple because of because of the correlation.the correlation.

Page 140: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

140140

2.4 2.4 The EXISTS function, NULLs, Explicit SetsThe EXISTS function, NULLs, Explicit Sets

THE EXISTS FUNCTIONTHE EXISTS FUNCTION:: EXISTS used to check whether the result of a correlated EXISTS used to check whether the result of a correlated

nested query is empty (contains no tuples) or not.nested query is empty (contains no tuples) or not. We can formulate Query 12 in an alternative form that uses We can formulate Query 12 in an alternative form that uses

EXISTS as Q12B below.EXISTS as Q12B below.

Query 12Query 12: Retrieve the name of each employee who has a : Retrieve the name of each employee who has a dependent with the same first name as the employee.dependent with the same first name as the employee.

Q12B: SELECT FNAME, LNAMEQ12B: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE

WHERE EXISTS (SELECT *WHERE EXISTS (SELECT * FROM DEPENDENTFROM DEPENDENT WHERE SSN=ESSN ANDWHERE SSN=ESSN AND

FNAME=DEPENDENT_NAME)FNAME=DEPENDENT_NAME)

Page 141: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

141141

Query 6Query 6: Retrieve the names of employees who have : Retrieve the names of employees who have no dependents.no dependents.

Q6: SELECT FNAME, LNAMEQ6: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE

WHERE NOT EXISTSWHERE NOT EXISTS (SELECT * (SELECT * FROM DEPENDENTFROM DEPENDENT WHERE SSN=ESSN)WHERE SSN=ESSN)

In Q6, the correlated nested query retrieves all In Q6, the correlated nested query retrieves all DEPENDENT tuples related to an EMPLOYEE tuple. DEPENDENT tuples related to an EMPLOYEE tuple. If If none existnone exist, the EMPLOYEE tuple is selected., the EMPLOYEE tuple is selected.

EXISTS is necessary for the expressive power of EXISTS is necessary for the expressive power of SQL.SQL.

Page 142: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

142142

EXPLICIT SETS:EXPLICIT SETS:

It is also possible to use an explicit set of values in It is also possible to use an explicit set of values in the WHERE-clause rather than a nested query.the WHERE-clause rather than a nested query.

Query 13Query 13: Retrieve the social security numbers of all : Retrieve the social security numbers of all employees who work on project number 1, 2, or 3.employees who work on project number 1, 2, or 3.

Q13: SELECT DISTINCT ESSNQ13: SELECT DISTINCT ESSN FROM WORKS_ONFROM WORKS_ON WHERE PNO IN (1,2,3)WHERE PNO IN (1,2,3)

Page 143: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

143143

NULLS IN SQL QUERIES:NULLS IN SQL QUERIES:

SQL allows queries that check if a value is NULL SQL allows queries that check if a value is NULL (missing or undefined or not applicable).(missing or undefined or not applicable).

SQL uses SQL uses ISIS or or IS NOTIS NOT to compare NULLs because it to compare NULLs because it considers each NULL value distinct from other NULL considers each NULL value distinct from other NULL values, so equality comparison is not appropriate.values, so equality comparison is not appropriate.

Query 14Query 14: Retrieve the names of all employees who do not : Retrieve the names of all employees who do not have supervisors.have supervisors.

Q14: SELECT FNAME, LNAMEQ14: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE WHERE SUPERSSN IS NULLWHERE SUPERSSN IS NULL

NoteNote: If a join condition is specified, tuples with NULL : If a join condition is specified, tuples with NULL values for the join attributes are not included in the values for the join attributes are not included in the result.result.

Page 144: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

144144

2.5 2.5 Aggregate Functions and GroupingAggregate Functions and Grouping

AGGREGATE FUNCTIONSAGGREGATE FUNCTIONS:: Include COUNT, SUM, MAX, MIN, and AVGInclude COUNT, SUM, MAX, MIN, and AVG

Query 15Query 15: Find the maximum salary, the minimum salary, : Find the maximum salary, the minimum salary, and the average salary among all employees.and the average salary among all employees.

Q15: SELECT MAX (SALARY), MIN (SALARY), AVG Q15: SELECT MAX (SALARY), MIN (SALARY), AVG (SALARY)(SALARY)

FROM EMPLOYEEFROM EMPLOYEE

Some SQL implementations Some SQL implementations may not allow more than may not allow more than one functionone function in the SELECT-clause. in the SELECT-clause.

Page 145: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

145145

Query 16Query 16: Find the maximum salary, the minimum salary, : Find the maximum salary, the minimum salary, and the average salary among employees who work and the average salary among employees who work for the ‘Research’ department.for the ‘Research’ department.

Q16: SELECT MAX (SALARY), MIN (SALARY), AVG Q16: SELECT MAX (SALARY), MIN (SALARY), AVG (SALARY)(SALARY)

FROM EMPLOYEE, DEPARTMENTFROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME=‘Research’WHERE DNO=DNUMBER AND DNAME=‘Research’

Queries 17 and 18Queries 17 and 18: Retrieve the total number of : Retrieve the total number of employees in the company (Q17), and the number of employees in the company (Q17), and the number of employees in the ‘Research’ department (Q18).employees in the ‘Research’ department (Q18).

Q17: SELECT COUNT (*)Q17: SELECT COUNT (*) FROM EMPLOYEEFROM EMPLOYEE Q18: SELECT COUNT (*)Q18: SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENTFROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME=‘Research’WHERE DNO=DNUMBER AND DNAME=‘Research’

Page 146: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

146146

GROUPINGGROUPING

In many cases, we want to apply the aggregate functions In many cases, we want to apply the aggregate functions to to subgroups of tuples in a relationsubgroups of tuples in a relation..

Each subgroup of tuples consists of the set of tuples that Each subgroup of tuples consists of the set of tuples that have have the same valuethe same value for the for the grouping attributegrouping attribute((ss).).

The function is applied to each subgroup independently.The function is applied to each subgroup independently. SQL has a SQL has a GROUP BYGROUP BY-clause for specifying the grouping -clause for specifying the grouping

attributes, which attributes, which must also appear in the SELECT-clausemust also appear in the SELECT-clause..

Page 147: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

147147

Query 20Query 20: For each department, retrieve the department : For each department, retrieve the department number, the number of employees in the department, number, the number of employees in the department, and their average salary.and their average salary.

Q20: SELECT DNO, COUNT (*), AVE (SALARY)Q20: SELECT DNO, COUNT (*), AVE (SALARY) FROM EMPLOYEEFROM EMPLOYEE GROUP BY DNOGROUP BY DNO

In Q20, the EMPLOYEE tuples are divided into In Q20, the EMPLOYEE tuples are divided into groups -- each group having the same value for the groups -- each group having the same value for the grouping attribute DNO.grouping attribute DNO.

The COUNT and AVG functions are applied to each The COUNT and AVG functions are applied to each such group of tuples separately.such group of tuples separately.

The SELECT-clause includes only the grouping The SELECT-clause includes only the grouping attribute and the functions to be applied on each attribute and the functions to be applied on each group of tuples.group of tuples.

Page 148: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

148148

A join condition can be used in conjunction with A join condition can be used in conjunction with grouping.grouping.

Query 21Query 21: For each project, retrieve the project number, : For each project, retrieve the project number, project name, and the number of employees who project name, and the number of employees who work on the project.work on the project.

Q21: SELECT PNUMBER, PNAME, COUNT (*)Q21: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ONFROM PROJECT, WORKS_ON WHERE PNUMBER=PNOWHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME GROUP BY PNUMBER, PNAME

In this case, the grouping and functions are applied In this case, the grouping and functions are applied after after the joining of the two relations.the joining of the two relations.

Page 149: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

149149

THE HAVING-CLAUSE:THE HAVING-CLAUSE:

Sometimes we want to retrieve the values of these Sometimes we want to retrieve the values of these functions for only those functions for only those groups that satisfy certain groups that satisfy certain conditionsconditions..

The HAVING-clause is used for specifying a selection The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples).condition on groups (rather than on individual tuples).

Query 22Query 22: For each project : For each project on which more than two on which more than two employees workemployees work, retrieve the project number, project name, , retrieve the project number, project name, and the number of employees who work on that project.and the number of employees who work on that project.

Q22: SELECT PNUMBER, PNAME, COUNT (*)Q22: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ONFROM PROJECT, WORKS_ON WHERE PNUMBER=PNOWHERE PNUMBER=PNO GROUP BY PNUMBER, PNAMEGROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2 HAVING COUNT (*) > 2

Page 150: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

150150

2.6 2.6 Substring Comparisons, Arithmetic, ORDER BYSubstring Comparisons, Arithmetic, ORDER BY

SUBSTRING COMPARISONSUBSTRING COMPARISON:: The LIKE comparison operator is used to compare The LIKE comparison operator is used to compare

partial strings.partial strings. Two reserved characters are used: ‘%’ (or ‘*’ in some Two reserved characters are used: ‘%’ (or ‘*’ in some

implementations) replaces an arbitrary number of implementations) replaces an arbitrary number of characters, and ‘_’ replaces a single arbitrary character.characters, and ‘_’ replaces a single arbitrary character.

Query 25Query 25: Retrieve all employees whose address is in : Retrieve all employees whose address is in Houston, Texas. Here, the value of the ADDRESS Houston, Texas. Here, the value of the ADDRESS attribute must contain the substring ‘Houston,TX’.attribute must contain the substring ‘Houston,TX’.

Q25: SELECT FNAME, LNAMEQ25: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE WHERE ADDRESS LIKE ‘%Houston,TX%’WHERE ADDRESS LIKE ‘%Houston,TX%’

Page 151: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

151151

Query 26Query 26: Retrieve all employees who were born during : Retrieve all employees who were born during the 1950s. Here, ‘5’ must be the 8th character of the the 1950s. Here, ‘5’ must be the 8th character of the string (according to our format for date), so the string (according to our format for date), so the BDATE value is ‘______5_’, with each underscore as BDATE value is ‘______5_’, with each underscore as a place holder for a single arbitrary character.a place holder for a single arbitrary character.

Q26: SELECT FNAME, LNAMEQ26: SELECT FNAME, LNAME FROM EMPLOYEEFROM EMPLOYEE WHERE BDATE LIKE ‘______5_’WHERE BDATE LIKE ‘______5_’

The LIKE operator allows us to get around the fact The LIKE operator allows us to get around the fact that each value is considered atomic and indivisible; that each value is considered atomic and indivisible; hence, in SQL, character string attribute values are hence, in SQL, character string attribute values are not atomic.not atomic.

Page 152: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

152152

ARITHMETIC OPERATIONSARITHMETIC OPERATIONS

The standard arithmetic operators ‘+’, ‘-’, ‘*’ and ‘/’ (for The standard arithmetic operators ‘+’, ‘-’, ‘*’ and ‘/’ (for addition, subtraction, multiplication, and division, addition, subtraction, multiplication, and division, respectively) can be applied to numeric values in an respectively) can be applied to numeric values in an SQL query result.SQL query result.

Query 27Query 27: Show the effect of giving all employees who : Show the effect of giving all employees who work on the ‘ProductX’ project a 10% raise.work on the ‘ProductX’ project a 10% raise.

Q27: SELECT FNAME, LNAME, 1.1*SALARYQ27: SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECTFROM EMPLOYEE, WORKS_ON, PROJECT

WHERE SSN=ESSN AND PNO=PNUMBER AND WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME=‘ProductX’PNAME=‘ProductX’

Page 153: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

153153

ORDER BYORDER BY

The ORDER BY clause is used to sort the tuples in a query The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s).result based on the values of some attribute(s).

Query 28Query 28: Retrieve a list of employees and the projects each : Retrieve a list of employees and the projects each works in, ordered by the employee’s department, and within works in, ordered by the employee’s department, and within each department ordered alphabetically by employees last each department ordered alphabetically by employees last name.name.

Q28: SELECT DNAME, LNAME, FNAME, PNAMEQ28: SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARMENT, EMPLOYEE, WORKS_ON, PROJECTFROM DEPARMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN ANDWHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBERPNO=PNUMBER ORDER BY DNAME, LNAMEORDER BY DNAME, LNAME The default order is in ascending order of values.The default order is in ascending order of values. We can specify the keyword DESC if we want a descending We can specify the keyword DESC if we want a descending

order; the keyword ASC can be used to explicitly specify order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default.ascending order, even though it is the default.

Page 154: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

154154

2.7 Summary of SQL Queries2.7 Summary of SQL Queries

A query in SQL can consist of up to six clauses, but only A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order:clauses are specified in the following order:

SELECTSELECT <attribute list><attribute list>FROMFROM <table list><table list>[WHERE[WHERE <condition>]<condition>][GROUP BY[GROUP BY <grouping attribute(s)>]<grouping attribute(s)>][HAVING[HAVING <group condition>]<group condition>][ORDER BY[ORDER BY <attribute list>]<attribute list>]

Page 155: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

155155

The SELECT-clause lists the attributes or functions to be The SELECT-clause lists the attributes or functions to be retrieved.retrieved.

The FROM-clause specifies all relations (or aliases) The FROM-clause specifies all relations (or aliases) needed in the query but not those needed in nested needed in the query but not those needed in nested queries.queries.

The WHERE-clause specifies the conditions for selection The WHERE-clause specifies the conditions for selection and join of tuples from the relations specified in the and join of tuples from the relations specified in the FROM-clause.FROM-clause.

GROUP BY specifies grouping attributes.GROUP BY specifies grouping attributes. HAVING specifies a condition for selection of groups.HAVING specifies a condition for selection of groups. ORDER BY specifies an order for displaying the result of ORDER BY specifies an order for displaying the result of

the query.the query. A query is evaluated by first applying the WHERE-clause, A query is evaluated by first applying the WHERE-clause,

then GROUP BY and HAVING, and finally the SELECT-then GROUP BY and HAVING, and finally the SELECT-clause.clause.

Page 156: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

156156

33 Specifying Updates in SQL Specifying Updates in SQL There are three SQL commands to modify the database: There are three SQL commands to modify the database:

INSERT, DELETE, and UPDATE.INSERT, DELETE, and UPDATE.INSERTINSERT:: In its simplest form, it is used to add a single tuple to a In its simplest form, it is used to add a single tuple to a

relation.relation. Attribute values should be listed in the same order as the Attribute values should be listed in the same order as the

attributes were specified in the CREATE TABLE command.attributes were specified in the CREATE TABLE command.Example:Example:

U1: INSERT INTO EMPLOYEEU1: INSERT INTO EMPLOYEE VALUES (‘ Richard’, ‘K’, “Marini’, ‘653298653’, ‘30-DEC-52’VALUES (‘ Richard’, ‘K’, “Marini’, ‘653298653’, ‘30-DEC-52’ ‘ ‘98 Oak Forest,Katy,TX’, ‘M’, 37000, ‘987654321’, 4)98 Oak Forest,Katy,TX’, ‘M’, 37000, ‘987654321’, 4) An alternate form of INSERT specifies explicitly the attribute An alternate form of INSERT specifies explicitly the attribute

names that correspond to the values in the new tuple.names that correspond to the values in the new tuple. Attributes with NULL values can be left out.Attributes with NULL values can be left out.

Page 157: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

157157

ExampleExample: Insert a tuple for a new EMPLOYEE for whom : Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME, and SSN we only know the FNAME, LNAME, and SSN attributes.attributes.

U1A: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)U1A: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)

VALUES (‘Richard’, “Marini’, ‘653298653’)VALUES (‘Richard’, “Marini’, ‘653298653’)

Important NoteImportant Note: Only the constraints specified in the : Only the constraints specified in the DDL commands are automatically enforced by the DDL commands are automatically enforced by the DBMS when updates are applied to the database.DBMS when updates are applied to the database.

Page 158: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

158158

Another variation of INSERT allows insertion of multiple Another variation of INSERT allows insertion of multiple tuples in a relation in a single command.tuples in a relation in a single command.

ExampleExample: Suppose we want to create a temporary table that : Suppose we want to create a temporary table that has the name, number of employees, and total salaries has the name, number of employees, and total salaries for each department. A table DEPTS_INFO is created by for each department. A table DEPTS_INFO is created by U3A, and is loaded with the summary information U3A, and is loaded with the summary information retrieved from the database by the query in U3B.retrieved from the database by the query in U3B.

U3A: CREATE TABLE DEPTS_INFOU3A: CREATE TABLE DEPTS_INFO (DEPT_NAME(DEPT_NAME VARCHAR(10)VARCHAR(10) NO_OF_EMPSNO_OF_EMPS INTEGER,INTEGER, TOTAL_SALTOTAL_SAL INTEGER);INTEGER);

Page 159: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

159159

U3B: INSERT INTOU3B: INSERT INTODEPTS_INFO (DEPT_NAME, NO_OF_EMPS, DEPTS_INFO (DEPT_NAME, NO_OF_EMPS,

TOTAL_SAL)TOTAL_SAL)SELECT DNAME, COUNT (*), SUM (SALARY)SELECT DNAME, COUNT (*), SUM (SALARY)

FROMFROM DEPARTMENT, EMPLOYEE DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOWHERE DNUMBER=DNOGROUP BY DNAME;GROUP BY DNAME;

NoteNote: The DEPTS_INFO table may not be up-to-date if : The DEPTS_INFO table may not be up-to-date if we change the tuples in either the DEPARTMENT or we change the tuples in either the DEPARTMENT or the EMPLOYEE relations the EMPLOYEE relations afterafter issuing U3B. We have issuing U3B. We have to create a view (see later) to keep such a table up to to create a view (see later) to keep such a table up to date.date.

Page 160: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

160160

DELETEDELETE

Removes tuples from a relation.Removes tuples from a relation. Includes a WHERE-clause to select the tuples to be Includes a WHERE-clause to select the tuples to be

deleted.deleted. Tuples are deleted from only Tuples are deleted from only one tableone table at a time. at a time. A missing WHERE-clause specifies that A missing WHERE-clause specifies that all tuplesall tuples in in

the relation are to be deleted; the table then becomes the relation are to be deleted; the table then becomes an empty table.an empty table.

The number of tuples deleted depends on the The number of tuples deleted depends on the number of tuples in the relation that satisfy the number of tuples in the relation that satisfy the WHERE-clause condition.WHERE-clause condition.

Page 161: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

161161

Examples:Examples:

U4A: DELETE FROM EMPLOYEU4A: DELETE FROM EMPLOYE WHERE LNAME=‘Brown’WHERE LNAME=‘Brown’

U4B: DELETE FROM EMPLOYEEU4B: DELETE FROM EMPLOYEE WHERE SSN=‘123456789’WHERE SSN=‘123456789’

U4C: DELETE FROM EMPLOYEEU4C: DELETE FROM EMPLOYEE WHERE DNO IN (SELECT NUMBERWHERE DNO IN (SELECT NUMBER

FROM DEPARTMENT FROM DEPARTMENT WHERE WHERE

DNAME=‘Research’DNAME=‘Research’

U4D: DELETE FROM EMPLOYEEU4D: DELETE FROM EMPLOYEE

Page 162: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

162162

UPDATEUPDATE

Used to modify attribute values of one or more Used to modify attribute values of one or more selected tuples.selected tuples.

A WHERE-clause selects the tuples to be modified.A WHERE-clause selects the tuples to be modified. An additional SET-clause specifies the attributes to An additional SET-clause specifies the attributes to

be modified and their new values.be modified and their new values. Each command modifies tuples in the same relation.Each command modifies tuples in the same relation.

ExampleExample: Change the location and controlling : Change the location and controlling department number of project number 10 to ‘Bellaire’ department number of project number 10 to ‘Bellaire’ and 5, respectively.and 5, respectively.

U5: UPDATE PROJECTU5: UPDATE PROJECT SET SET PLOCATION=‘Bellaire’, DNUM=5 PLOCATION=‘Bellaire’, DNUM=5 WHERE PNUMBER= 10WHERE PNUMBER= 10

Page 163: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

163163

ExamplExample: Give all employees in the ‘Research’ e: Give all employees in the ‘Research’ department a 10% raise in salary.department a 10% raise in salary.

U6: UPDATE EMPLOYEEU6: UPDATE EMPLOYEE SET SALARY=SALARY *1.1SET SALARY=SALARY *1.1 WHERE DNO IN (SELECTWHERE DNO IN (SELECT DNUMBERDNUMBER

FROMFROM DEPARTMENTDEPARTMENT WHEREWHERE DNAME=‘Research’)DNAME=‘Research’)

In this request, the modified SALARY value depends In this request, the modified SALARY value depends on on

the original SALARY value in each tuple.the original SALARY value in each tuple. The reference to the SALARY attribute on the right of The reference to the SALARY attribute on the right of

= refers to the old SALARY value before modification.= refers to the old SALARY value before modification. The reference to the SALARY attribute on the left of = The reference to the SALARY attribute on the left of =

refers to the new SALARY value after modification.refers to the new SALARY value after modification.

Page 164: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

164164

4 4 Relational Views in SQLRelational Views in SQL

A view is a single A view is a single virtual tablevirtual table that is derived from that is derived from other tables.other tables.

The other tables could be base tables or previously The other tables could be base tables or previously defined views.defined views.

A view does not necessarily exist in physical form, A view does not necessarily exist in physical form, which limits the possible update operations that can which limits the possible update operations that can be applied to views.be applied to views.

There are no limitations on querying a view.There are no limitations on querying a view. The CREATE VIEW command is used to specify a The CREATE VIEW command is used to specify a

view by specifying a (virtual) table name and a view by specifying a (virtual) table name and a defining query.defining query.

The view attribute names can be The view attribute names can be inherited frominherited from the the attribute names of the tables in the defining query.attribute names of the tables in the defining query.

Page 165: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

165165

ExamplesExamples::

V1: CREATE VIEWV1: CREATE VIEW WORKS_ON1 WORKS_ON1 ASAS SELECT FNAME, LNAME, PNAME, HOURSSELECT FNAME, LNAME, PNAME, HOURS

FROM EMPLOYEE, PROJECT, WORKS_ONFROM EMPLOYEE, PROJECT, WORKS_ONWHERE SSN=ESSN AND PNO=PNUMBER;WHERE SSN=ESSN AND PNO=PNUMBER;

V2: CREATE VIEWV2: CREATE VIEW DEPT_INFO DEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL)(DEPT_NAME, NO_OF_EMPS, TOTAL_SAL)

ASAS SELECT DNAME, COUNT (*), SUM (SALARY)SELECT DNAME, COUNT (*), SUM (SALARY)FROM DEPARTMENT, EMPLOYEEFROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOWHERE DNUMBER=DNOGROUP BY DNAME;GROUP BY DNAME;

In V1, the names of the view attribute names are In V1, the names of the view attribute names are inherited.inherited.

In V2, the view attribute names are listed using a one-to-In V2, the view attribute names are listed using a one-to-one correspondence with the entries in the SELECT-one correspondence with the entries in the SELECT-clause of the defining query.clause of the defining query.

Page 166: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

166166

QUERIES ON VIEWS:QUERIES ON VIEWS:

ExampleExample: Retrieve the last name and first name of all : Retrieve the last name and first name of all employees who work on ‘ProjectX’.employees who work on ‘ProjectX’.

QV1: SELECT PNAME, FNAME, LNAMEQV1: SELECT PNAME, FNAME, LNAME FROM WORKS_ON1FROM WORKS_ON1

WHERE PNAME=‘ProjectX’WHERE PNAME=‘ProjectX’

Without the view WORKS_ON1, this query specification Without the view WORKS_ON1, this query specification would require two join conditions.would require two join conditions.

A view can be defined to simplify frequently occurring A view can be defined to simplify frequently occurring queries.queries.

The DBMS is responsible for keeping the view always The DBMS is responsible for keeping the view always up-to-date if the base tables on which the view is defined up-to-date if the base tables on which the view is defined are modified.are modified.

Page 167: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

167167

Hence, the view is not realized at the time of Hence, the view is not realized at the time of view view definitiondefinition, but rather at the time we specify a query on , but rather at the time we specify a query on the view.the view.

A view is removed using the DROP VIEW command.A view is removed using the DROP VIEW command.

ExampleExample:: V1A: DROP VIEW WORKS_ON1;V1A: DROP VIEW WORKS_ON1; V2A: DROP VIEW DEPT_INFO;V2A: DROP VIEW DEPT_INFO;

Views can also be used as a security and Views can also be used as a security and authorization mechanism (see Chapter 20).authorization mechanism (see Chapter 20).

Page 168: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

168168

UPDATING OF VIEWS:UPDATING OF VIEWS:

A view update operation may be mapped in multiple ways A view update operation may be mapped in multiple ways to update operations on the defining base relations.to update operations on the defining base relations.

The topic of updating views is still an active research area.The topic of updating views is still an active research area.

ExampleExample: Suppose we issue the command in UV1 to update : Suppose we issue the command in UV1 to update the WORKS_ON1 view by modifying the PNAME attribute the WORKS_ON1 view by modifying the PNAME attribute of ‘John Smith’ from ‘ProductX’ to ‘ProductY’.of ‘John Smith’ from ‘ProductX’ to ‘ProductY’.

UV1: UPDATE WORKS_ON1UV1: UPDATE WORKS_ON1

SETSET PNAME=‘ProductY’ PNAME=‘ProductY’

WHERE LNAME=‘Smith’ AND FNAME=‘John’ ANDWHERE LNAME=‘Smith’ AND FNAME=‘John’ AND

PNAME=‘ProductX’PNAME=‘ProductX’

Page 169: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

169169

This can be mapped into several updates on the This can be mapped into several updates on the base relations to give the desired update on the view. base relations to give the desired update on the view. Two possibilities are:Two possibilities are:1 Change the name of the ‘ProductX’ tuple in the Change the name of the ‘ProductX’ tuple in the

PROJECT relation to ‘ProductY’.PROJECT relation to ‘ProductY’.

- It is quite unlikely that the user who specified the view - It is quite unlikely that the user who specified the view update UV1 wants the update to be interpreted this update UV1 wants the update to be interpreted this way.way.

(1):(1): UPDATE PRODUCTUPDATE PRODUCT SET PNAME=‘ProductY’SET PNAME=‘ProductY’

WHERE PNAME=‘ProductX’WHERE PNAME=‘ProductX’

2 Relate ‘John Smith’ to the ‘ProductY’ PROJECT tuple Relate ‘John Smith’ to the ‘ProductY’ PROJECT tuple in place of the ‘ProductX’ PROJECT tuple.in place of the ‘ProductX’ PROJECT tuple.

- This is most likely the update the user means.- This is most likely the update the user means.

Page 170: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

170170

(2): UPDATE WORKS_ON (2): UPDATE WORKS_ON

SETSET PNO= (SELECT PNUMBER FROM PROJECT PNO= (SELECT PNUMBER FROM PROJECT

WHERE PNAME=‘ProductY’)WHERE PNAME=‘ProductY’)

WHERE ESSN= (SELECT SSN FROM EMPLOYEEWHERE ESSN= (SELECT SSN FROM EMPLOYEE

WHERE LNAME=‘Smith’ AND ‘FNAME=‘John’)WHERE LNAME=‘Smith’ AND ‘FNAME=‘John’)

ANDAND

PNO= (SELECT PNUMBER FROM PROJECTPNO= (SELECT PNUMBER FROM PROJECT

WHERE PNAME=‘ProductX’)WHERE PNAME=‘ProductX’)

Some view updates may not make much sense; for example, Some view updates may not make much sense; for example, modifying the TOTAL_SAL attribute of DEPT_INFO as in modifying the TOTAL_SAL attribute of DEPT_INFO as in UV2.UV2.

UV2: MODIFY DEPT_INFOUV2: MODIFY DEPT_INFO SET TOTAL_SAL=100000SET TOTAL_SAL=100000 WHERE DNAME=‘Research’;WHERE DNAME=‘Research’;

Page 171: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

171171

In general, we cannot guarantee that any view can be In general, we cannot guarantee that any view can be updated.updated.

A view update is unambiguous only of one update on A view update is unambiguous only of one update on the base relations can accomplish the desired update the base relations can accomplish the desired update effect on the view.effect on the view.

If a view update can be mapped to more than on If a view update can be mapped to more than on update on the underlying base relations, we must update on the underlying base relations, we must have a certain procedure to choose the desired have a certain procedure to choose the desired update.update.

We can make the following general observations:We can make the following general observations:– A view with a single defining table is updatable if the view A view with a single defining table is updatable if the view

attributes contain the primary key.attributes contain the primary key.– Views defined on multiple tables using joins are generally Views defined on multiple tables using joins are generally

not updatable.not updatable.– Views defined with aggregate functions are not updatable.Views defined with aggregate functions are not updatable.

Page 172: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

172172

5 5 Creating Indexes in SQLCreating Indexes in SQL

An SQL base relation generally corresponds to a An SQL base relation generally corresponds to a stored file.stored file.

SQL has statements to create and drop indexes on SQL has statements to create and drop indexes on base relations.base relations.

One or more One or more indexing attributesindexing attributes are specified for are specified for each index.each index.

The CREATE INDEX command is used to specify an The CREATE INDEX command is used to specify an index.index.

Each index is given an Each index is given an index nameindex name..

ExampleExample::I1: CREATE INDX LNAME_INDEX ON EMPLOYEE (LNAME);I1: CREATE INDX LNAME_INDEX ON EMPLOYEE (LNAME);

Page 173: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

173173

The index entries are in ascending (ASC) order of the The index entries are in ascending (ASC) order of the indexing attributes; for descending order, the keyword indexing attributes; for descending order, the keyword DESC is added.DESC is added.

An index can be created on a combination of attributes.An index can be created on a combination of attributes.

Example:Example:

I2: CREATE INDEX NAMES_INDEXI2: CREATE INDEX NAMES_INDEX ON EMPLOYEE (LNAME ASC, FNAME DESC, MINIT);ON EMPLOYEE (LNAME ASC, FNAME DESC, MINIT);

Two options on indexes in SQL are UNIQUE and Two options on indexes in SQL are UNIQUE and CLUSTER.CLUSTER.

To specify the To specify the key constraintkey constraint on the indexing attribute or on the indexing attribute or combination of attributes, the keyword UNIQUE is used.combination of attributes, the keyword UNIQUE is used.

Page 174: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

174174

ExampleExample::

I3: CREATE UNIQUE INDEX SSN_INDEX ON EMPLOYEE (SSN);I3: CREATE UNIQUE INDEX SSN_INDEX ON EMPLOYEE (SSN);

This is best done before any tuples are inserted in This is best done before any tuples are inserted in the relation.the relation.

An attempt to create a unique index on an existing An attempt to create a unique index on an existing base table will fail if the current tuples in the table do base table will fail if the current tuples in the table do not obey the constraint.not obey the constraint.

Page 175: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

175175

A second option on index creation is to specify that A second option on index creation is to specify that the index is a clustering index using the keyword the index is a clustering index using the keyword CLUSTER.CLUSTER.

A base relation can have at most one clustering index, A base relation can have at most one clustering index, but any number of non-clustering indexes.but any number of non-clustering indexes.

ExampleExample::

I4: CREATE INDEX DNO_INDEXI4: CREATE INDEX DNO_INDEX ON EMPLOYEE (DNO)ON EMPLOYEE (DNO) CLUSTER;CLUSTER;

Page 176: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

176176

A A clustering and uniqueclustering and unique index in SQL is similar to the index in SQL is similar to the primary indexprimary index of Chapter 5. of Chapter 5.

A A clustering but non-uniqueclustering but non-unique index in SQL is similar to index in SQL is similar to the the clustering indexclustering index of Chapter 5. of Chapter 5.

A A non-clustering indexnon-clustering index is similar to the is similar to the secondary secondary indexindex of Chapter 5. of Chapter 5.

Each DBMS will have its own index implementation Each DBMS will have its own index implementation technique; in most cases, some variation of the B+-technique; in most cases, some variation of the B+-tree data structure is used.tree data structure is used.

To drop an index, we issue the DROP INDEX To drop an index, we issue the DROP INDEX command.command.

The index name is needed to refer to the index when The index name is needed to refer to the index when it is to be dropped.it is to be dropped.

Example:Example:

I5: DROP INDEX DNO_INDEX;I5: DROP INDEX DNO_INDEX;

Page 177: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

177177

6 6 Embedding SQL in a Programming LanguageEmbedding SQL in a Programming Language

SQL can also be used in conjunction with a general SQL can also be used in conjunction with a general purpose programming language, such as PASCAL, purpose programming language, such as PASCAL, COBOL, or PL/I.COBOL, or PL/I.

The programming language is called the The programming language is called the host language.host language. The embedded SQL statement is distinguished from The embedded SQL statement is distinguished from

programming language statements by prefixing it with a programming language statements by prefixing it with a special character or command so that a special character or command so that a preprocessorpreprocessor can extract the SQL statements.can extract the SQL statements.

In PL/I the keywords EXEC SQL precede any SQL In PL/I the keywords EXEC SQL precede any SQL statement.statement.

In some implementations, SQL statements are passed In some implementations, SQL statements are passed as parameters in procedure calls.as parameters in procedure calls.

Page 178: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

178178

We will use PASCAL as the host programming We will use PASCAL as the host programming language, and a “$” sign to identify SQL statements language, and a “$” sign to identify SQL statements in the program.in the program.

Within an embedded SQL command, we may refer to Within an embedded SQL command, we may refer to program variables, which are prefixed by a “%” sign.program variables, which are prefixed by a “%” sign.

The programmer should declare program variables to The programmer should declare program variables to match the data types of the database attributes that match the data types of the database attributes that the program will process.the program will process.

These program variables may or may not have These program variables may or may not have names that are identical to their corresponding names that are identical to their corresponding attributes.attributes.

Page 179: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

179179

ExampleExample: Write a program segment (loop) that reads a : Write a program segment (loop) that reads a social security number and prints out some information social security number and prints out some information from the corresponding EMPLOYEE tuple.from the corresponding EMPLOYEE tuple.

E1: LOOP:=‘Y’;E1: LOOP:=‘Y’; while LOOP=‘Y’ dowhile LOOP=‘Y’ do

beginbeginwriteln(‘input social security number:’);writeln(‘input social security number:’);readln(SOC_SEC_NUM);readln(SOC_SEC_NUM);$SELECT FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS$SELECT FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS

SALARYSALARYINTO %E.FNAME, %E.MINIT, %E.LNAME, %E.SSN,INTO %E.FNAME, %E.MINIT, %E.LNAME, %E.SSN, %E.BDATE, %E.ADDRESS, %E.SALARY%E.BDATE, %E.ADDRESS, %E.SALARYFROM EMPLOYEEFROM EMPLOYEEWHERE SSN=%SOC_SEC_NUM;WHERE SSN=%SOC_SEC_NUM;writeln(E.FNAME, E.MINIT, E.LNAME, E.SSN, E.BDATE,writeln(E.FNAME, E.MINIT, E.LNAME, E.SSN, E.BDATE,

E.ADDRESS, E.SALARY);E.ADDRESS, E.SALARY);writeln(‘more social security numbers (Y or N)?’);writeln(‘more social security numbers (Y or N)?’);readln(LOOP)readln(LOOP)end;end;

Page 180: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

180180

In E1, a In E1, a single tuplesingle tuple is selected by the embedded is selected by the embedded SQL query; that is why we are able to assign its SQL query; that is why we are able to assign its attribute values directly to program variables.attribute values directly to program variables.

In general, an SQL query can retrieve many tuples.In general, an SQL query can retrieve many tuples. The concept of a cursor is used to allow tuple-at-a-The concept of a cursor is used to allow tuple-at-a-

time processing by the PASCAL program.time processing by the PASCAL program.

Page 181: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

181181

CURSORS:CURSORS:

We can think of a cursor as a pointer that points to a We can think of a cursor as a pointer that points to a single tuplesingle tuple (row) from the result of a query. (row) from the result of a query.

The cursor is declared when the SQL query The cursor is declared when the SQL query command is specified.command is specified.

A subsequent OPEN cursor command fetches the A subsequent OPEN cursor command fetches the query result and sets the cursor to a position query result and sets the cursor to a position before before the first rowthe first row in the result of the query; this becomes in the result of the query; this becomes the the current rowcurrent row for the cursor. for the cursor.

Subsequent FETCH commands in the program Subsequent FETCH commands in the program advance the cursor to the advance the cursor to the next rownext row and copy its and copy its attribute values into PASCAL program variables attribute values into PASCAL program variables specified in the FETCH command.specified in the FETCH command.

Page 182: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

182182

An implicit variable SQLCODE communicates to the program An implicit variable SQLCODE communicates to the program the status of SQL embedded commands.the status of SQL embedded commands.

An SQLCODE of 0 (zero) indicates successful execution.An SQLCODE of 0 (zero) indicates successful execution. Different codes are returned to indicate exceptions and errors.Different codes are returned to indicate exceptions and errors. A special END_OF_CURSOR code is used to terminate a A special END_OF_CURSOR code is used to terminate a

loop over the tuples in a query result.loop over the tuples in a query result. A CLOSE cursor command is issued to indicate that we are A CLOSE cursor command is issued to indicate that we are

done with the result of the query.done with the result of the query. When a cursor is defined for rows that are to be updated the When a cursor is defined for rows that are to be updated the

clause FOR UPDATE OF must be in the cursor declaration, clause FOR UPDATE OF must be in the cursor declaration, and a list of the names of any attributes that will be updated and a list of the names of any attributes that will be updated follows.follows.

The condition WHERE CURRENT OF cursor specifies that The condition WHERE CURRENT OF cursor specifies that the current tuple is the one to be updated (or deleted).the current tuple is the one to be updated (or deleted).

Page 183: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

183183

ExampleExample: Write a program segment that reads (inputs) a : Write a program segment that reads (inputs) a department name, then lists the names of employees department name, then lists the names of employees who work in that department, one at a time. The who work in that department, one at a time. The program reads a raise amount for each employee and program reads a raise amount for each employee and updates the employee’s salary by that amount.updates the employee’s salary by that amount.

E2:E2: writeln(‘enter the department name:’);writeln(‘enter the department name:’);readln(DNAME);readln(DNAME);$SELECT DNUMBER INTO %DNUMBER$SELECT DNUMBER INTO %DNUMBER FROM DEPARTMENTFROM DEPARTMENT WHERE DNAME=%DNAME;WHERE DNAME=%DNAME;$DECLARE EMP CURSOR FOR$DECLARE EMP CURSOR FOR

SELECT SSN, FNAME, MINIT, LNAME, SELECT SSN, FNAME, MINIT, LNAME, SALARYSALARY

FROM EMPLOYEEFROM EMPLOYEEWHERE DNO=%DNUMBERWHERE DNO=%DNUMBER

FOR UPDATE OF SALARY;FOR UPDATE OF SALARY;$OPEN EMP;$OPEN EMP;

Page 184: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

184184

$FETCH EMP INTO %E.SSN, %E.FNAME, %E.MINIT$FETCH EMP INTO %E.SSN, %E.FNAME, %E.MINIT %E.LNAME, %E.SAL;%E.LNAME, %E.SAL;

while SQLCODE = 0 dowhile SQLCODE = 0 do beginbegin writeln(‘employee name:’, E.FNAME, E.MINIT, writeln(‘employee name:’, E.FNAME, E.MINIT,

E.LNAME);E.LNAME); writeln(‘enter raise amount:’);writeln(‘enter raise amount:’); readln(RAISE);readln(RAISE); $UPDATE EMPLOYEE SET SALARY = SALARY + $UPDATE EMPLOYEE SET SALARY = SALARY +

%RAISE%RAISEWHERE CURRENT OF EMP;WHERE CURRENT OF EMP;

$FETCH EMP INTO %E.SSN, %E.FNAME, %E.MINIT,$FETCH EMP INTO %E.SSN, %E.FNAME, %E.MINIT,%E.LNAME, %E.SAL;%E.LNAME, %E.SAL;

end;end;$CLOSE CURSOR EMP;$CLOSE CURSOR EMP;

Page 185: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

185185

7 7 Recent Advances in SQLRecent Advances in SQL

Some SQL systems allow the specification of keys Some SQL systems allow the specification of keys and referential integrity constraints (foreign keys).and referential integrity constraints (foreign keys).

To allow a relation to have multiple keys, the keys To allow a relation to have multiple keys, the keys can be numbered 0 (for primary key), and 1, 2, 3,… can be numbered 0 (for primary key), and 1, 2, 3,… (for other keys).(for other keys).

The keyword KEY followed by one or more key The keyword KEY followed by one or more key numbers specifies that an attribute is a member of numbers specifies that an attribute is a member of the specified keys.the specified keys.

The keyword REFERENCES <relation>.<attribute> The keyword REFERENCES <relation>.<attribute> specifies that an attribute is a foreign key referencing specifies that an attribute is a foreign key referencing <attribute> of <relation>.<attribute> of <relation>.

Page 186: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

186186

ExampleExample::

CREATE TALBE EMPLOYEE(FNAME VARCHAR(15) KEYMEMBER 1 NOT NULL,MINIT CHAR(1) KEYMEMBER 1,LNAME VARCHAR(15) KEYMEMBER 1 NOT NULL

SSN CHAR(9) KEYMEMBER 0 NOT NULLBDATE CHAR(9),ADDRESS VARCHAR(30),

SEX CHAR(1),SALARY INTEGER,SUPERSSN CHAR(9) REFERENCES EMPLOYEE.SSN,

DNO INTEGER REFERENCES DEPARTMENT.DNUMBER);

CREATE TABLE DEPARTMENT

(DNAME VARCHAR(10) KEYMEMBER 1 NOT NULLDNUMBER INTEGER KEYMEMBER 0 NOT NULLMGRSSN CHAR(9) REFERENCES EMPLOYEE.SSN

MGRSTARTDATE CHAR(90);

Page 187: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

187187

SPECIFYING OUTER JOINS:SPECIFYING OUTER JOINS:

Some SQL systems include the OUTER JOIN Some SQL systems include the OUTER JOIN operation.operation.

The equality comparison operator = is modified to other The equality comparison operator = is modified to other symbols (+=, =+, +=+) to specify the various outer symbols (+=, =+, +=+) to specify the various outer joins.joins.

REGULAR JOIN CONDITIONREGULAR JOIN CONDITION::EMPLOYEE.DNO = DEPARTMENT.DNUMBEREMPLOYEE.DNO = DEPARTMENT.DNUMBER

This retrieves only those EMPLOYEE tuples related to This retrieves only those EMPLOYEE tuples related to a DEPARTMENT tuple, and only those DEPARTMENT a DEPARTMENT tuple, and only those DEPARTMENT tuples related to at least one EMPLOYEE tuple.tuples related to at least one EMPLOYEE tuple.

Page 188: Prepared by: Deepak Gour Lecturer-IT, SCT 1 INTRODUCTION TO DATABASE Prepared by Deepak Gour Lecturer-IT Salalah College of Technology.

Prepared by: Deepak Gour Lecturer-IPrepared by: Deepak Gour Lecturer-IT, SCTT, SCT

188188

LEFT OUTER JOINLEFT OUTER JOIN::EMPLOYEE.DNO += DEPARTMENT.DNUMBEREMPLOYEE.DNO += DEPARTMENT.DNUMBER

All EMPLOYEE tuples are retrieved; those not related All EMPLOYEE tuples are retrieved; those not related to a DEPARTMENT tuple are padded with NULLs.to a DEPARTMENT tuple are padded with NULLs.

LEFT OUTER JOINLEFT OUTER JOIN::EMPLOYEE.DNO =+ DEPARTMENT.DNUMBEREMPLOYEE.DNO =+ DEPARTMENT.DNUMBER

All DEPARTMENT tuples are retrieved; those not All DEPARTMENT tuples are retrieved; those not related to any EMPLOYEE tuple are padded with related to any EMPLOYEE tuple are padded with NULLs.NULLs.

LEFT OUTER JOINLEFT OUTER JOIN::

EMPLOYEE.DNO +=+ DEPARTMENT.DNUMBEREMPLOYEE.DNO +=+ DEPARTMENT.DNUMBER

All EMPLOYEE or DEPARTMENT tuples are All EMPLOYEE or DEPARTMENT tuples are retrieved.retrieved.