Top Banner
Introduction to RDBMS & SQL Course Map IDCGRF002 CourseMap.doc Copyright © 2009 Accenture All Rights Reserved WEEK 1 Day 1 Day 2 Day 3 9:00 - 9:15 M1: Introduction 1.1 School Opening (1:00) Morning Review Morning Review 9:15 - 9:30 M6: Data Definition Language (1:00) Activity 3(0:45) M8: Constraints (0:15) Activity 5 (0:45) 9:30 - 9:45 9:45 - 10:00 10:00 - 10:15 M2 : Introduction to RDBMS (1:00) 10:15 - 10:30 M9: Aggregate Functions, Joins and Sub queries (2:30) Activity (0:15) 10:30 - 10:45 10:45 - 11:00 11:00 - 11:15 M3 : The E-R Model of the Database ( 1:45) Activity (0:15) M7 : Data Manipulation Language (2:00) 11:15 - 11:30 11:30 - 11:45 11:45 - 12:00 12:00 - 12:15 12:15 - 12:30 12:30 - 12:45 12:45 - 1:00 1:00 -2:00 LUNCH LUNCH LUNCH 2:00 - 2:15 Knowledge Check 1 & 2 M7 : Data Manipulation Language (continued) Activity 4 (2:30) M9: Aggregate Functions, Joins and Sub queries (continued) Activity (2:15) 2:15 - 2:30 2:30 - 2:45 M4 : Database Design Techniques (0:45) Activity 2 (0:15) 2:45 - 3:00 3:00 - 3:15 3:15 - 3:30 3:30 - 3:45 M5: Introduction to SQL (1:00) 3:45 - 4:00 4:00 - 4:15 4:15 - 4:30 4:30 - 4:45 Knowledge Check 3 & 4 Knowledge Check 5 & 6 M10: Views (0:45) 4:45 - 5:00 5:00 - 5:15 Team Buliding Activity M8: Constraints (0:45) 5:15 - 5:30 Knowledge Check 7, 8 & 9 5:30 - 5:45 5:45 - 6:00 Day 1 Summary Day 2 Summary Day 3 Summary
182
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to RDBMS Participant Guide

Introduction to RDBMS & SQL Course Map

IDCGRF002 CourseMap.doc Copyright © 2009 Accenture All Rights Reserved

WEEK 1 Day 1 Day 2 Day 3 9:00 - 9:15

M1: Introduction 1.1 School Opening

(1:00)

Morning Review Morning Review 9:15 - 9:30

M6: Data Definition Language (1:00) Activity 3(0:45)

M8: Constraints (0:15) Activity 5 (0:45)

9:30 - 9:45 9:45 - 10:00

10:00 - 10:15

M2 : Introduction to RDBMS (1:00)

10:15 - 10:30

M9: Aggregate Functions, Joins and Sub queries (2:30)

Activity (0:15)

10:30 -10:45

10:45 - 11:00

11:00 - 11:15

M3 : The E-R Model of the Database ( 1:45) Activity

(0:15) M7 : Data Manipulation

Language (2:00)

11:15 - 11:30

11:30 - 11:45

11:45 - 12:00

12:00 - 12:15

12:15 - 12:30

12:30 - 12:45

12:45 - 1:00

1:00 -2:00 LUNCH LUNCH LUNCH 2:00 - 2:15 Knowledge Check 1 & 2

M7 : Data Manipulation Language (continued)

Activity 4 (2:30)

M9: Aggregate Functions, Joins and Sub queries (continued)

Activity (2:15)

2:15 - 2:30 2:30 - 2:45 M4 : Database Design

Techniques (0:45) Activity 2 (0:15)

2:45 - 3:00 3:00 - 3:15 3:15 - 3:30

3:30 - 3:45

M5: Introduction to SQL (1:00) 3:45 - 4:00 4:00 - 4:15 4:15 - 4:30 4:30 - 4:45 Knowledge Check 3 & 4 Knowledge Check 5 & 6 M10: Views (0:45) 4:45 - 5:00 5:00 - 5:15

Team Buliding Activity M8: Constraints (0:45) 5:15 - 5:30 Knowledge Check 7, 8 & 9 5:30 - 5:45 5:45 - 6:00 Day 1 Summary Day 2 Summary Day 3 Summary

Page 2: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Module 1: Course Overview

Introduction to RDBMSand SQL

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

• Welcome• Objectives

Agenda

• Introductions• Expectations of Participants• Ground Rules• Course Objectives• Course Approach and Outline

Copyright © 2009 Accenture All Rights Reserved. 2

1

Page 3: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Welcome to RDBMS Course

The purpose of this 3 day Course is to provide programmers with the tools necessary to understand database and write SQL queries

Welcome

tools necessary to understand database and write SQL queries.

This Course will cover the following topics:– Introduction to RDBMS– Introduction to SQL– Introduction to execute records using different Queries– Introduction to commonly used concepts in programming like– DDL

Copyright © 2009 Accenture All Rights Reserved. 3

DDL– DML– DCL etc.

At the end of this presentation, you should be able to:• Understand the expectations and ground rules

Objectives

• Understand the training approach and evaluation process.• Understand how to access the school resources, including:

the online book, online support, team members and faculty.

Copyright © 2009 Accenture All Rights Reserved. 4

2

Page 4: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

• Name• Your self assessment based on:

“Wh I’ h ”

Introductions

– “Why I’m here.”– “I am a programmer (using a different programming

language).”– “I am familiar with Programming concepts.”– “I know how to program using C.”– “I am a C Programmer and practice Best programming

T h i ”

Copyright © 2009 Accenture All Rights Reserved. 5

Techniques.”• One interesting note about yourself (e.g., a hobby or

talent)• Your expectations from the course

• You will work as a team to complete the deliverables of the course.You should be resourceful and creative Utilize the tools

Expectations of participants

• You should be resourceful and creative. Utilize the tools and materials that have been provided.

• Participate in discussions, ask questions to clarify if necessary.

Copyright © 2009 Accenture All Rights Reserved. 6

3

Page 5: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Participants who have completed this school, will be able to:• List the types of data used in a Oracle database and

Course Objectives

ypexplain about E-R model of the Database.

• Describe database design techniques and its features• List the advantages of working on a database in

application development• Describe the different types of SQL commands

Explain Data Definition Language Data Manipulation

Copyright © 2009 Accenture All Rights Reserved. 7

• Explain Data Definition Language, Data Manipulation Language

• Describe the database constraints• Describe Aggregate functions, joins and sub queries,

Views

Learn by Doing• Hands-on programming

Course Approach

Activity-based Learning• Activities are designed to be difficult but doable• Activities have time limits to encourage wise use of your time• Activities will force you to research on the required knowledge

Resource-rich EnvironmentU il bl (i li / ffli t i l h

Copyright © 2009 Accenture All Rights Reserved. 8

• Use available resources (i.e., online/offline materials, human resources, etc…)

• Encourage research and learning on your own

4

Page 6: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Teaching Method• This is not a lecture course! • Lessons serve only as guideposts and reminders and are not

Course Approach (Cont.)

• Lessons serve only as guideposts and reminders, and are not expected to be complete classes on these topics

• Instructors serve mainly as facilitators and knowledge coaches

Performance Evaluation• Each participant will be evaluated

P ti i t

Copyright © 2009 Accenture All Rights Reserved. 9

Participate• Don’t just listen to discussions, interact!• If in doubt, ask questions to clarify.• Spot problems and suggest alternatives or workarounds.

Teamwork• Cooperate, coordinate, collaborate!

Course Approach (Cont.)

• Work together to complete the deliverables for the course.

Be resourceful • Don’t ask for answers or solutions, find them!• The course environment provides all the necessary tools

d t i l t l tili th ll

Copyright © 2009 Accenture All Rights Reserved. 10

and materials to learn, utilize them well.

5

Page 7: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

• One of the tenets of the school is that the best way to learn is to take a more active, ‘hands-on’ approach.

Course Approach - Learn By Doing

learn is to take a more active, hands on approach.

• The majority of the activities consist of participants working to complete the appropriate deliverables.

• The faculty will act as knowledge coaches and technical

Copyright © 2009 Accenture All Rights Reserved. 11

consultants.

• This course encourages participants to be resourceful and inquisitive.

Level 1 – You– Try to resolve the problem on your own.

Course Approach - Tiers of Support

– Read documentation, try sample codes, surf the web…Level 2 – Teammates

– Try to resolve the problem with your teammates.– Consult entire team, investigate, work together to solve the

problem.Level 3 – Other Teams

Copyright © 2009 Accenture All Rights Reserved. 12

Level 3 Other Teams– Try to resolve problem with other teams. – Share tips, guides, resolutions, workarounds…

Level 4 – Faculty– Try to resolve problem with your faculty members.

6

Page 8: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Course MapDay 1 Day 2 Day 3

Course Introduction

Module 1: School Opening

M6: Data Definition Language

M7:Constraints

M9: Aggregate Functions, Joins and Subqueries

Module 1: School Opening

Module 2: Introduction to RDBMS

Module 3: Database Design Techniques

M7:Constraints

Lunch Lunch Lunch

Module 4:The E-R Model of the Database M7: Constraints (cont) M9: Aggregate Functions, Joins and

Copyright © 2009 Accenture All Rights Reserved. 13

Module 5: Introduction to SQLM8: Data Manipulation Language

Sub queries (cont)

Module 10: Views

Ground Rules• Observe proper professional behavior at all times.

– Core hours are from 9:00 a.m. to 6:00 p.m. Inform your supervisors when you will be late or absent.

– Set phones (or beepers) to silent/vibrate mode or turn them off.

– The Accenture Code of Ethics is enforced at all times.

• Observe proper use of Accenture resources and facilities.– No unauthorized software (especially games) installed on

workstations

Copyright © 2009 Accenture All Rights Reserved. 14

workstations.– Landline is strictly for business purposes or emergency calls

only.– Turn off your machines when you leave for the day. – Downloading of non-training related materials is strictly

prohibited.

7

Page 9: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

– No unauthorized software especially games should be installed in workstations

Ground Rules (Cont.)

– Landline is strictly for business purposes or emergency calls only

– Observe proper dress code

– Proper use of Accenture resources and facilities (e.g.

Copyright © 2009 Accenture All Rights Reserved. 15

Proper use of Accenture resources and facilities (e.g. desktops, training room, pantry)

– Maintain confidentiality of company and client-related matters

• Be aware there will be Knowledge Checks (quizzes) to test your understanding of the information presented.

Training Resources

y g p

• You may use the Internet, as long as you use it responsibly to access or research Programming technique related resources.

• We recommend self study.

Copyright © 2009 Accenture All Rights Reserved. 16

• Get to know your fellow students and the resources they offer. Tell your fellow students about your strengths and the resources you bring.

8

Page 10: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 1_Course Overview.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 17

9

Page 11: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMSand SQLModule 2: Introduction to RDBMS

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGF002

Agenda• Data and Storage.• Drawbacks with File Systems.• Introduction to DBMS and its

benefits.• Multi-tier Architecture• Data Models

– Hierarchical Model.

© Accenture 2009 All Rights Reserved 2

– Network Model.– Relational Data Model.

• Relational Data Model concepts.• Codd’s 12 rules.

10

Page 12: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Learning Objectives

• Understand the purpose of storing data.• Understand drawbacks of file systems• Understand drawbacks of file systems.• Understand the meaning of Database.• Compare Databases with traditional methods.• Understand the Multi-Tier Architecture.• Understand Data Models.

© Accenture 2009 All Rights Reserved 3

• Understand Codd’s Rules.

Data and its storage• We require reliable data to work with and hence it becomes

essential to store the data.• We often have to store the data as it is crucial in business

decisions.• There are 2 ways to store data in computer:

– Traditional Approach (File Systems).– Database Management Systems (DBMS).

• A File System is described by a very simple data storage

© Accenture 2009 All Rights Reserved 4

A File System is described by a very simple data storage model – In this, all the information is stored in a plain text file, one record

per line.– Each record is divided into fields using delimiters or are

delimited using fixed column positions.

11

Page 13: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Drawbacks with File SystemsDrawbacks Description

Data Dependency

Data dependency means that the application program is dependant on the data So any modifications made on the data affects the application programDependency data. So any modifications made on the data affects the application program using it, forcing it to be rewritten.

Redundancy Redundancy is the repetition of data. Data duplication was allowed in the traditional approach. Data redundancy caused data inconsistency to occur in the data.

Sharing Data Sharing was difficult or impossible with traditional systems.

Security Data stored on the computer must be secured.

© Accenture 2009 All Rights Reserved 5

It was difficult to enforce independent information security in traditional approach.

Transaction Control

Transaction is unit of work.If one is performing some work ( for e.g. inserting some records) other persons should not be able to use that particular data.There was no way to isolate independent units of work in traditional approach.

Introduction to DBMS

• DBMS is Data Base Management System.• It is a program that lets one or more computerIt is a program that lets one or more computer

users create and access data in a database. • It allows data definition, storage, and management

of data in the centralized pool that can be shared by many users.

© Accenture 2009 All Rights Reserved 6

12

Page 14: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

Data ConcurrencyDatabases allow multiple users to access the same database simultaneously.Data RedundancyA properly set-up database minimizes data redundancy. It will avoid data repetition in the databases.

Data ValidityDatabases allow you to set up rules that ensure that data remains consistent when add or

dif d tmodify data. Data SharingSharing data is also much easier using a database. You can share data among a number of users on the same computer or among users on different computers linked via a network or the Internet. Databases also allow more than one person to access the database at the same time and change the data stored; the database management system handles simultaneous changes.

Data SecurityOne final advantage of databases is security. Most database management systems allow you to create users in order to indicate various levels of security. Before someone accesses the database, he or she must log on as a specific user. Each user has various rights and limits. Someone who maintains the database has full ability to edit data, modify the database’s structure, add and delete users, and so on. Other users may only have the ability to view data but not change it, or you may even want to limit what data they can view. Many database management systems provide a granular level of security, that is, they are very

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

specific as to what a user can do.

13

Page 15: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

This diagram shows how application programs interact with the DBMS. DBMS actually is a repository of data which provide information to the application programs as well as storing information from the application programs.This is a typical example of a client-server system, where different application programs will access the DBMS via network. All the applications will access only one database. The DBMS is physically stored as Files in the Hard Disk of the system.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

14

Page 16: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

15

Page 17: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

Two tier architectureTwo tier architectures consist of three components distributed in two layers: client (requester of services) and server (provider of services). The three components are User System Interface (such as session, text input, dialog, and display management services) Processing Management (such as process development processProcessing Management (such as process development, process enactment, process monitoring, and process resource services) Database Management (such as data and file services) The two tier design allocates the user system interface exclusively to the client. It places database management on the server and splits the processing management between client and server, creating two layers. In general the user system interface client invokes services from theIn general, the user system interface client invokes services from the database management server. In many two tier designs, most of the application portion of processing is in the client environment. The database management server usually provides the portion of the processing related to accessing data (often implemented in store procedures). Clients commonly communicate with the server through SQL statements or a call-level interface. It should be noted that

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

connectivity between tiers can be dynamically changed depending upon the user's request for data and services.

16

Page 18: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

Hierarchical Model : This data model explicitly makes use of the hierarchies by providing a tree by which all data are accessible. The network model allows each record to have multiple parent and child records, forming a lattice structure. Relational Model : Each table represents some real-world person, place, thing, or event about which information is collected. A relational database is a collection of two-dimensional tables. The relational database is built around the Relational Model designed by E. F. Codd at IBM in 1970. We will explore Relational Model in detail in the coming slides.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

17

Page 19: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

In practice, many database products (for e.g. Oracle, Sybase etc..) are considered 'relational' even if they do not strictly adhere to all 12 rules.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

18

Page 20: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Network Data Model

© Accenture 2009 All Rights Reserved 13

Relational Data Model• It is based on Relational algebra i. e. mathematical theory of

relations.• It was first described by E.F. Codd in 1970 and then modified

b IBMby IBM.• It presents data in form of tables.• Rules of Relational Data Model

– It defines tables which contains Rows and Columns.– It presents a set of rules to ensure the integrity of the

database.– In Relational model a table is also a relation.

© Accenture 2009 All Rights Reserved 14

In Relational model a table is also a relation.– Row is known as a tuple. – Column is known as an attribute.

• Dr. Codd modified his model by defining 12 rules (Codd’s Rules), that a DBMS must meet in order to be considered a relational database.

19

Page 21: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Basic Terms and Definitions• The term 'database' has many interpretations - one

definition is that database is a 'collection of persistent data‘.

• A relational database is one in which the data consists of a 'collection of tables related to each other through common values‘.

• A relational database management system (RDBMS)uses matching values in multiple tables to relate the information in one table with the information in the other table.

© Accenture 2009 All Rights Reserved 15

• The presentation of data as tables is a logical construct - it is independent of the way the data is physically stored on disk.

Basic Terms and Definitions (Contd …)• The two most prominent characteristics of a relational

database are – Data stored in tables.Data stored in tables. – Relationships between tables.

• A table (entity or relation) is a collection of rows and columns.

• A row (record or tuple) represents a collection of information about a separate item (e.g., a customer).

• A column (field or attribute) represents the characteristics

© Accenture 2009 All Rights Reserved 16

co u ( e d o att bute) ep ese ts t e c a acte st csof an item (e.g., the customer's name or phone number).

• A relationship (join) is a logical link between two tables.

20

Page 22: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Codd’s 12 rules

Rule No. Rule Description

# 1 Information rule • Database must consist of tables related to each other and data should be stored in the form of tables only.

# 2 Guaranteed access Rule

• The data can be accessed by specifying the table name and the columns that define the primary key. Primary key ensures that each value is unique and accessible.

# 3 Systematic treatment of null values

• A Null is an unknown value and every database must have a provision for storing NULL values.

# 4 Dynamic on-line catalog based on the

l ti l d l

• In addition to user data, a relational database contains data about itself, there are 2 types of tables.

© Accenture 2009 All Rights Reserved 17

relational model • User tables - that contain the 'working' data and system tables contain data about the database structure.

• Metadata –that describes the structure of the database itself and includes object definitions (tables, indexes, stored procedures, etc.) and how they relate to each other.

• The collection of system tables is also referred to as the system catalog or data dictionary.

Codd’s 12 rules (Contd…)

Rule No. Rule Description

# 5 Comprehensive Data Sublanguage Rule

• There must be a single language that handles all communication with the database management system.

• The language must support relational operations with respect to: data modification, data definition and administration.

# 6 View Updating Rule • Database must allow for presenting data to the user in different combinations through views.

• Views are nothing but virtual tables which contains extraction of data from the source tables

© Accenture 2009 All Rights Reserved 18

data from the source tables.• Views allows to create customized snapshot of data to suit specific

needs. • If a view is a simple view then it can provide update and delete

operations on views.

21

Page 23: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Codd’s 12 rules (Contd…)

Rule No. Rule Description

# 7 Hi h l l i t R t t d t f d t i l ti ti# 7 High-level insert, update and delete

• Rows are treated as sets for data manipulation operations. • A relational database should support basic operations like sub-

queries, join, operators and set operations like union, intersection and minus.

• Set operations and relational operators are used to operate on 'relations' (tables) to produce other relations (tables).

# 8 Physical Data Independence

• Any changes in the data storage should not affect the application that accesses it.

© Accenture 2009 All Rights Reserved 19

# 9 Logical Data Independence

• Data is logically stored in tables and physically in files. For any change in the structure of tables and relationships, the application need not be re-created.

# 10 Integrity Independence

• In order to be considered relational, data integrity must be an internal function of the DBMS; not the application program.

• Data integrity means the consistency and accuracy of the data in the database (i.e., keeping the garbage out of the database).

22

Page 24: Introduction to RDBMS Participant Guide

2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL

0. Foundation RuleInterestingly Codd defined a Rule 0 for relational database systems."For any system that is advertised as, or claimed to be, a relational database management system, that system must be able to manage databases entirely through its relational capabilities, no matter what additional capabilities the system may support." (Codd, 1990)That means no matter what additional features a relational database mightThat means, no matter what additional features a relational database might support, in order to be truly called relational it must comply with the 12 rules. Codd added this rule in 1990. Also he expanded this 12 rules to 18 to include rules on catalogs, data types (domains), authorization and other. Codd himself had to admit the fact that based on the above rules there is no fully relational database system available. This has not changed since 1990. To be more specific rules 6, 9, 10, 11 and 12 seem to be difficult to satisfy.y

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

23

Page 25: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 2_IntroductionToRDBMS.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Key Points

• Databases are an efficient way to store large amounts of data.

• Relational Databases contain tables and fields.• It ensures that any data entered is valid and doesn’t

corrupt the database.• Databases are part of a larger software application

called a database management system (DBMS).

© Accenture 2009 All Rights Reserved 21

called a database management system (DBMS).• A database to be called as RDBMS, should adhere

to Codd’s Rules.

Questions and Comments

• What questions or comments do you

?have?

© Accenture 2009 All Rights Reserved 22

24

Page 26: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Module 3: Database Design Techniques

Introduction to RDBMS and SQL

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGF002

Agenda• Normalization.• Types of Normal forms.• First Normal Form.• Functional Dependency.• Full Functional Dependence and Partial

Functional Dependence.• Second Normal Form

Copyright © 2009 Accenture All Rights Reserved. 2

Second Normal Form.• Transitive Dependency.• Third Normal Form.• Denormalization.

25

Page 27: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Learning Objectives

• Understand Database design techniques.• Understand the need for normalization.U de sta d t e eed o o a at o• Understand different types of normalization.• Understand Functional dependencies.• Understand Denormalization.

Copyright © 2009 Accenture All Rights Reserved. 3

Normalization

• Normalization is the process of efficiently organizing data in a database.

• It is a design technique that is widely used as a guide in designing relational databases.

• Normalization is essentially a two step process

– It puts data into tabular form by removing repeating groups.

Copyright © 2009 Accenture All Rights Reserved. 4

– It removes duplicated data from the relational tables.• Normalization theory is based on the concepts of

normal forms.

26

Page 28: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Normal Forms

• A relational table is said to be in a normal form if it satisfies a certain set of constraints.

• They are special properties and constraints that a table schema should possess in order to achieve certain desired goals like minimizing redundancy of data.

• There are six normal forms that have been defined

First Normal Form (1NF) Second Normal Form (2NF)

Copyright © 2009 Accenture All Rights Reserved. 5

st o a o ( ) Seco d o a o ( )

Third Normal Form (3NF) Boyce Codd Normal Form (BCNF)Fourth Normal Form (4NF) Fifth Normal Form (5NF)

• The Third Normal Form is quite sufficient for most business database design purposes.

Example of Normalization

• Normalize the following Data

item_no item_desc price manufacturer_id

manufacturer_name

distributor_id

distributor_name order_id date_entered Qty

1 Watches 3000 M1001 Aqua Marine D1001Marine World

1001010011 12-May-07 20

Water 10011

Copyright © 2009 Accenture All Rights Reserved. 6

2 Pens 1000 M1002 Magnum D1002 World 10012 14-May-07 10

3 Mobiles 4000 M1003 Coral D1003Alpha Company

1001010012 16-May-07 15

27

Page 29: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

A design is in the first normal form if:There are no repeating groupsAll the key attributes are definedAll attributes are dependent on the primary key

A table is said to be in the 1NF when each cell of the table contains precisely one value.Consider the following project Table.ECODE DEPT Projecode HoursECODE DEPT Projecode Hours

E101 System p27 90p51 101p20 60

E305 Sales p27 109 p22 98

E508 Admin p51 nullp27 72

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

p27 72The data in the table is not normalized because cell in ProjCode and Hours has more than one value.

28

Page 30: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Content continued:

By applying the 1NF definition to the Project table, you arrive at the following table.

ECODE DEPT Projecode HoursE101 Systems p27 90E101 S t 51 101E101 Systems p51 101 E101 Systems p20 60E305 Sales p27 109E305 Sales p22 98E508 Admin p51 NullE508 Admin p27 72E508 Admin p27 72

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

29

Page 31: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

30

Page 32: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Consider the example:EmployeeID EmpName Loc-------------------------------------------------------------------------------------------------E100 Reshma MDCE101 Kshitij DDCE102 Asha PDCE103 Shivraj HDCE104 Neeta CDCE105 Naveen BDC

In the example, Employee Name has a functional dependency on Employee p , p y p y p yID, because a particular Employee ID value corresponds to one and only one Employee Name value. The reverse is not true because there could be several employees having the same name and hence one Employee name value could correspond to more than one Employee ID. Employee ID is therefore not functionally dependent on Employee Address.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

31

Page 33: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Content Continued:

Find the functional dependency between the attributes.

CourseCode CourseName Duration

------------------------------------------------------------------------------------------

C_101 Unix 16

C_102 Oracle –SQL 24

C_103 Oracle-PLSQL 32

C 104 C 24C_104 C 24

C_105 C++ 40

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

32

Page 34: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

33

Page 35: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

34

Page 36: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Let us take another example to understand Full functional dependence andPartial functional dependence. Suppose we have a transaction relation asshown here. For the Transaction relation, we may now say that:

Cname is fully functionally dependent on C#Ccity is fully functionally dependent on C#Cphone is fully functionally dependent on C#Qnt is fully functionally dependent on (C#, P#, Date – composite key)C i t f ll f ti ll d d t (C# P# D t ) it i lCname is not fully functionally dependent on (C#, P#, Date), it is only partially dependent on it (and similarly for Ccity and Cphone).

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

35

Page 37: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

A relation is in 2NF if and only if it is in 1NF and every non-key attribute is irreducibly dependent on the primary key

orA table to be in 2NF , the non key attributes must be fully functionally dependent on the Whole Key and not part of a Key.

The example discussed before is in first normal form To convert into SecondThe example discussed before is in first normal form. To convert into Second Normal form, apply functional dependency on the attributes of the table.

Two tables are created out of the above example.1st table – Items and 2nd table – Orders.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

36

Page 38: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Example :Let’s take an example in which a project manager manages a number of projects. Now the relation ‘Project’ has a candidate key ‘ProjectNum’. The ProjectNum field determines the values for all other fields – ProjectTitle, ProjectMgr and Phone. For a particular projectNum, there will always be a unique value in these other fields. So ProjectTitle, ProjectMgr and Phone are fully functionally dependent on ProjectNum.Now consider the attribute ‘Phone’. The phone number is dependent on the manager and manager is dependent on the project number. This is transitive dependency. Note that project manager is not a candidate key since the same manager manages more than one project.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

37

Page 39: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

Boyce-Codd normal form (BCNF) is a more rigorous version of the 3NF deal with relational tables that had

(a) multiple candidate keys(b) composite candidate keys and (c) candidate keys that overlapped .

Fourth Normal FormA relational table is in the fourth normal form (4NF) if it is in BCNF and all multivalued dependencies are also functional dependencies.

Fifth Normal FormA table is in the fifth normal form (5NF) if it cannot have a losslessA table is in the fifth normal form (5NF) if it cannot have a lossless decomposition into any number of smaller tables.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

38

Page 40: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

39

Page 41: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

40

Page 42: Introduction to RDBMS Participant Guide

3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL

In the example the relation Item, item_id is the primary key. The item_iddetermines the values for all the other fields – Item_Desc, Price,manufacturer_id, Distributor_id.Manufacturer name is dependent onmanufacturer_id which is not a candidate key.

The attribute manufacturer_name is dependent on the manufacturer_id andmanufacturer_id is dependent on the item_id. This is transitive dependency.The manufacturer_id is not a candidate key since the same manufacturercan supply many items.

Same is the case with Distributor_id and Distributor_name. The attributedistributor_name is dependent on the Distributor_id and Distributor_id isdependent on the item_id. This is transitive dependency. The Distributor_idyis not a candidate key since the same distributor can supply many items.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

41

Page 43: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

DENORMALIZATION• What is DENORMALIZATION?• Denormalization is a technique which is the opposite of normalization. In order

to speed up the database access, it suggests to move from higher level of normalization to lower normal forms of database modelingnormalization to lower normal forms of database modeling.

• NEED FOR DENORMALIZATION• Consider 2 tables –Orders and OrderItems which stores the order and items to

be ordered respectively. As per your analysis, you have created a view called Order_Item_View. This is one of the most heavily used views in the database. To read data from Order and the OrderItems table will require a join statement and access to many physical pages. To write data will require several update statements. Moreover 90 percent of Orders have no more than 5 positions. To avoid joins, you can merge the two tables into 1 table.

Copyright © 2009 Accenture All Rights Reserved. 21

avoid joins, you can merge the two tables into 1 table.• Data is normalized to avoid maximum redundancy. They are not optimized for

minimum access time. In the case of denormalization process, time does not play a role. The only reason why denormalization is done is to enhance the performance.

Denormalization (Contd…)

Copyright © 2009 Accenture All Rights Reserved. 22

42

Page 44: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

3: Database Design TechniquesActivity

• Input documents:– Activity_1.0_Module3_Datab

aseDesignTechniques.doc• Output document:

– Activity_1.0_Module3_DatabaseDesignTechniquesOutput.doc

Copyright © 2009 Accenture All Rights Reserved. 23

60 Minutes

3: Database Design TechniquesKey Points

• Normalization is the process of efficiently organizing data in a database.

• Normalization is designed to logically address potential problems with information stored in a database.

• There are six normal forms.

Copyright © 2009 Accenture All Rights Reserved. 24

• Typically a database will be in Third Normal Form.

43

Page 45: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 3_DatabaseDesignTechniques.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

3: Database Design TechniquesKey Points (Contd…)

• A design is said to be in first normal form(1NF) when there are no repeating groups and all attributes are dependent on the primary keyon the primary key.

• An entity type is in second normal form (2NF) if it is in 1NF and all its attributes are dependent on the primary key.

• A transitive dependency is a type of functional dependency in which the value in a non-key field is determined by the value in another non-key field and that fi ld i did k

Copyright © 2009 Accenture All Rights Reserved. 25

field is not a candidate key.

3: Database Design TechniquesQuestions and Comments

• What questions or comments

?do you have?

Copyright © 2009 Accenture All Rights Reserved. 2626

44

Page 46: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQLModule 4: ER Model of Database

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGF002

Agenda• Introduction to Entity Relationship (ER) Model.• Entity Relationship Diagram (ERD).• Entities Attributes and Relationships• Entities, Attributes and Relationships.• Mapping cardinalities

– One to one.– One to many.– Many to one.– Many to many.

• Keys

Copyright © 2009 Accenture All Rights Reserved. 2

– Primary Key.– Candidate Keys.– Alternate Key.– Foreign Key.– Composite key.

45

Page 47: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Learning Objectives

• Understand the Entity-Relationship (ER) model• Understand Entity Relationship diagramUnderstand Entity Relationship diagram• Understand Entities, Attributes and Relationships• Understand different types of cardinalities• Creating Entity Relationship Diagram• Understand Different types of Keys

Copyright © 2009 Accenture All Rights Reserved. 3

E-R Model• E-R model means Entity –Relationship Model.• It describes basic objects called entities as understood in j

real world and relationships among the objects

• It is a way of graphically representing the logical relationships of entities (or objects) in order to create a database

• E-R model helps to develop the logical database design of

Copyright © 2009 Accenture All Rights Reserved. 4

the System

• E-R model facilitates easy design of the database to represent the logical structure of the database

46

Page 48: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Based on the perception of the real world, an E-R diagram is prepared as shown below

Entity Relationship Diagram (ERD)

Real world ERD Definition Symbol

Object Entity An entity is an any object or activity which an enterprise records.

Property Attribute Instantiated from an object

Copyright © 2009 Accenture All Rights Reserved. 5

Property Attribute Instantiated from an object.

Relationship Relationship Association between two dependent objects.

Entity

• An Entity is an object in the real world about which we want or need to maintain information.

Persons: - information stored about people.Ex: Customers, Employees, Authors,Things Companies Assets

Examples:

Copyright © 2009 Accenture All Rights Reserved. 6

Employee

Things: Companies, Assets

47

Page 49: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Attributes

• Attributes are the significant properties or characteristics of an entity that help in describing y p gthe entity and provide the information needed to interact with it or use it.

First

Birth date

Age

Copyright © 2009 Accenture All Rights Reserved. 7

Middle

Last

Name Employee

SSN

Projects

Relationship

Relationships are the associations between entities. They can involve one or more entities and belong to particular relationship typesbelong to particular relationship types.

Dept DeptHeadAssigned

Copyright © 2009 Accenture All Rights Reserved. 8

Where Dept and DeptHead are Dependent Entity.Assigned is Relationship.

48

Page 50: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Mapping cardinalities • Cardinality is a quantity relationship between elements.• The number of rows in the table is called as cardinality.• Mapping cardinalities or cardinality ratio, expresses the

number of entities to which another entity can be associated via a relationship set.

• The following are the different mapping cardinalities– One to one.

Copyright © 2009 Accenture All Rights Reserved. 9

– One to many.– Many to one.– Many to Many.

One to one (1:1)• An entity in A is related to at most one entity in B, and an

entity in B is related to at most one entity in A. • Example 1:• Example 1:

EMPLOYEE WORKSTATION

Entity A Entity BRepresents 1

Copyright © 2009 Accenture All Rights Reserved. 10

Every Employee is assigned to One Workstation.

• Example 2:One Customer can hold one Salary Account in a bank.

Represents 1

49

Page 51: Introduction to RDBMS Participant Guide

4_ERModel.pptIntroduction to RDBMS and SQL

Few more examples of Schematic Relationship:Few more examples of Schematic Relationship:

• Each DEPARTMENT has many LECTURERS, one of whom is

. head of the DEPARTMENT;

• A LECTURER belongs to only one DEPARTMENT;

Each DEPARTMENT offers many different COURSES;• Each DEPARTMENT offers many different COURSES;

• Each COURSE is taught by a single LECTURER;

• A STUDENT may enroll for many COURSES offered by . . . . .

different DEPARTMENTS.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

50

Page 52: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Many to One (N : 1)• An entity in A is related to at most one entity in B, but an

entity in B is related to any number of entities in A. • Example 1:• Example 1:

State City

Entity A Entity B

Copyright © 2009 Accenture All Rights Reserved. 12

A city exists in only one state. However each state will have many cities.

• Example 2: Many Customers can hold different Accounts in one bank.

Many to Many (M:N)• An entity in A is related to any number of entities in B,

similarly an entity in B is related to any number of entities in A

• Example 1:

A Student can enroll for more than one course And each

STUDENT COURSE

Entity A Entity B

Copyright © 2009 Accenture All Rights Reserved. 13

A Student can enroll for more than one course. And each course will contain more than one student

• Example 2:Many products purchased by many customers

51

Page 53: Introduction to RDBMS Participant Guide

4_ERModel.pptIntroduction to RDBMS and SQL

Relationships of College DB :1:1 relationship

between LECTURER & DEPARTMENT;N:1 relationship

between LECTURER & DEPARTMENT

1:N relationship between DEPARTMENT & COURSE;;

M:N relationship between STUDENT & COURSE

1:N relationship between LECTURER & COURSE

1:1 relationship HEAD_OFbetween LECTURER & DEPARTMENT;between LECTURER & DEPARTMENT;

N:1 relationship IS_INbetween LECTURER & DEPARTMENT

1:N relationship OFFERSbetween DEPARTMENT & COURSE;

M:N relationship ENROLLSbetween STUDENT & COURSE

1 N l ti hi TEACHES

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

1:N relationship TEACHESbetween LECTURER & COURSE.

52

Page 54: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Keys

• Keys are used to validate the data that is being entered into a database

• Keys play a vital role in Maintaining data accuracy in a Database

• There are Four types of keys– Primary Key

Candidate Key

Copyright © 2009 Accenture All Rights Reserved. 15

– Candidate Key– Alternate Key– Composite key

Primary Key

• Primary key enforces integrity of the data by uniquely identifying records. A table can have only 1 primary keyy g y p y y

Emp No Name Designation

Primary Key

Copyright © 2009 Accenture All Rights Reserved. 16

1000 Venkat SSE

2000 Ramesh Team Leader

3000 Poornima ASE

53

Page 55: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Candidate key• Candidate key is a Key that helps to uniquely

identify row in a table• It could potentially serve as the primary Key.

Emp No WS# PrjName

4561 WS.A.1 Greenfield4562 WS.B.2 Am Express

4563 WS C 3 A d

Primary Key

The example shows the columns that either EmpNo or WS# can be identified as

Copyright © 2009 Accenture All Rights Reserved. 17

4563 WS.C.3 Avanande

Candidate Key (All rows are Unique)

candidates to become a primary key since choosing any one of them will make a row unique. In these cases we have to choose voluntarily one column as primary key.

Candidate Key (Contd...)• Overlapping candidate key: Two candidate keys overlap

if they involve two or more attributes each (composite candidate key) and have one or more attribute in common.

Emp No WS# PrjName

4561 WS.A.1 Greenfield

4562 WS.B.2 Am Express

4563 WS.C.3 Avanande

Copyright © 2009 Accenture All Rights Reserved. 18

4563 WS.C.3 Avanande

First Candidate Key Second Candidate Key

In this example you can choose EmpNo and WS# to unique identify the row or WS# and PrjName, in which the WS# is common.

54

Page 56: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Alternate Key

• Non-key attribute: Attribute that is not identified as a candidate key

• Alternate Key: Any of the candidate keys that is not the primary key is called an alternate key

Copyright © 2009 Accenture All Rights Reserved. 19

the primary key is called an alternate key

Foreign Key

• Foreign key :It provides relationship between table in the databasethe database

• In relational database, a foreign key of a table is a set of Column/Columns that references the primary key of another table

• The enforcement of this Constraint is Known as R f ti l I t it

Copyright © 2009 Accenture All Rights Reserved. 20

Referential Integrity

55

Page 57: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Composite Key

• A key composed of more then one column is called composite key or concatenated Keyp y y

EmpNo WS# Start date End date Hours single

4561 AS12 12/11/2005 12/3/2006 150

4562 AS13 12/11/2005 12/11/2005 8

Copyright © 2009 Accenture All Rights Reserved. 21

4563 AS14 13/11/2005 13/11/2005 8

Primary key is a combination of Emp No. and WS#

Activity• Input documents:

– Activity_2.0_Module4_ER Model.doc

• Output document:– Activity_2.0_Module4_ER

ModelOutput.doc

Copyright © 2009 Accenture All Rights Reserved. 22

60 Minutes

56

Page 58: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 4_ERModel.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Key Points

• E – R model is the building block of any database.• E – R Model is essential for any good database design.• Keys play a vital role in Maintaining data accuracy in a

Database• Primary key enforce entity integrity by uniquely

identifying entity instances.• Candidate key is a Key that uniquely identifies row in a

Copyright © 2009 Accenture All Rights Reserved. 23

y y q ytable.

• Key Composed more then one column is called composite key or concatenated Key

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 24

57

Page 59: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQLModule 5: Introduction to SQL

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Agenda• What is SQL.• The SQL sublanguages.• Data Definition Language.• Data Manipulation Language.• Data Control Language Transaction Control.

Copyright © 2009 Accenture All Rights Reserved. 2

58

Page 60: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Objectives• Understand SQL.• Understand the Sublanguages of SQL.• Understand basic SQL queries.

Copyright © 2009 Accenture All Rights Reserved. 3

Structured Query Language (SQL)• SQL is Structured Query Language.• It is a special-purpose, nonprocedural language that

t th d fi iti i l ti d t l fsupports the definition, manipulation, and control of data in relational database management systems.

• SQL is used to manipulate and retrieve data stored in a database.

• SQL is the most commonly used query language available.

Copyright © 2009 Accenture All Rights Reserved. 4

• SQL was designed by IBM during 1970’s.• Word SQL is derived from “Sequel”.

59

Page 61: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Structured Query Language (SQL) (Contd…)• Depending on the functionality SQL is classified as

follows:Data Definition Lang age (DDL)– Data Definition Language (DDL)

– Data modification Language (DML)– Data Control Language (DCL– Transaction Control Language (TCL)

Copyright © 2009 Accenture All Rights Reserved. 5

SQL is segregated into DDL,DML, DCL and TCL.D t t i l SELECT

Sub-languages of SQL

Data retrieval : SELECT

DDL DML DCL TCL

CREATE INSERT GRANT COMMIT

ALTER UPDATE REVOKE ROLLBACK

Copyright © 2009 Accenture All Rights Reserved. 6

DROP DELETE SAVEPOINT

TRUNCATE

60

Page 62: Introduction to RDBMS Participant Guide

5_IntroductionToSQL.pptIntroduction to RDBMS and SQL

Data Definition Language : It is a method of data definition and storage.The Data Definition Language is used to create object (e.g. Table), alter thestructure of an object and also to drop the object created.The conceptRelating to Data Definition Language are explained in paragraph.

DDL is a language used by a database management system which allows users todefine the database and its objects, specifying data types, structures andconstraints on the data

It allows the Specification like:•structure for each relation and integrity constraints•set of indices to be maintained for each relation (Indexes)•security and authorization information for each relation•The physical storage of each relation on disk•It is a language that enables users to access or manipulate data asorganized by the appropriate data model•DML Manipulation commands are the most frequently used SQL commands.•They are used to query and Manipulate existing objects like tables

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

•They are used to query and Manipulate existing objects like tables

61

Page 63: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Data Manipulation Language (DML)• It is a language that enables users to access or

manipulate data as organized by the appropriate data modelmodel.

• DML Manipulation commands are the most frequently used SQL commands..

• They are used to query and manipulate existing objects like tables.

Copyright © 2009 Accenture All Rights Reserved. 8

Data Control Language (DCL)• It is a language which provides users with privilege

commands. • DCL is the segment of SQL used for controlling

access to data in a database. • DCL allows protecting the tables and other objects

created by a user from accidental manipulation by another user.

• Granting privileges (insert select) to others allows

Copyright © 2009 Accenture All Rights Reserved. 9

• Granting privileges (insert, select) to others, allows them to perform operations within their scope.

• Privileges determines whether or not a particular user can perform a command.

• Using DCL we can control the privileges.

62

Page 64: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Transaction Control Language (TCL)• We can use SQL to control transactions.• Transactions:

– Collections of operations that form a single logical unit of work.

– It ensures that all changes made are either committed to the database or if there is a failure at any point of time then none of the changes are committed in the database

Copyright © 2009 Accenture All Rights Reserved. 10

committed in the database.– Transaction changes can be made permanent to a

database only if they are committed.– Transactions operations are executed between the

begin and end of the Transaction.

Key Points

• Define and understand Query Languages that are vital in extracting information from a database

• SQL is the most commonly used query language• SQL is a declarative programming language• SQL contains 3 sub languages

– DDL– DML

Copyright © 2009 Accenture All Rights Reserved. 11

– DCL• Transaction Control

63

Page 65: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 5_IntroductionToSQL.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 12

64

Page 66: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQLModule 6: Data Definition Language

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGF002

Learning Objectives

At the end of this presentation, you should be able to:

• Understand basic datatypes of SQL.• Understand how to create/alter and drop a user.• Understand basic user operations such as

creating and assigning privileges to a user.• Understand basic schema operations such as

© Accenture 2009 All Rights Reserved 2

• Understand basic schema operations such as creating, altering and deleting a table.

65

Page 67: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Agenda

• Understanding Data Types• Creating/Altering/Dropping a User• Creating/Altering/Dropping a User• Assigning and Revoking permissions on user• Creating a Table• Altering a Table• Truncate Table

© Accenture 2009 All Rights Reserved 3

• Dropping a Table

66

Page 68: Introduction to RDBMS Participant Guide

6_DataDefinitionLanguage.pptIntroduction to RDBMS and SQL

Oracle database makes use it own format to store date in fixed length of 7 bytes each of century, month, day, year, hour, minutes and second.

To view system date and time sysdate () can be used.

Using varchar2 saves disk space when compared to char.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

67

Page 69: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Data types

Data Type Description Max.Size

BLOB Bi L Obj t It t Bi 4 GBBLOB Binary Large Objects. It stores Binary Data like storing Images

4 GB

CLOB Character Large Object. It stores Character Data like large documents in any character set.

4 GB

BFILE Binary data stored in an external file outside of oracle database

4 GB

ROWID Is a 64 base number system ti th i dd f

-N/A – (as it is internally d b th l t )

© Accenture 2009 All Rights Reserved 5

representing the unique address of a row in its table.

managed by the oracle system).

Creating a new User• A new user can be created by the command-Create

user. The user can log in the oracle system just as you login using “scott”login using “scott”.

• Syntax to create the user:Create user <username>identified by <password>;

Note: To create a new user, you should have the DBA t i il Y l d thi b

© Accenture 2009 All Rights Reserved 6

or create user privilege. You can also do this by logging in as System or sys.

Ex: Create user sam identified by admin;

68

Page 70: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Altering the User• A user can change his own password.• Syntax :

alter user <username>identified by <newpassword>;

• Note: This can be done by the user or the DBA, incase the user forgets or loses his password.

• Example :

© Accenture 2009 All Rights Reserved 7

palter user sam

identified by admin;

Dropping a User

• The DBA can drop or remove the user from the oracle database.

• Syntax:

Drop user <username>;

• Example:

© Accenture 2009 All Rights Reserved 8

drop user sam;

• The user is dropped from the oracle database.

69

Page 71: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Assigning privileges to a user

• Once a user is created, the DBA has to assign privilege to the user depending on the type of access the user would require on the database.

• Syntax to grant privilege:

grant connect, resource to <username>;

© Accenture 2009 All Rights Reserved 9

• Note: Grant is a DCL command used to grant the privilege to a user.

Assigning privileges to a user – (Contd…)• Privileges:

– Connect - user is able to connect to the database.– Resource – user is able to create objects.

Eg: tables, views, procedures, index, functions etc.– Database Administrator – user gets the rights of the

super user or administrator with DBA privilege. He can do the task what a “System” or “Sys” user can do.

Example:

© Accenture 2009 All Rights Reserved 10

Example:

SQL>grant connect, resource to SAM;

70

Page 72: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Revoking the Privileges:

• A privilege can be revoked by using Revoke.• It is a DCL command.Syntax:

revoke <privilege> from <username>;

Example:

© Accenture 2009 All Rights Reserved 11

revoke resource from sam;

Note: to revoke the privilege the user should be a dba or have dba privilege.

6: Data Definition LanguageActivity (1 of 3)

• Work in groups of 4 or 5

• With your group, try to identify the role and responsibilities of a Database Administrator (DBA)

• Share your thoughts with the l

© Accenture 2009 All Rights Reserved 12

class

10 Minutes

71

Page 73: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Creating Table

Syntax CREATE TABLE table_name(

name of column column datatypename_of_column column_datatype,[name_of_column column_datatype,]

. . . . . . . . .)

CREATE TABLE dept infoE l

© Accenture 2009 All Rights Reserved 13

CREATE TABLE dept_info(

Deptno Number(2),Dname Varchar2(20),Loc Varchar2(20),

);

Example

6: Data Definition LanguageActivity (2 of 3)

• Input documents:– Activity_3.0_Module6_DataDefi

ti L dnationLanguage.doc• Output documents:

– Activity_3.0_Module6_DataDefinationLanguageOutput.doc

© Accenture 2009 All Rights Reserved 14

60 Minutes

72

Page 74: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Alter Table Statement

• Alter command is used to add, modify and drop columns

• It is used – To add constraints – To add a new column

ALTER TABLE table_nameADD name of field data type;Syntax:

© Accenture 2009 All Rights Reserved 15

ADD name_of_field data_type;

ALTER TABLE dept_infoADD state varchar2(2);Example:

y

Alter Table Statement

ALTER TABLE table_nameMODIFY name_of_field data_type;

Syntax to Modify

Column :

ALTER TABLE dept_infoMODIFY dname varchar2(25);Example:

Column :

ALTER TABLE table_name DROP COLUMN name of field;

Syntax to D l

© Accenture 2009 All Rights Reserved 16

DROP COLUMN name_of_field;Drop column

ALTER TABLE Train_timesDROP COLUMN state;

Example:

73

Page 75: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

6: Data Definition LanguageActivity (3 of 3)

• Input documents:– Activity_3.1_Module6_DataDefi

ti L dnationLanguage.doc• Output documents:

– Activity_3.1_Module6_DataDefinationLanguageOutput.doc

© Accenture 2009 All Rights Reserved 17

45 Minutes

Truncate table

• Truncate table is used to remove all data from a table, without disturbing the structure.

Syntax :Truncate table <table_name>;

Example:Truncate table dept_info;

© Accenture 2009 All Rights Reserved 18

• The truncate command deletes all rows from specified table

• By adding a ‘reuse storage’ clause to the same command the space that is used for the storage can be reclaimed

74

Page 76: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

To Remove Table

• DROP is used to remove a table.

DROP TABLE table_name

Syntax

Example:

© Accenture 2009 All Rights Reserved 19

DROP TABLE dept_info

6: Data Definition Language

• Question:– What is the difference

between truncate and the delete command?

© Accenture 2009 All Rights Reserved 20

75

Page 77: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

6: Data Definition LanguageKey Points

• Integer, long varchar2 are few of the data types used in SQL.

• To design the schema or modifying it we have to use datatypes.

• To create a Table use CREATE TABLE command.• Alter command is used to add, modify and drop

columns.

© Accenture 2009 All Rights Reserved 21

columns.• Truncate command is used for deleting the rows

from a specified table.• DROP is used to drop of a Table.

6: Data Definition LanguageKey Points (Contd…)

• A user can be created by the dba or by the user having dba privilege.

• To create the user use the create user command.• A user can modify the password by using the alter

command.• To assign the privilege use the grant command.• To revoke the privilege use the revoke command.

© Accenture 2009 All Rights Reserved 22

To revoke the privilege use the revoke command.

76

Page 78: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 6_DataDefinitionLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

© Accenture 2009 All Rights Reserved 23

77

Page 79: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQLModule 7: Constraints

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Objectives

At the end of this presentation, you should be able to:

• Understand the need of constraints• Understand different types of constraints• Understand how to add constraints in the schema

design• Understand how to remove constraints

Copyright © 2009 Accenture All Rights Reserved. 2

Understand how to remove constraints• Understand how to add default value to a column

78

Page 80: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Agenda

• Constraints• Primary Key Constraint• Foreign Key Constraint• UNIQUE constraint• CHECK constraint• NOT NULL Constraint

Defa lt

Copyright © 2009 Accenture All Rights Reserved. 3

• Default

Constraints

• Constraint is a rule or set of rules that are applied to a column or combination of columnsto a column or combination of columns.

• It help in preventing data corruption.• It help in preventing human errors while entering

data into the database.• Database constraints help to achieve data integrity

Copyright © 2009 Accenture All Rights Reserved. 4

without the need to write an external program.

79

Page 81: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Types of Constraints

• Different Types of Constraints are as below– Primary keyPrimary key– Foreign key– Check– Unique– Not null

Copyright © 2009 Accenture All Rights Reserved. 5

• Constraints can be created at the time of creating the table using CREATE TABLE or after creating the table using ALTER TABLE.

Primary Key Constraint• Primary key Constraints avoid the duplication of data.• A table can have only one primary key constraint but

can have several UNIQUE constraintscan have several UNIQUE constraints.• Example- Create the EMP_INFO table by adding a

primary key constraint PK_EMPNO on the column EMPNO.CREATE TABLE EMP_INFO (EMPNO NUMBER(4) CONSTRAINT PK_EMPNO PRIMARY KEY,ENAME VARCHAR2(20),DEPTNO NUMBER (2))

Copyright © 2009 Accenture All Rights Reserved. 6

The above example creates the EMP_INFO table by adding a primary key constraint PK_EMPNO on the column EMPNO.

80

Page 82: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Primary Key Constraint (Contd…)• Example- Create and modify the EMP_INFO1 table by

adding a primary key constraint PK_EMPNO1 on the column EMPNOcolumn EMPNO.

• Example CREATE TABLE EMP_INFO1 (EMPNO NUMBER(4), ENAME VARCHAR2(20), DEPTNO NUMBER (2))

ALTER TABLE EMP_INFO1 ADD CONSTRAINT PK EMPNO1 PRIMARY

• The example creates and modifies the EMP_INFO1 table by adding a primary key constraint PK_EMPNO1 on the column EMPNO

Copyright © 2009 Accenture All Rights Reserved. 7

CONSTRAINT PK_EMPNO1 PRIMARY KEY (EmpNo);

ALTER TABLE DEPT_INFO ADD CONSTRAINT PK_DEPTNO PRIMARY KEY (DEPTNO);

the column EMPNO.

• It also modifies the DEPT_INFO table with the primary key PK_DEPTNO on the deptno column.

Foreign Key Constraint• When a column in one table refers to the Primary Key of

another table, that column is referred as Foreign Key.• It is also known as Referential Integrity and implemented

CREATE TABLE EMP_INFO2(EMPNO NUMBER(4) CONSTRAINT PK_EMPNO2 PRIMARY KEY, ENAME VARCHAR2(20) DEPTNO

It is also known as Referential Integrity and implemented through Foreign Key constraint.

• Example- create a table EMP_INFO2 to add a foreign key constraint:

The example adds a foreign key constraint FK_DEPTNO1 to the

Copyright © 2009 Accenture All Rights Reserved. 8

ENAME VARCHAR2(20) , DEPTNO CONSTRAINT FK_DEPTNO1REFERENCES DEPT_INFO (DEPTNO))

EMP_INFO2 table on the deptno column which references DEPTNO -the primary key of the DEPT_INFO Table.

81

Page 83: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Foreign Key Constraint (Contd…)• Example- Modify the EMP_INFO1 table by adding a foreign

key constraint FK_DEPTNO1 on the column DEPTNO:

ALTER TABLE EMP_INFO1ADD CONSTRAINT FK_DEPTNO2FOREIGN KEY(DEPTNO) REFERENCES DEPT_INFO(DEPTNO);

Example :

Copyright © 2009 Accenture All Rights Reserved. 9

The above example adds a foreign key constraint FK_DEPTNO2 to the EMP_INFO1 table on the DEPTNO column which references the primary key of the DEPT_INFO Table.

Unique Constraint• Unique Key Constraints are used to enforce the

uniqueness of a column. • If a column has a Unique Constraint on it duplicate values• If a column has a Unique Constraint on it, duplicate values

cannot be inserted on that column.• Unique key allows Null value to be stored.• Example: Create a table emp_sal to add the unique

constraint.CREATE TABLE EMP_SAL(EMPNO NUMBER(4)

The example adds a unique key

Copyright © 2009 Accenture All Rights Reserved. 10

(EMPNO NUMBER(4),ENAME VARCHAR2(20),ACTNO NUMBER (8) CONSTRAINT UK_ACTNO UNIQUE,JOB VARCHAR2(20),HIREDATE DATE)

q yconstraint UK_ACTNO on the ACTNO columns of the EMP_SAL table.

82

Page 84: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Unique Constraint

• Example: Modify the table emp_sal to add the unique constraint.

ALTER TABLE EMP_SAL ADD CONSTRAINT UK_JOB_HDATE UNIQUE (job, hiredate);

Copyright © 2009 Accenture All Rights Reserved. 11

The above example adds a unique key constraint UK_JOB_HDATE on the job and hiredate columns of the EMP_SAL table.

CHECK constraint

• Check Constraints are the most elementary form of integrity constraints.

• Check constraint is also known as Domain Integrity.• This powerful feature allows to establish range for data.• Check Constraints are created by specifying a domain

(Range) for a column.• If we specify a domain constraint for a particular

Copyright © 2009 Accenture All Rights Reserved. 12

column, that column will contain only values specified in that domain.

83

Page 85: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Example – Check Constraint

• Example: Create a table emp_sal1 to add the unique constraint.

CREATE TABLE EMP_SAL1 (EMPNO NUMBER(4), ENAME VARCHAR2(20), ACTNO NUMBER(8),JOB VARCHAR2(20) CONSTRAINT CHK_JOB CHECK (job IN ('ANALYST','CLERK')), HIREDATE DATE)

The above example adds a check constraint CHK_JOB on the JOB column of the EMP_SAL1 table.

Copyright © 2009 Accenture All Rights Reserved. 13

ALTER TABLE EMP_SAL add CONSTRAINT CHK_JOB CHECK (job IN ('ANALYST', 'CLERK'))

The example adds a check constraint CHK_JOB on the job column of the EMP_SAL table.

NOT NULL Constraint• A NOT NULL constraint specifies that a column must not

assume the NULL value.• A NOT NULL constraint is always written as a column• A NOT NULL constraint is always written as a column

constraint.

CREATE TABLE PRODUCTS (PRODUCT_NO NUMBER(2) CONSTRAINT NN_PROFNO NOT NULL, NAME VARCHAR2(40) CONSTRAINT

Example :

Copyright © 2009 Accenture All Rights Reserved. 14

( )NN_PROD_NAME NOT NULL)

The above example creates a table called products with two columns product_no and name. Both have a constraint NOT NULL.

84

Page 86: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Removing Constraints

• A constraint can be removed as shown below

ALTER TABLE EMP_INFO DROP CONSTRAINT PK_EMPNO

Example :

The above example removes a constraint named PK EMPNO from EMP INFO table

Copyright © 2009 Accenture All Rights Reserved. 15

PK_EMPNO from EMP_INFO table.

Default• The default keyword is assigned to a column of a table at the

time of creating a table or altering it.• The value in the default keyword is applied when no value is y pp

inserted in the table using the INSERT statement.• Example: Create a table products1 to create default

CREATE TABLE PRODUCTS1 (PRODUCT_NO NUMBER(2) NOT NULL, NAME VARCHAR2(40) NOT NULL, STATE VARCHAR2(2) DEFAULT 'MH')INSERT INTO PRODUCTS1 (PRODUCT NO NAME)

Copyright © 2009 Accenture All Rights Reserved. 16

The above example adds a default value of ‘MH’ into the state field as no explicit value is provided while inserting.

INSERT INTO PRODUCTS1 (PRODUCT_NO,NAME)VALUES(1, 'PENS')

85

Page 87: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

7: ConstraintsActivity

• Input documents:– Activity_4.0_Module7_Constr

aints.doc• Output :

– Activity_4.0_Module7_ConstraintsOutput.doc

Copyright © 2009 Accenture All Rights Reserved. 17

45 Minutes

Key Points

• Constraint is a rule or set of rules that apply to a column or combination of columnsC• Constraints ensure data integrity

• Important constraints are– Primary Key– Foreign Key– CHECK

Copyright © 2009 Accenture All Rights Reserved. 18

CHECK– UNIQUE– NOT NULL

86

Page 88: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 7_Constraints.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 19

87

Page 89: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMSand SQL

Module 8: Data Manipulation Language

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Learning ObjectivesAt the end of this presentation, you should be able to:

• Insert new data into the table• Update existing data• Delete existing data• Retrieve data from the table using SELECT• Filter rows using WHERE clause• Sort the results retrieved from the table• Char Number and Date Functions

Copyright © 2009 Accenture All Rights Reserved. 22

• Char, Number and Date Functions• Handling NULL data using NVL• Understanding DECODE function• Understand the use of ESCAPE sequence and SPOOL

option

88

Page 90: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Module 8: Agenda• Inserting New Data• Updating Existing Data• Deleting Existing DataDeleting Existing Data• Retrieving data using SELECT

– Basic SELECT statement– Filtering rows using WHERE clause

• Operators and Operator Precedence• Introducing NULL Data• Using Aliases

Copyright © 2009 Accenture All Rights Reserved. 33

g• Sorting Information• TO_CHAR, TO_NUMBER, TO_DATE functions• NVL function• DECODE function• ESCAPE sequence and SPOOL option

89

Page 91: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

Table Structure for Dept table is given below:

DeptNo Number(2),DNAME VARCHAR2(25),Loc Varchar2(20),State varchar2(2);

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

90

Page 92: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

Sometimes changes to the database become imminent. For example DEPT table, to reflect such changes to the existing record in a DEPT table the update command is used. With the update command we can update rows in the Table. A single column may be updated or more than one column could be updated. Specific rows could be updated based on a specific condition.

UPDATE Dept SET state=‘MH’;UPDATE Dept SET state= MH ;

It will update all the state as ‘KANPUR’ from the dept table.

UPDATE Dept SET state=‘MH’WHERE DeptNo=1;

It will update the state as a MH where DEPTNO is 1It will update the state as a MH where DEPTNO is 1

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

91

Page 93: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

92

Page 94: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

One or More rows could be deleted using delete command. Alternatively, all rows of DEPT table could also be deleted while structure remains unaltered. To delete specific rows from a table the ‘where’ clause is used in combination with the delete command. To delete several rowsFrom a table, select the rows with appropriate condition in a ‘where’ clause . The ‘where’ clause can also include a query.The Delete command consists of a ‘From’ clause followed by an optional ‘where’The Delete command consists of a From clause followed by an optional whereclause.

Example 1:DELETE FROM DEPT;It Will delete all the rows from the DEPT table.

Example 2:DELETE FROM DEPT WHERE DEPTNO=1;It will delete all the rows from DEPT table where DEPTNO = 1.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

93

Page 95: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Deleting Existing Data (Contd…)

Syntax for deleting all the rows

DELETE FROM DEPT;

DELETE FROM <table_name>

Example:

Copyright © 2009 Accenture All Rights Reserved. 88

DELETE FROM DEPT;

8: Data Manipulation LanguageActivity (1 of 2)

• Input documents:– Activity_5.0_Module8_DataM

anipulationLanguage.doc– C:\RDBMS\Day2\createSche

ma.sql • Output :

– Execute the sql file ti d b

Copyright © 2009 Accenture All Rights Reserved. 99

mentioned above

15 Minutes

94

Page 96: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Retrieving Columns• SELECT statement is used to retrieve data from the table • It can be used to retrieve a column or multiple columns

E lfrom a table. Example: • To get the names of all the departments

SELECT DNAME FROM DEPT;

• List the names of the columns separated by a comma to retrieve multiple columns

Copyright © 2009 Accenture All Rights Reserved. 1010

SELECT DNAME, LOC FROM DEPT;

• * is used to retrieve all columns from the table SELECT * from DEPT;

Using ALL

• ALL is used with SELECT statement to retrieve all the dept names. The ALL keyword is optional.– Example: To retrieve all dept name from table DEPT

SELECT ALL DName from DEPT;

– By-default all the values will be retrieved from the

Copyright © 2009 Accenture All Rights Reserved. 1111

ycolumn though ALL is not specified

95

Page 97: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using DISTINCT

• DISTINCT keyword is used with SELECT statement to retrieve unique values from a column– Example : To retrieve unique location from the table DEPT

SELECT DISTINCT LOC FROM DEPT;

Copyright © 2009 Accenture All Rights Reserved. 1212

Filtering Rows• It is common to filter the results to get only the information required than

selecting all the records in a table.• We can use WHERE clause with SELECT statements to filter results to

SELECT COL1,COL2,.........FROM TABLE_NAME WHERE < SEARCH CONDITION>;

We can use WHERE clause with SELECT statements to filter results to get only the data which is required.

Syntax :

Example: SELECT EMPNO,ENAME,DEPTNO FROM EMP WHERE JOB=‘ANALYST’;

Copyright © 2009 Accenture All Rights Reserved. 1313

EMPNO ENAME SAL DEPTNO===================================7788 SCOTT 3000 207902 FORD 3000 20

Sample output

96

Page 98: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Operators in WHERE Clause

O t D i ti

• Operators can be used with WHERE clause

Operator Description<,>,<=,>=,=,<> or !=

It is used to compare values

IN It selects from a list of valuesBETWEEN Selects from a range of values

Copyright © 2009 Accenture All Rights Reserved. 1414

BETWEEN Selects from a range of valuesNULL Compares with Null valuesLIKE Compares with the pattern

Comparison Operators• Comparison operators are used to compare the values from

the left hand side of a relational operator with that on the right hand side

SELECT EMPNO,ENAME

right hand side• Relational Operators are: = , < , > , <= , >= , != or < >

Example: To retrieve all the EMPNO,ENAME columns which belong to the DEPTNO 10 :

Sample output

Copyright © 2009 Accenture All Rights Reserved. 1515

FROM EMPWHERE DEPTNO = 10;

• EMPNO ENAME=====================

7782 CLARK• 7839 KING• 7934 MILLER

97

Page 99: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using IN Operator

• The IN operator is generally used to retrieve values from a list of values called as inclusive list.I l i li t i li t hi h t i lti l l t b• Inclusive list is a list which contains multiple values to be retrieved for the same column.

• The IN operator checks the database to see if the specified column matches one or more of the values listed inside the list.Example : To get the list of Employees working as MANAGER and ANALYST:

Copyright © 2009 Accenture All Rights Reserved. 1616

SELECT EMPNO,ENAME FROM EMPWHERE JOB IN (‘MANAGER’ ,’ANALYST’);

MANAGER and ANALYST:EMPNO ENAME

================•7566 JONES7698 BLAKE7782 CLARK•7788 SCOTT7902 FORD

Sample Output

Using BETWEEN Operator• The BETWEEN operator allows to specify a range of values.• Where the range consists of lower range and a higher range.

It eliminates the use of > and < Relational operators• It eliminates the use of >= and <= Relational operators• BETWEEN operator can be modified using AND

Example: To get EMPNO,ENAME,JOB,SAL where salary is in the range 1000 to 2000 (inclusive) :

• EMPNO ENAME JOB SALSample output

Copyright © 2009 Accenture All Rights Reserved. 1717

SELECT EMPNO,ENAME,JOB,SAL FROM EMPWHERE SAL BETWEEN 1000 AND 2000;

====================================• 7499 ALLEN SALESMAN 1600• 7521 WARD SALESMAN 1250• 7654 MARTIN SALESMAN 1250• 7844 TURNER SALESMAN 1500• 7876 ADAMS CLERK 1100• 7934 MILLER CLERK 1300

98

Page 100: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using LIKE Operator• The LIKE operator allows you to use wildcard characters

when searching a character field.

• A wildcard character matches any one or more characters in a string.

• 2 Types of Wildcards– % : This wildcard matches multiple characters.

Copyright © 2009 Accenture All Rights Reserved. 1818

% : This wildcard matches multiple characters.– _ : This wildcard matches exactly one character.

Using LIKE Operator (Contd…)• Examples :

A% indicates matching data starting with A– A% indicates matching data starting with A and having any number of characters.

– %S indicates matching data ending with S and having any number of characters.

– A_R%S indicates matching data starting with A, having r as the third character ending with S.

– __S_A indicates matching data having S as the third character and A as the fifth character. This

Copyright © 2009 Accenture All Rights Reserved. 1919

data should be of 5 characters only.

99

Page 101: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using LIKE Operator (Contd…)

Example: To get details of employees whose

Example: To get details of employees whose name starts

ith J and the fo rth letter as E

SELECT EMPNO, ENAME, JOB,SAL FROM EMP WHERE ENAME LIKE ‘S%’;

SELECT EMPNO, ENAME, JOB,SAL FROM EMP WHERE ENAME LIKE ‘J__E%'

name begin with letter S : with J, and the fourth letter as E and the remaining can be anything.

Copyright © 2009 Accenture All Rights Reserved. 2020

•EMPNO ENAME JOB SAL=================================

• 7369 SMITH CLERK 800• 7788 SCOTT ANALYST 3000

•EMPNO ENAME JOB SAL====================================

•7566 JONES MANAGER 2975•7900 JAMES CLERK 950

Using Logical operators

• In WHERE statement AND and OR logical operators is used to test more than one condition

Operator DescriptionAND Both the condition on the left-hand side of the

operator and the condition on the right-hand side must evaluate to true

OR Either condition must evaluate to true. If the condition on the left hand side of the operator

Copyright © 2009 Accenture All Rights Reserved. 2121

condition on the left-hand side of the operator evaluates to true, the next condition is not evaluated.

NOT Negates the condition. It can be used with IN, BETWEEN and LIKE operator

100

Page 102: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using Logical operators (Contd…)Example: To get EMPNO, ENAME, JOB, SAL of all employees having salary more

Example: To get EMPNO, ENAME, JOB of all employees working as SALESMAN or those

SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL >2000 AND

e p oyees a g sa a y o ethan 2000 and working in DEPTNO 20.

o g as S S o oseemployees whose names start with A.SELECT EMPNO,ENAME, JOB FROM EMP WHEREJOB= 'SALESMAN'OR ENAME LIKE 'A%'

Copyright © 2009 Accenture All Rights Reserved. 2222

DEPTNO=20

EMPNO ENAME SAL DEPTNO==============================7566 JONES 2975 207788 SCOTT 3000 207902 FORD 3000 20

•EMPNO ENAME JOB ==============================7499 ALLEN SALESMAN

•7521 WARD SALESMAN •7654 MARTIN SALESMAN •7844 TURNER SALESMAN •7876 ADAMS CLERK

Using Logical operators (Contd…)Example: To get EMPNO, ENAME, JOB, SAL of all employees whose names do not start with A.

SELECT EMPNO, ENAME,JOBFROM EMP WHEREENAME NOT LIKE 'A%'

•EMPNO ENAME JOB ==============================

• 7369 SMITH CLERK•7521 WARD SALESMAN•7566 JONES MANAGER•7654 MARTIN SALESMAN•7698 BLAKE MANAGER•7782 CLARK MANAGER•7788 SCOTT ANALYST

Copyright © 2009 Accenture All Rights Reserved. 2323

•7839 KING PRESIDENT•7844 TURNER SALESMAN•7900 JAMES CLERK•7902 FORD ANALYST•7934 MILLER CLERK

101

Page 103: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using NULL Operator• NULL values are also known as unknown values. • In RDBMS, inapplicable or missing information is known as

NULL

Example: To get EMPNO, ENAME and SAL from EMP who do not receive a commission.

NULL.• The IS NULL condition tests for nulls.

•EMPNO ENAME SAL COMM===================================• 7369 SMITH 800• 7566 JONES 2975

7698 BLAKE 2850

Sample output

Copyright © 2009 Accenture All Rights Reserved. 2424

SELECT EMPNO, ENAME,SAL FROM EMPWHERE COMM IS NULL;

• 7698 BLAKE 2850• 7782 CLARK 2450• 7788 SCOTT 3000• 7839 KING 5000• 7876 ADAMS 1100• 7900 JAMES 950• 7902 FORD 3000• 7934 MILLER 1300

Using NOT NULL Operator• NOT NULL is used to check whether a particular column

contains a value• We can use NOT NULL to select a column which containWe can use NOT NULL to select a column which contain

values

EMPNO ENAME SAL COMM=================================7499 ALLEN 1600 3007521 WARD 1250 500

Example: To get EMPNO, ENAME and SAL from EMP who do not receive a commission.

Sample output

Copyright © 2009 Accenture All Rights Reserved. 2525

7654 MARTIN 1250 14007844 TURNER 1500 0SELECT EMPNO, ENAME,

SAL FROM EMPWHERE COMM ISNOT NULL;

102

Page 104: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using Arithmetic Operators

• Arithmetic operators along with the column names can be used to retrieve values

SELECT

• Arithmetic operations can be performed on a single column or multiple columns

• The Arithmetic operators normally used are: +, - , / and *

Example: To get EMPNO and TOTALSAL of all employees

Sample output :

Copyright © 2009 Accenture All Rights Reserved. 2626

EMPNO,SAL+ COMM TOTALSAL FROM EMP WHERE COMM IS NOT NULL;

•EMPNO TOTALSAL=================• 7499 1900• 7521 1750• 7654 2650• 7844 1500

103

Page 105: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

String values can be used to give more clarity to the result set.

Example: To get EMPNO and TOTALSAL for all EMPLOYEES:

SELECT EMPNO AS EmployeeNum, SAL+COMM AS Total Sal FROM EMP;

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

104

Page 106: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

Column standing position is the position of the column in the select statement.The column standing position comes handy when we are applying some aggregatefunctions on a column name and that column has to be used in the order by clause

Example : SELECT ENAME,JOB FROM P WHERE DEPTNO IN (10,20) ORDER BY 1 DESC, 2;

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

105

Page 107: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

106

Page 108: Introduction to RDBMS Participant Guide

8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL

Try out different combinations for date.1) Display month2) Display only year3) Display day4) Display hour, min and seconds

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

107

Page 109: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

To_number• It converts a char value which contains digits to a numeric

value.Sample Output :

SELECT TO_NUMBER(TO_CHAR(HIREDATE,'MM')) AS MONTHNUMBER FROM EMP

•MONTHNUMBER•==============• 12• 2• 2• 4• 9• 5

p p

Copyright © 2009 Accenture All Rights Reserved. 31

• 6• 4• 11• 9• 5• 12• 12• 1

31

Date Functions:

MONTHS_BETWEEN: It finds the number of months between two dates. Syntax :

MONTHS_BETWEEN(date1, date2)

Example :

SELECT MONTHS_BETWEEN(SYSDATE,'1-OCT-08')From dual

Copyright © 2009 Accenture All Rights Reserved. 32

•MONTHSBETWEEN•==================

2.96264337

Sample Output :

32

108

Page 110: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

NVL Function

• Converts a null value to a non-null value.Syntax :Syntax :

NVL(arg1, arg2)

• If argument1 is not null, then it displays its value. • If argument 1 is null , then it displays arg2.

Copyright © 2009 Accenture All Rights Reserved. 33

Example: SELECT NVL(COMM,0) FROM EMP

33

NVL Function (Contd...)SELECT NVL(COMM,0) AS COMMISION FROM EMP

SELECT NVL(TO_CHAR (COMM),'NO COMMISION')AS COMMISION FROM EMP

S l O t t

• COMMISION•============• 0• 300• 500• 0• 1400• 0• 0

AS COMMISION FROM EMP

• COMMISION•============•NO COMMISION•300•500•NO COMMISION•1400•NO COMMISION

Copyright © 2009 Accenture All Rights Reserved. 34

Sample Output • 0• 0• 0• 0• 0• 0• 0

•NO COMMISION•NO COMMISION•NO COMMISION•0•NO COMMISION•NO COMMISION•NO COMMISION•NO COMMISION

34

109

Page 111: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

DECODE

• The DECODE function behaves like the IF..THEN ..ELSE statement. Syntax:

DECODE (expression , search1 , result1 [, search2 , result2]... [, default] )

• If the value of expression is equivalent to search1

Copyright © 2009 Accenture All Rights Reserved. 35

then result1 is returned, else expression is compared to search2 and if found equal returns result2 and so on. If no match found, then “default” is returned.

35

DECODE (Contd...)

• JOB

Sample Output :Example:

SELECT DECODE(JOB,'ANALYST','A‘ ,'CLERK','C',

'MANAGER','M','PRESIDENT','P','SALESMAN','S')

• JOB•=====•C•S•S•M•S•M•M•A

Copyright © 2009 Accenture All Rights Reserved. 36

AS JOB FROM EMP;•A•P•S•C•C•A•C

36

110

Page 112: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

ESCAPE option• Escape option is used when you use special characters in the string and

the actual meaning of these characters should be ignored when “%” and “_” are used for pattern matching.

Th ti ifi h t th h t i h t t• The option specifies what the escape character is when you want to search for strings that contains ‘Sr_’

• Example: If job contains: • Sr_MAN• Sr_Exec• Sr_Asst• Sr_Clerk

SQL> SELECT * FROM EMP WHERE JOB Output:

Copyright © 2009 Accenture All Rights Reserved. 3737

LIKE ‘Sr\_%’ ESCAPE ‘\’; SA_MANSA_REPSA_REPSA_REP

Printing the SQL Output

• The SQL output can be redirected using SPOOL command. By default the redirection is on the

fscreen, but it can be changed to file or printer as required.

SPOOL ONSELECT * FROM EMP;

Redirection IS ON SCREENSPOOL PRN

Copyright © 2009 Accenture All Rights Reserved. 38

SPOOL PRN;SELECT * FROM EMP;

Redirection IS ON PRINTERSPOOL OFF

38

111

Page 113: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Printing the SQL Output (Contd...)

TO FILE:

SPOOL FILE1SELECT * FROM EMP;

Redirected TO FILE1.LST [c:\ORACLE\BIN ]

SPOOL OFF

Copyright © 2009 Accenture All Rights Reserved. 39

SPOOL OFF

39

8: Data Manipulation LanguageActivity (2 of 2)

• Input documents:– Activity_5.1_Module8_DataM

anipulationLanguage.doc• Output documents:

– Activity_5.1_Module8_DataManipulationLanguageOutput.doc

Copyright © 2009 Accenture All Rights Reserved. 4040

120 Minutes

112

Page 114: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Key Points• RDBMS allow to view tables and the records they

hold.• It allows to add modify and delete the data• It allows to add, modify and delete the data.• SELECT statement is used to retrieve data from a

table.• SELECT statement along with WHERE clause can be

used to filter the rows from a table.• The logical operators AND, OR and NOT can be used

t bi diti f WHERE l

Copyright © 2009 Accenture All Rights Reserved. 4141

to combine conditions for a WHERE clause.• ORDER BY can be used to sort the results from a

SELECT statement.

8: Data Manipulation LanguageKey Points (Contd…)

• TO_Char converts a date or a number to a character value.

• To_number converts a char. string which contains digits to a numeric value.

• Months_Between finds the number of months between date1 and date2.

• NVL Converts a null value to an NON-NULL value.Th DECODE f ti b h lik th IF THEN

Copyright © 2009 Accenture All Rights Reserved. 4242

• The DECODE function behaves like the IF..THEN ..ELSE statement

• SQL output can be redirected by using SPOOL command.

113

Page 115: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 8_DataManipulationLanguage.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 43

114

Page 116: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMSand SQL

Module 9: Aggregate Functions, Joins and Sub queries

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Learning Objectives• Understand aggregate functions• Work with Group By and Having By Clause.• Work with Set Operators.• Work with Sub queries and Correlated sub queries• Work with EXISTS and NOT EXISTS• Work with different types of joins• Understand the difference between joins and subqueries

Copyright © 2009 Accenture All Rights Reserved. 2

115

Page 117: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Module 9: Agenda• Aggregate Functions• Retrieval Using GROUP BY and HAVING Clause• Set Operators• Set Operators

– Union.– Intersect.– Minus.

• Subqueries– Non-Corelated Subqueries.– Correlated Subqueries.

Copyright © 2009 Accenture All Rights Reserved.

Correlated Subqueries.• Joins

– Inner Join– Self Join– Outer Join

• Use of EXISTS3

Aggregate functions

• Aggregate functions are functions that take a collection (a set or multiset) of values as input and return a single al evalue.

• Each of these functions perform an action that draws data from a set of rows instead of a single row.

• Aggregate functions are used along with the column names in the SELECT statement.

• Aggregate functions ignore null values.

Copyright © 2009 Accenture All Rights Reserved.

• Aggregate functions cannot be used with the WHERE clause.

4

116

Page 118: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Aggregate functions (Contd..)

Function Name Description

SUM() Adds up the values in the specified column of numeric data type.Value of the sum must be within the range of that data type.

AVG() Returns the average of all the values in the specified column.Column must be numeric data type.

MAX() Returns the largest value that occurs in the specified column.Column need not be numeric data type.

MIN() Returns the smallest value that occurs in the specified column.

Copyright © 2009 Accenture All Rights Reserved.

Column need not be numeric data type.

COUNT(Qty) Returns the number of rows that do not have NULL Value in the column Qty.

COUNT(*) Returns the number of rows in the table.

5

117

Page 119: Introduction to RDBMS Participant Guide

9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL

The aggregate functions ignore the null values while applying aggregation.

Example:

SELECT AVG(COMM) FROM EMP will return 550, however

SELECT AVG(NVL(COMM,0)) FROM EMP will return 157.14

The difference in result is due to the null values ignored in the earlier example. Withthe use of NVL function, the null values are converted to 0 and hence they are usedwhile performing the average function.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

118

Page 120: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using GROUP BY• Any column on which the aggregate function is used is called an

aggregate column and a column on which an aggregate function is not applied is called a non-aggregate columnapplied is called a non aggregate column.

• GROUP BY clause works on rows which can be grouped on the basis of non-aggregate columns.

• The GROUP By clause cannot work on its own, it has to be used with aggregate functions.

• GROUP BY allows to group identical data into one subset rather than listing each record and sorts the data on the grouped column.

Copyright © 2009 Accenture All Rights Reserved.

g g p• The GROUP BY clause must include all the non-aggregate columns

mentioned in the SELECT statement.• Example:

– Find the number of Employees belonging to a particular department– Total salary for each job

7

Example - GROUP BY Clause

Example: Display JOB, TOTALSAL of each employee.

SELECT JOB, SUM(SAL) TOTALSALFROM EMPGROUP BY JOB;

Sample Output : JOB TOTALSAL===================

Copyright © 2009 Accenture All Rights Reserved.

Sa p e Output ===================ANALYST 6000CLERK 4150MANAGER 8275PRESIDENT 5000SALESMAN 5600

8

119

Page 121: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using HAVING Clause• HAVING Clause is used to filter data and is used only with

GROUP BY clause

• Aggregate functions can be used with the HAVING clause.

• Both the WHERE and HAVING clause are used for filtering the data. However, the WHERE clause is applied before the GROUP BY whereas the HAVING clause is applied after GROUP BY.

HAVING l i d i it ti h th filt i i

Copyright © 2009 Accenture All Rights Reserved.

• HAVING clause is used in situations where the filtering is required on the aggregate columns.

SELECT column_list FROM table GROUP BY column HAVING condition

Syntax:

9

120

Page 122: Introduction to RDBMS Participant Guide

9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL

To display the total number of employees in each dept, the query is: SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO

However, if the total number of employees working in each dept should be more than 3 then the query is:

SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3;

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

121

Page 123: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

9: Aggregate Functions, Joins and Sub queriesActivity (1 of 4)

• Input documents:– Activity_6.0_Module9_Aggregate.d

ococ

• Output documents:– Activity_6.0_Module9_AggregateO

utput.doc

Copyright © 2009 Accenture All Rights Reserved. 11

60 Minutes

SET Operators• The SET operators are used to work on multiple tables and

return information that is either – Common as well as unique in all the tablesq– Common in all the tables– Unique in the table

• There are 3 sets of operators– UNION/UNION ALL– INTERSECT– MINUS

• For the above operators to work correctly same number of

Copyright © 2009 Accenture All Rights Reserved.

• For the above operators to work correctly, same number of columns must be specified in each SELECT statement and the data types should also match.

• The order by clause can be used at the end of the last select statement and can be sorted only on the columns specified in the first SELECT statement.

12

122

Page 124: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using UNION

• Union operator is used to combine the result of two or more SELECT statements into one result set.

• It returns all distinct rows selected by the queries.

• Duplicates are removed unless UNION ALL is used.

SELECT column-list FROM tableS t

Copyright © 2009 Accenture All Rights Reserved.

SELECT column list FROM table

UNION

SELECT column-list FROM table

Syntax:

13

Using UNION (Contd…)

Example: To get a list of all the deptno where the employees are working along with the list of those deptno where noare working along with the list of those deptno where no employees are working in it.

SELECT DEPTNO FROM DEPTUNIONSELECT DEPTNO FROM EMP

Copyright © 2009 Accenture All Rights Reserved.

Sample Output :•DEPTNO=================• 10• 20• 30• 40

14

123

Page 125: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using INTERSECT

• INTERSECT operator returns only rows that are common in all the tables.

Syntax:

SELECT column-list FROM table1

INTERSECT

Copyright © 2009 Accenture All Rights Reserved.

INTERSECT

SELECT column-list FROM table2

15

Using INTERSECT (Contd…)

Example: To get a list of all deptno which has employees working in it.working in it.

SELECT DEPTNO FROM DEPTINTERSECTSELECT DEPTNO FROM EMP

S l O t t •DEPTNO

Copyright © 2009 Accenture All Rights Reserved.

Sample Output : =================• 10• 20• 30

16

124

Page 126: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Using Minus• MINUS operator returns only rows that are unique in the

first table.

Syntax:

SELECT column-list FROM table1

MINUS

SELECT l li t FROM t bl 2

Copyright © 2009 Accenture All Rights Reserved.

SELECT column-list FROM table2

17

Using Minus (Contd…)

Example: To get a list of all deptno which does not have any employees working in it.any employees working in it.

SELECT DEPTNO FROM DEPTMINUSSELECT DEPTNO FROM EMP

S l O t t •DEPTNO

Copyright © 2009 Accenture All Rights Reserved.

Sample Output : =================• 40

18

125

Page 127: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

9: Aggregate Functions, Joins and Sub queriesActivity (2 of 4)

• Input documents:– Activity_6.1_Module9_Union_

Intersect_Minus.doc• Output documents:

– Activity_6.1_Module9_Union_Intersect_Minus.doc

Copyright © 2009 Accenture All Rights Reserved. 19

45 Minutes

Subqueries

• Subqueries are also called as Nested queries which means SELECT statement can be nested i id th SELECT t t tinside another SELECT statement.

• The subquery is placed in the WHERE clause of a SELECT statement.

• It allows to group multiple SELECT statements together.

• There are 2 types of Sub queries:

Copyright © 2009 Accenture All Rights Reserved.

• There are 2 types of Sub queries:– Independent/Non-correlated sub queries and – Correlated sub queries

• Subqueries can return either a single row or multiple rows.

20

126

Page 128: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Independent/Non-Correlated Sub queries

• A subquery is also called as an inner query.

• The query which is placed before the inner query is called• The query which is placed before the inner query is called as the Outer query or Parent Query

• In Independent Sub queries– Inner query is executed independent of outer query.– The inner query executes only once.

Copyright © 2009 Accenture All Rights Reserved.

– Inner query is executed first and the results replace the inner SELECT statement.

– Outer query then executes based on the results provided by the inner query.

21

Operators used in Sub queries

Operator Description

Comparison (= <> < > <= >=) Used when subquery returnsComparison Operator

(=,<>,<,>,<=,>=). Used when subquery returns a single value.

IN It is used to select rows that match the value in a list. Used when subquery returns multiple rows.

ANY or SOMEALL

It compares a value to either each value returned by a sub query or all values returned

Copyright © 2009 Accenture All Rights Reserved.

ALL e u ed by a sub que y o a a ues e u edby the subquery. Used when subquery returns multiple rows along with comparison operators.

EXISTS It always returns data in terms of TRUE or False value. Used with co-related subqueries.

22

127

Page 129: Introduction to RDBMS Participant Guide

9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL

Contents:If the option of subquery was not available then to solve the query of finding theemployees who are receiving the salary less than the average salary, 2 separatequeries will be required as shown below:

1) Find the average salary• SELECT AVG(SAL) FROM EMP

2) Get the average salary and find the employee names2) Get the average salary and find the employee names.• SELECT ENAME FROM EMP WHERE SAL < 2073.21

Instead of executing these two queries separately, you can execute it through asubquery. The advantage here is that if there are any change in the EMP table, i,enew record is added in emp table or the salary is updated or a record is deleted,then the second query will not give the correct result since the average is changedthen the second query will not give the correct result since the average is changed.So, for every change in the EMP table, the first query has to be run first, theaverage has to be noted and then execute the second query. To avoid this situatuionsubquery can be used as shown below:

• SELECT ENAME FROM EMP WHERE SAL < (SELECT AVG(SAL) FROM EMP);

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

128

Page 130: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Non-Corelated Sub queries (Contd…)

Example: To display the names of the employees working in dept

Subqueries returning multiple rows.

To display the names of the employees working in dept ACCOUNTING and SALES.

SELECT ENAME,JOB,SAL FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM

Sample Output :•ENAME JOB SAL•============================• ALLEN SALESMAN 1600• WARD SALESMAN 1250

Copyright © 2009 Accenture All Rights Reserved.

(DEPT WHERE DNAME IN ('ACCOUNTING','SALES'))

•MARTIN SALESMAN 1250• BLAKE MANAGER 2850• CLARK MANAGER 2450• KING PRESIDENT 5000•TURNER SALESMAN 1500• JAMES CLERK 950•MILLER CLERK 1300

24

Non-Corelated Sub queries (Contd…)

Example: To find the names of the employees who receive

Subqueries with ANY/ALL operatorsExample: To find the names of the

l h i l l

SELECT ENAME,JOB, SAL FROM EMPWHERE SAL <ALL(SELECT AVG(SAL)FROM EMP GROUP BY JOB)

the employees who receive salary less than every average salary for each type of job.

employees who receive salary less than either of average salary for each type of job.

SELECT ENAME,JOB, SAL FROM EMPWHERE SAL <ANY(SELECT AVG(SAL)FROM EMP GROUP BY JOB)

Copyright © 2009 Accenture All Rights Reserved.

)

Sample Output :•ENAME JOB SAL•===========================•SMITH CLERK 800•ALLEN SALESMAN 1600•……… ………….. ……….

•ENAME JOB SAL•========================•SMITH CLERK 800•JAMES CLERK 950

)

Sample Output :

25

129

Page 131: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Correlated Sub queries

• Correlated subquery is a subquery that references the outer query.q y

• For Correlated Subqueries– Inner query is dependent upon the outer query– The inner query is executed as many times as

the outer query executes.

Copyright © 2009 Accenture All Rights Reserved. 26

Example – Correlated sub query

To get the employee details who earn salary greater than the average salary of their department.g y p

SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP E WHERE SAL >(SELECT AVG(SAL) FROM EMP E2WHERE E1.DEPTNO=E2.DEPTNO);

Sample Output : EMPNO ENAME SAL DEPTNO============================

Copyright © 2009 Accenture All Rights Reserved.

p p ============================7499 ALLEN 1600 307566 JONES 2975 207698 BLAKE 2850 307788 SCOTT 3000 207839 KING 5000 107902 FORD 3000 20

27

130

Page 132: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Example – Correlated sub query

To get employee names who have a reporting authority. Sample Output :

SELECT ENAME FROM EMP E1WHERE MGR =(SELECT EMPNO FROM EMP E2WHERE E1 MGR=E2 EMPNO);

Sample Output :•ENAME•=========•SMITH•ALLEN•WARD•JONES•MARTIN•BLAKE

Copyright © 2009 Accenture All Rights Reserved.

WHERE E1.MGR E2.EMPNO);•CLARK•SCOTT•TURNER•ADAMS•JAMES•FORD•MILLER

28

Using EXISTS

• Exists clause checks for the existence of rows and does not compare columns or its values.It i d t h k th i t f d t di t• It is used to check the existence of data rows according to the condition specified in the inner query and passes the existence status to the outer query to produce the result set.

• EXISTS clause, always returns data in terms of a TRUE or FALSE value.

• EXISTS clause can also be used with the not operator

Copyright © 2009 Accenture All Rights Reserved.

EXISTS clause can also be used with the not operator.• The inner query need not specify any columns in the select

statement.

29

131

Page 133: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Example – using Exists

Example To list the employee details who directly report to manager ‘KING’.

SELECT ENAME FROM EMP E1 WHERE EXISTS(SELECT * FROM EMP E2 WHERE E1.MGR=E2.EMPNO AND E2.ENAME=‘KING’);

p g

Copyright © 2009 Accenture All Rights Reserved.

Sample Output :ENAME=======JONESBLAKECLARK

30

9: Aggregate Functions, Joins and Sub queriesActivity (3 of 4)

• Input documents:– Activity_6.2_Module9_Subqueries.

docdoc

• Output documents:– Activity_6.2_Module9_Subqueries.

doc

Copyright © 2009 Accenture All Rights Reserved. 31

100 Minutes

132

Page 134: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

JOINS• Joins are normally used to retrieve data from more than

one table.• The JOIN keyword joins one or more tables together in a• The JOIN keyword joins one or more tables together in a

results set • To perform a join there must be a common key that defines

how the rows in the table correspond to each other.• All subqueries can be converted to joins but all joins cannot

be converted to subqueries.

Copyright © 2009 Accenture All Rights Reserved. 32

Types of Joins

• Different types of joins are

– Inner joinInner join

– Outer join

• Left-outer join

• Right-outer join• Full outer join

Copyright © 2009 Accenture All Rights Reserved.

– Self join

33

133

Page 135: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Inner Join

• The inner join joins two or more tables returning only matched rows

• Inner Join requires that both tables involved in the join must have a primary-foreign key relationship

Copyright © 2009 Accenture All Rights Reserved. 34

Inner Join (contd...)

Example: To display the ename, job, sal and dname in which the employees are workingp y g

SELECT ENAME, JOB,SAL, DNAME FROM DEPT D,EMP EWHERED DEPTNO=E DEPTNO;

•ENAME JOB SAL DNAME•=====================================•SMITH CLERK 800 RESEARCH•ALLEN SALESMAN 1600 SALES•WARD SALESMAN 1250 SALES•JONES MANAGER 2975 RESEARCH•MARTIN SALESMAN 1250 SALES•BLAKE MANAGER 2850 SALES•CLARK MANAGER 2450 ACCOUNTING

Copyright © 2009 Accenture All Rights Reserved.

D.DEPTNO=E.DEPTNO;

Sample Output

•CLARK MANAGER 2450 ACCOUNTING•SCOTT ANALYST 3000 RESEARCH•KING PRESIDENT 5000 ACCOUNTING•TURNER SALESMAN 1500 SALES•ADAMS CLERK 1100 RESEARCH•JAMES CLERK 950 SALES•FORD ANALYST 3000 RESEARCH•MILLER CLERK 1300 ACCOUNTING

35

134

Page 136: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Outer Join

• Outer Join returns not only the common rows from the tables but also returns the rows that are unique in the tables

• In Outer Join, rows are returned even if the rows from one table is not matching with those of another table

• There are three types of Outer Joins – Left outer join – Right outer join– Full outer join

Copyright © 2009 Accenture All Rights Reserved.

– Full outer join

36

Left Outer Join

• In left outer join, all the records from the table on the left of the OUTER JOIN statement are returned

SELECT column_list FROM left_table LEFT [OUTER] JOIN right_table ON condition

Syntax

Copyright © 2009 Accenture All Rights Reserved.

SELECT column_list FROM table t1,table t2 where t1.column_name=t2.column_name (+)

37

135

Page 137: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Left Outer Join (contd…)

Example: To display the ename, job, sal and dname in which the employees are working along with the dname in which no employees are workingare working.

SELECT ENAME,JOB,SAL, DNAME FROM DEPT DLEFT JOIN EMP E ON D.DEPTNO =

•ENAME JOB SAL DNAME•=====================================•SMITH CLERK 800 RESEARCH•ALLEN SALESMAN 1600 SALES•WARD SALESMAN 1250 SALES•JONES MANAGER 2975 RESEARCH•MARTIN SALESMAN 1250 SALES•BLAKE MANAGER 2850 SALES•CLARK MANAGER 2450 ACCOUNTING

Copyright © 2009 Accenture All Rights Reserved.

E.DEPTNO;

Sample Output

•SCOTT ANALYST 3000 RESEARCH•KING PRESIDENT 5000 ACCOUNTING•TURNER SALESMAN 1500 SALES•ADAMS CLERK 1100 RESEARCH•JAMES CLERK 950 SALES•FORD ANALYST 3000 RESEARCH•MILLER CLERK 1300 ACCOUNTING

38

136

Page 138: Introduction to RDBMS Participant Guide

9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL

The above example will retrieve rows from order_master table which do not haveany matching records in the order_detail table.Such a retrieval is due to thepresence of an outer join(+).

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

137

Page 139: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Right Outer Join (contd…)

Example: To display the ename, job, sal and dname in which the employees are working along with the dname in which no employees are workingare working.

SELECT ENAME,JOB,SAL, DNAME FROM EMP ERIGHT JOIN DEPT D ON E.DEPTNO =

•ENAME JOB SAL DNAME•=====================================•SMITH CLERK 800 RESEARCH•ALLEN SALESMAN 1600 SALES•WARD SALESMAN 1250 SALES•JONES MANAGER 2975 RESEARCH•MARTIN SALESMAN 1250 SALES•BLAKE MANAGER 2850 SALES•CLARK MANAGER 2450 ACCOUNTING

Copyright © 2009 Accenture All Rights Reserved.

D.DEPTNO;

Sample Output

40

•SCOTT ANALYST 3000 RESEARCH•KING PRESIDENT 5000 ACCOUNTING•TURNER SALESMAN 1500 SALES•ADAMS CLERK 1100 RESEARCH•JAMES CLERK 950 SALES•FORD ANALYST 3000 RESEARCH•MILLER CLERK 1300 ACCOUNTING

OPERATIONS

Full Outer Join• A full outer join is essentially a combination of

left and right outer joins i.e..,The records from the table on left are included even if– The records from the table on left are included even if there are no matching records on the right

– The records from the table on the right are included even if there are no matching records on the left.

Syntax:

Copyright © 2009 Accenture All Rights Reserved.

SELECT column_list FROM left_table FULL [OUTER] JOIN right_table ON condition

41

138

Page 140: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Full Outer Join (contd...)

Example: Sample Output :

SELECT ENAME, JOB,SAL, DNAME FROM EMP E FULL JOIN DEPT D ON E.DEPTNO = D.DEPTNO;

•ENAME JOB SAL DNAME•=====================================•SMITH CLERK 800 RESEARCH•ALLEN SALESMAN 1600 SALES•WARD SALESMAN 1250 SALES•JONES MANAGER 2975 RESEARCH•MARTIN SALESMAN 1250 SALES•BLAKE MANAGER 2850 SALES•CLARK MANAGER 2450 ACCOUNTING

Copyright © 2009 Accenture All Rights Reserved.

;

42

•SCOTT ANALYST 3000 RESEARCH•KING PRESIDENT 5000 ACCOUNTING•TURNER SALESMAN 1500 SALES•ADAMS CLERK 1100 RESEARCH•JAMES CLERK 950 SALES•FORD ANALYST 3000 RESEARCH•MILLER CLERK 1300 ACCOUNTING

OPERATIONS

Self Join

• A self-join is a query in which a table is joined (compared) to itself.

• It is used to compare values in a column with other values in the same column in the same table.

• Self-joins are also very useful in conjunction with sub queries.

Copyright © 2009 Accenture All Rights Reserved. 43

139

Page 141: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Self Join (Contd…)

Example: To find out the manager names for each of theemployee

S l O t tSELECT E1.ENAME||'REPORTS TO '|| E2.ENAME AS REPORTS FROM EMP E1, EMP E2 WHERE E1.MGR=E2.EMPNO;

Sample Output :•REPORTS•==============•SMITH REPORTS TO FORD•ALLEN REPORTS TO BLAKE•WARD REPORTS TO BLAKE•JONES REPORTS TO KING•MARTIN REPORTS TO BLAKE

Copyright © 2009 Accenture All Rights Reserved.

•BLAKE REPORTS TO KING•CLARK REPORTS TO KING•SCOTT REPORTS TO JONES•TURNER REPORTS TO BLAKE•ADAMS REPORTS TO SCOTT•JAMES REPORTS TO BLAKE•FORD REPORTS TO JONES•MILLER REPORTS TO CLARK

44

Sample Output :

9: Aggregate Functions, Joins and Sub queriesActivity (4 of 4)

• Input documents:– Activity_6.3_Module9_Joins.doc

• Output documents:– Activity_6.3_Module9_JoinsOutput.

doc

Copyright © 2009 Accenture All Rights Reserved. 45

150 Minutes

140

Page 142: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Key Points

• Aggregate Functions are applied on rows and return single value.GROUP BY clause works on rows which can be grouped• GROUP BY clause works on rows which can be grouped on the basis of non-aggregate columns.

• SUBQUERIES are SQL statements within SQL statement.• SUBQUERIES can be independent or correlated.• Joins are used to retrieve data from more than one table.• Different types of JOINS

Copyright © 2009 Accenture All Rights Reserved. 46

yp– Inner Join.– Outer Join (Left Outer Join, Right Outer Join and Full

Outer Join).– Self Join.

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 47

141

Page 143: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 10_Views.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQLModule 10: Views

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Learning Objectives

• Understand the concept of Views• Understand why views are required in a database• Understand how to create and work with the views

Copyright © 2009 Accenture All Rights Reserved. 2

142

Page 144: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 10_Views.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Agenda• Introduction to Views• Creating Views• Complex Views• Read Only view• View with Check Option

Copyright © 2009 Accenture All Rights Reserved. 3

• Views are virtual tables (tables which don’t occupy memory) whose contents are taken or derived from

Introduction to Views

other tables.• Just like other tables, a view consists of rows with

columns, and you can retrieve data from a view.• Views can be used to join two tables in database

and present the data as if the data were coming from a single table

Copyright © 2009 Accenture All Rights Reserved.

from a single table • Views can be used as a security mechanism to

restrict the data available to end users • Views can also be used to aggregate data.

4

143

Page 145: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

This example shows creating a view called EmpView from the EMP table.This view contains two columns EmpNo and Empname which are taken from EMP table. The actual data will be in the EMP table, which can be manipulated from the EmpView.The EmpView will not occupy memory. But those who are using this view can see only EmpNo and Empname columns.They won’t be able to see the entire EMP tableThey won t be able to see the entire EMP table.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

144

Page 146: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

This example shows how to create a view from an existing table. Ask the participants to create a table Supplier with columns supp_no, supp-name, city, state, postal_code.Ask the participants to enter few data.The example creates a view called v_supp which is derived from the Supplier table. It contains supp_no, supp_name and supp_city columns from the Supplier table.

Second example creates a v_supp_city View from Supplier table. But this view contains rows which belong to the MUM city.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

145

Page 147: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

146

Page 148: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

The syntax of Complex view is similar to Create ViewComplex view is a view which contains normally GROUP BY functions as well as joins.The above example creates a complex view v_dept_emp which selects the dname column, maximum sal, minimum sal and average sal.The example uses three Aggregate functions and it joins two tables Dept and Emp.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

147

Page 149: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

148

Page 150: Introduction to RDBMS Participant Guide

10_Views.pptIntroduction to RDBMS and SQL

Faculty Notes:The With Check option clause specifies that Inserts and Updates performed through the View are not allowed to create rows which the view cannot select, and therefore allows integrity constraints and data validation checks to be enforced on data begin Inserted or Updated.

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

149

Page 151: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 10_Views.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Activity

• Input documents:– Activity_7.0_Module10_Views.doc

• Output documents:– Activity_7.0_Module10_ViewsOutp

ut.doc

Copyright © 2009 Accenture All Rights Reserved. 11

45 Minutes

Key Points

• Views are virtual tables.• Views provide security of data.• Views conceal complexity of queries which contain

complicated queries or sub queries.• Normally a complex view will contain joins, subqueries and

aggregate functions.

Copyright © 2009 Accenture All Rights Reserved. 12

150

Page 152: Introduction to RDBMS Participant Guide

Introduction to RDBMS and SQL 10_Views.ppt

IDCGRF002Copyright © 2009 Accenture All Rights Reserved

Questions/ Comments• What questions or

comments do you have?

Copyright © 2009 Accenture All Rights Reserved. 13

151

Page 153: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 3: Database Design Techniques

IDCGRF002 Activity_1.0_Module3_DatabaseDesignTechniques.doc © 2009 Accenture. All Rights Reserved.

Module 3 Activity 1.0: Create Database Design

Estimated Completion Time: 60 minutes

Overview This exercise will require participants to design the database using normalization techniques. Participants should identify the primary key and will link the two tables via a foreign key.

Instructions The normalized structure should be created using the Microsoft Word.

1. In order to proceed with normalization, first analyze the given data structure and identify all related data elements. If required or needed create new data elements create new tables or reuse the data elements. Data elements and tables should be unique. Name the tables with <tablename>_INFO.

Hints 1. Ensure the following while normalizing the table:

Each course has many sections and the sections are taught by different instructors.

A student may enroll in 1 section or many sections or may not enroll in any sections. i.e., the student may come just for inquiry of a particular course but may not necessarily enroll.

A student is awarded a grade based on the sections that he/she has enrolled for. Each section may have different grade types and it also stores how many times the student has taken an exam and has received a grade.

1

Page 154: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 3: Database Design Techniques

IDCGRF002 Activity_1.0_Module3_DatabaseDesignTechniques.doc © 2009 Accenture. All Rights Reserved.

Data Structure

Field Name Primary Key

COURSE_NO

COURSE_NAME

COURSE_PREREQUISITE

COST

SECTION_ID

SECTION_NO

LOCATION

CAPACITY

STUDENT_ID

STUDENT_FIRST_NAME

STUDENT_LAST_NAME

REGISTRATION_DATE

INSTRUCTOR_ID

INSTRUCTOR_FIRST_NAME

INSTRUCTOR_LAST_NAME

ZIP_CODE

CITY

STATE

STREET_ADDRESS

ENROLL_DATE

GRADE_TYPE_CODE

GRADE_CODE_OCCURANCE

NUMERIC_GRADE

2

Page 155: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 4: E-R Mode

IDCGRF002 Activity_2.0_Module4_ER Model.doc © 2009 Accenture. All Rights Reserved.

Module 4 Activity 2.0: E-R Model

Estimated Completion Time: 60 minutes

Overview This exercise will require participants to create an entity relationship diagram. Participants should identify the types of relationship between the tables, primary key and will link the two tables via a foreign key.

Instructions The entity relationship diagram should be created using Microsoft Word.

1. In order to proceed with the entity relationship, first identify the tables from the given data structure and define the relationship between them.

2. Naming conventions should be followed for creating the entity relationship as follows:

Symbols Element Name

Table Name

# Primary Key

* Not Null

Numeric Values

Varchar Values

Date Values

Hints 1. Ensure the following while designing the Entity Relationship diagram:

The symbols shown above should be placed before the column name. Each table should be placed in a rectangle with the specific symbol.

• <tableName> Each column should be placed with a specific symbol.

• # emp_id number primary key The tables should be identified with proper symbols for identifying the

relationships.

3

Page 156: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 4: E-R Mode

IDCGRF002 Activity_2.0_Module4_ER Model.doc © 2009 Accenture. All Rights Reserved.

Tables

1) The tables normalized in the Module 3 should be used as a base for creating the Entity-Relationship diagrams.

4

Page 157: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.0_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

Module 6 Activity 3.0: Creating Tables

Estimated Completion Time: 60 minutes

Overview This exercise will require participants to create the tables in Oracle SQL PLUS using the SQL language.

Instructions The creation of the tables should be done in Oracle SQL PLUS.

1. In order to proceed with creating the tables, first create a new user in SYSTEM login and grant resource and connect permissions to that user.

2. Login using that user and then proceed to create the tables. Name the tables with <tablename>_INFO.

Hints 1. Ensure the following while creating the table:

Each table name should end with the word INFO. Create a notepad file and save the file in C:\RDBMS\Day2\Tables.sql. In the notepad file write the SQL syntax for creating the tables. Run the file in SQL Plus as @ c:\RDBMS\Day2\Tables.sql. After running the file give the command “SELECT * FROM TAB” to view the

tables created after executing Tables.sql.

5

Page 158: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.0_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

Tables

1) Table Name: ZIPCODE_INFO

Field Name Type Length

ZIP_CODE VARCHAR2 5

CITY VARCHAR2 10

2) Table Name: INSTRUCTOR_INFO

Field Name Type Length

INSTRUCTOR_ID NUMBER 8,0

INSTRUCTOR_FIRST_NAME VARCHAR2 15

INSTRUCTOR_LAST_NAME VARCHAR2 15

3) Table Name: COURSE_INFO

Field Name Type Length

COURSE_NO NUMBER 8,0

COST NUMBER 5,2

4) Table Name: STUDENT_INFO

Field Name Type Length

STUDENT_ID NUMBER 8,0

STUDENT_FIRST_NAME VARCHAR2 15

STUDENT_LAST_NAME VARCHAR2 15

6

Page 159: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.0_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

5) Table Name: SECTION_INFO

Field Name Type Length

SECTION_ID NUMBER 8,0

COURSE_NO NUMBER 8,0

SECTION_NO NUMBER 5

INSTRUCTOR_ID NUMBER 8,0

6) Table Name: ENROLLMENT_INFO

Field Name Type Length

STUDENT_ID NUMBER 8,0

SECTION_ID NUMBER 8,0

7) Table Name: GRADE_INFO

Field Name Type Length

STUDENT_ID NUMBER 8,0

SECTION_ID NUMBER 8,0

GRADE_TYPE_CODE CHAR 2

GRADE_CODE_OCCURANCE NUMBER 5

7

Page 160: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.1_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

Module 6 Activity 3.1: Altering Tables

Estimated Completion Time: 45 minutes

Overview This exercise will require participants to alter the tables in Oracle SQL PLUS using the SQL language.

Instructions The altering of the tables should be done in Oracle SQL PLUS.

1. In order to proceed with altering the tables, login using your user name created in Exercise 01 and then proceed to alter the tables.

Hints 1. Ensure the following while altering the table:

Create a notepad file and save the file in C:\RDBMS\Day2\AlterTables.sql. In the notepad file write the SQL syntax for creating the tables. Run the file in SQL Plus as @ c:\RDBMS\Day2\AlterTables.sql. After running the file give the command “SELECT * FROM TAB” to view the

tables created after executing Tables.sql.

8

Page 161: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.1_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

Tables

Below are the changes to be made to the tables. Please refer to Tables.sql created in the previous exercise and accordingly alter the table.

1) Table Name: ZIPCODE_INFO

Field Name Type Length

ZIP_CODE VARCHAR2 5

CITY VARCHAR2 25

STATE VARCHAR2 2

2) Table Name: INSTRUCTOR_INFO

Field Name Type Length

INSTRUCTOR_ID NUMBER 8,0

INSTRUCTOR_FIRST_NAME VARCHAR2 25

INSTRUCTOR_LAST_NAME VARCHAR2 25

STREET_ADDRESS VARCHAR2 50

ZIP_CODE VARCHAR2 5

3) Table Name: COURSE_INFO

Field Name Type Length

COURSE_NO NUMBER 8,0

COURSE_NAME VARCHAR2 50

COURSE_PREREQUISITE NUMBER 8,0

COST NUMBER 9,2

4) Table Name: STUDENT_INFO

Field Name Type Length

STUDENT_ID NUMBER 8,0

STUDENT_FIRST_NAME VARCHAR2 25

STUDENT_LAST_NAME VARCHAR2 25

STREET_ADDRESS VARCHAR2 50

ZIP_CODE VARCHAR2 5

9

Page 162: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 6: Data Definition Language

IDCGRF002 Activity_3.1_Module6_DataDefinationLanguage.doc © 2009 Accenture. All Rights Reserved.

5) Table Name: SECTION_INFO

Field Name Type Length

SECTION_ID NUMBER 8,0

COURSE_NO NUMBER 8,0

SECTION_NO NUMBER 3,0

INSTRUCTOR_ID NUMBER 8,0

LOCATION VARCHAR2 50

CAPACITY NUMBER 3,0

6) Table Name: ENROLLMENT_INFO

Syntactical

Field Name Type Length

STUDENT_ID NUMBER 8,0

SECTION_ID NUMBER 8,0

ENROLLMENT_DATE DATE

7) Table Name: GRADE_INFO

Field Name Type Length

STUDENT_ID NUMBER 8,0

SECTION_ID NUMBER 8,0

GRADE_TYPE_CODE CHAR 2

GRADE_CODE_OCCURANCE NUMBER 38,0

NUMERIC_GRADE NUMBER 3,0

10

Page 163: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 7: Constraints

IDCGRF002 Activity_4.0_Module7_Constraints.doc © 2009 Accenture. All Rights Reserved.

Module 7 Activity 4.0: Creating Constraints

Estimated Completion Time: 45 minutes

Overview This exercise will require participants to alter the tables in Oracle SQL PLUS using the SQL language.

Instructions Creating constraints on the tables should be done in Oracle SQL PLUS.

1. In order to proceed with creating constraints on the tables, login using your user name created in Exercise 01 and then proceed to create the constraints on the tables.

Hints 1. Ensure the following while creating the constraints on the table:

All the tables are created and end with the word INFO. Create a notepad file and save the file in C:\RDBMS\Day2\constraints.sql In the notepad file write the SQL syntax for creating the constraints. Run the file in SQL Plus as @ c:\RDBMS\Day2\constraints.sql

11

Page 164: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 7: Constraints

IDCGRF002 Activity_4.0_Module7_Constraints.doc © 2009 Accenture. All Rights Reserved.

Tables

Below are the constraints to be made on the tables.

1) Table Name: ZIPCODE_INFO

Field Name Type Length Constraint Name

ZIP_CODE VARCHAR2 5 PRIMARY KEY – ZIP_PK

CITY VARCHAR2 25 NOT NULL – ZIP_CITY_NN

STATE VARCHAR2 2 NOT NULL – ZIP_STATE_NN

2) Table Name: INSTRUCTOR_INFO

Field Name Type Length CONSTRAINT NAME

INSTRUCTOR_ID NUMBER 8,0 PRIMARY KEY – INSTRUCTOR_ID_PK

INSTRUCTOR_FIRST_NAME VARCHAR2 25 NOT NULL – INSTRUCTOR_FN_NN

INSTRUCTOR_LAST_NAME VARCHAR2 25 NOT NULL – INSTRUCTOR_LN_NN

STREET_ADDRESS VARCHAR2 50

ZIP_CODE VARCHAR2 5 FOREIGN KEY – ZIP_INSTRUCTOR_FK

3) Table Name: COURSE_INFO

Field Name Type Length CONSTRAINT NAME

COURSE_NO NUMBER 8,0 PRIMARY KEY – COURSE_NO_PK

COURSE_NAME VARCHAR2 50 NOT NULL – COURSE_NAME_NN

COURSE_PREREQUISITE NUMBER 8,0

COST NUMBER 9,2 NOT NULL – COST_NN

4) Table Name: STUDENT_INFO

Field Name Type Length CONSTRAINT NAME

STUDENT_ID NUMBER 8,0 PRIMARY KEY – STUDENT_ID_PK

STUDENT_FIRST_NAME VARCHAR2 25 NOT NULL –STUDENT_FN_NN

STUDENT_LAST_NAME VARCHAR2 25 NOT NULL – STUDENT_LN_NN

STREET_ADDRESS VARCHAR2 50

ZIP_CODE VARCHAR2 5 FOREIGN KEY – ZIP_STUDENT_FK

12

Page 165: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 7: Constraints

IDCGRF002 Activity_4.0_Module7_Constraints.doc © 2009 Accenture. All Rights Reserved.

5) Table Name: SECTION_INFO

Field Name Type Length CONSTRAINT NAME

SECTION_ID NUMBER 8,0 PRIMARY KEY – SECTION_ID_PK

COURSE_NO NUMBER 8,0 FOREIGN KEY – COURSE_SECTION_FK

SECTION_NO NUMBER 3,0 NOT NULL -SECTION_NO_NN

INSTRUCTOR_ID NUMBER 8,0 FOREIGN KEY – INSTRUCTOR_SECTION_FK

LOCATION VARCHAR2 50

CAPACITY NUMBER 3,0

6) Table Name: ENROLLMENT_INFO

Field Name Type Length CONSTRAINT NAME

STUDENT_ID NUMBER 8,0 PRIMARY KEY – (STUDENT_ID,SECTION_ID)

ENROLLMENT_STUD_SECT_PK

FOREIGN KEY-ENROLLMENT_STUDENT_ID_FK

FOREIGN KEY-ENROLLMENT_SECTION_ID_FK

SECTION_ID NUMBER 8,0

ENROLLMENT_DATE DATE

7) Table Name: GRADE_INFO

Field Name Type Length CONSTRAINT NAME

STUDENT_ID NUMBER 8,0 PRIMARY KEY –

(STUDENTID,SECTIONID,GRADE_TYPE_CODE,GRADE_CODE_OCCURANCE)

GRADE_STUD_SECT_TYPE_CODE_PK

FOREIGN KEY-GRADE_STUDENT_ID_FK

FOREIGN KEY-GRADE_SECTION_ID_FK

CHECK - CHK_GRADE_TYPE_CODE CHECK

VALID VALUES FOR GRADE TYPE CODE - FI,HM, MT,PA,PJ,QZ

SECTION_ID NUMBER 8,0

GRADE_TYPE_CODE CHAR 2

GRADE_CODE_OCCURANCE NUMBER 38,0

NUMERIC_GRADE NUMBER 3,0 NUMERIC_GRADE_NN

DEFAULT 0

13

Page 166: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 8: Data Manipulation Language

IDCGRF002 Activity_5.0_Module8_DataManipulationLanguage.doc © 2009 Accenture. All Rights Reserved.

Module 8 Activity 5.0: Inserting records in table

Estimated Completion Time: 15 minutes

Overview This exercise will require participants to insert record in the tables in Oracle SQL PLUS using the SQL language.

Instructions Inserting records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with inserting records in the tables, login using your user name created in Exercise 01 and then proceed to create the constraints on the tables.

Hints 1. Ensure the following while inserting records in the table:

Execute the file C:\RDBMS\Day2\createSchema.sql.

14

Page 167: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 8: Data Manipulation Language

IDCGRF002 Activity_5.0_Module8_DataManipulationLanguage.doc © 2009 Accenture. All Rights Reserved.

Inserting Records

1) Execute the file C:\RDBMS\Day2\createSchema.sql.

15

Page 168: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 8: Data Manipulation Language

IDCGRF002 Activity_5.1_Module8_DataManipulationLanguage.doc © 2009 Accenture. All Rights Reserved.

Module 8 Activity 5.1: Querying records against table

Estimated Completion Time: 120 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01.

Hints 1. Ensure the following while querying the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day2\Queries.sql append.

16

Page 169: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 8: Data Manipulation Language

IDCGRF002 Activity_5.1_Module8_DataManipulationLanguage.doc © 2009 Accenture. All Rights Reserved.

Querying Records

Plain SQL queries

1) Display the structure of the course table. 2) Display the zipcode, city and state. Observe the column heading of state column. If not appearing correctly, give a proper heading. Save the SQL statement in the sql file. C:\RDBMS\Day2\zipquery.sql.

3) Run the zipquery.sql. 4) Display the unique states. 5) Display the student_id, name. Concatenate the first_name and last name. 6) Display the Zipcode, city and state as a single column. Separate the data with a comma. E.g 400050, Mumbai, MH. Give the column heading as Address.

7) Display the description of the course. 8) In the above query also display the cost. 9) Display all the columns of the course_info table. 10) Display the instructor's last name and the zip in which the instructor resides. 11) There are many students who are living in the area, display unique zip's only. 12) Write a select statement to list the first and last names of all students. 13) Write a select statement to list all cities, their states and zip codes.

SELECT using WHERE 1) Display the student_id, section_id and numeric_grade of those students who have the grade

code type as ‘FI’. 2) Display the Zipcode and cities for the state ‘MI’. 3) Display the student details that have enrolled in the month of Jan 1999. Sort the data in the

ascending order of student names. Note: Names should be concatenated. 4) Display the section and the instructor id of the course 10 and 20. Sort the data in the ascending

order of instructor id. 5) Display the student_id, section_id and numeric_grade. Sort the section_id in ascending order

followed by numeric_grade in descending order. 6) Display the course_no, description and cost of the courses. The courses should have the word

‘Intro’. 7) Display the course details whose third from last letter is ‘a’. 8) Display the student names whose student_id is in the range of 300 to 350. 9) Display the course details whose cost ranges from 4000 to 7000. 10) Write a select statement that displays the instructor's first name whose last name is 'Schumer'. 11) Write a select statement that displays the instructor's first name whose last name is not

'Schumer'. 12) Display the course name and cost of those courses whose cost is more than 4000. 13) Display the course name and cost of those courses whose cost is in the range of 3000 and 7000. 14) Display the course name and cost of those courses whose cost is 4000 and 4500. 15) Write a select statement that displays the student's first name and address whose last name

starts with 'S'. 16) Write a select statement that displays the student's first name and address whose last name

contains 'o' as the second letter.

17

Page 170: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 8: Data Manipulation Language

IDCGRF002 Activity_5.1_Module8_DataManipulationLanguage.doc © 2009 Accenture. All Rights Reserved.

17) Write a select statement that displays the instructor's first name whose last name does not start with 'S'.

18) Display the course name and cost of those courses whose cost is in range of 4000 and 4500 and the course name starts with 'I'.

19) Display the course name and cost and prerequisite of those courses whose cost is 2000 and prerequisite is 20 and all courses whose prerequisite is 25.

20) Display the course name and cost and prerequisite of those courses whose cost is 2000 and all records whose prerequisite is 20 and 25.

21) Display the records of the course_info table which have no prerequisite. 22) Write a select statement to list the last names of students living either in zip code 10048, 11102

and 11209. 23) Write a select statement to list the first and last names of instructors with the letter 'i' in any case

in the last name and living in zip code 10025. 24) Write a select statement to list descriptions of courses which have prerequisites and cost is less

than 1100. 25) Write a select statement to list the cost of courses that do not a prerequisite. In the result the cost

should not be repeated. 26) Display the course_no and the coursename who do not a prerequisite. Sort the data on the basis

of coursename. 27) For the above query sort in the descending order of coursename. 28) Write a select statement to list each city in state New York or Connecticut sorted in ascending

order by zipcode. 29) Display the zip, first and last name of students with the last name Graham. Order the result by zip

in descending order and the first name in ascending order. 30) Display the city and state as 1 column. 31) Display the first name of the student. Only the first letter of the first name should be in

uppercase. 32) Write a select statement that displays the instructor's first name followed by comma and a space

which is followed by last_name. The result should be displayed in 1 result set. 33) Display the select statement that displays the cost, add 10 to cost, subtract 20 from cost, multiply

cost by 30 and divide cost by 5. 34) Write a select statement that displays unique numeric grade, half these values and do not

display this value in decimals. This calculation should be displayed as a separate column.

SELECT with TO_CHAR/DECODE/IS NULL

1) Display the cost in the following format for all the courses whose course_no is less than 25.

EX. 4,000

3,500

2) Write a query to format the cost column. The cost displayed should have a leading $ sign followed by a comma to separate the thousands and should display 2 decimals. E.g $2,000.00

3) For those courses having no pre-requisites display data as 'Not Applicable'

4) Display the state as 'New York' for NY, 'New Jersey' for NY and 'Others' for any other state.

18

Page 171: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Aggregate Functions

IDCGRF002 Activity_6.0_Module9_Aggregate.doc © 2009 Accenture. All Rights Reserved.

Module 9 Activity 6.0: Aggregate functions against the table

Estimated Completion Time: 60 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to use the aggregate functions.

Hints 1. Ensure the following while creating the queries on the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\agg.sql append.

19

Page 172: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Aggregate Functions

IDCGRF002 Activity_6.0_Module9_Aggregate.doc © 2009 Accenture. All Rights Reserved.

Aggregate Functions

1) Display the count of records in the course table. 2) Display the total number of records in enrollment table. 3) Display sum of numeric_grade from grade_info. 4) Display the average, total, minimum and maximum numeric grade. 5) Display the count of grade code type. 6) Write a SELECT statement that displays the total number of courses which do not have any pre-requisite.

7) Display the date of the student who got recently enrolled.

Group by and Having Clause

1) Display the count of cities for each state. 2) Display the minimum numeric grade section wise for each student. 3) Display the average numeric grade for each student. 4) Display the count of students enrolled in each section. Display only those sections where the

number of students enrolled is more than 5. 5) Display the average numeric grade for each student and section. The average numeric grade

should be more than 75. 6) For the above query display the data for student_id more than 280. 7) Display each prerequisite and its count from the course_info table. 8) Display student_id and number of courses they are enrolled in. Those students who are enrolled

in more than 2 courses should be displayed. 9) Display the average capacity of each course. 10) For the above query display those courses which have exactly 2 sections.

20

Page 173: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Union-Intersect-Minus

IDCGRF002 Activity_6.1_Module9_Union_Intersect_Minus.doc © 2009 Accenture. All Rights Reserved.

Module 9 Activity 6.1 – Union/Intersect/Minus functions against the table

Estimated Completion Time: 45 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to use the SET operators.

Hints 1. Ensure the following while creating the queries on the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\UnIntMin.sql append.

21

Page 174: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Union-Intersect-Minus

IDCGRF002 Activity_6.1_Module9_Union_Intersect_Minus.doc © 2009 Accenture. All Rights Reserved.

Union/Intersect and Minus

1) Display the first name and last name of both the instructor and student in one result set.

2) Modify the above query to display duplicate names also.

3) Modify the above query to add a column Name to display text as 'Instructor' or 'Student' in each row.

4) Display the instructor id not having any section.

5) Display the course no having section.

6) Display a list of courses and section having no students enrolled. Add a new column called as status that displays text as 'No Student Enrolled'.

7) Display all the zip codes that are present in both the instructor and the student tables.

8) Display the student ids who have enrolled.

22

Page 175: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Subqueries

IDCGRF002 Activity_6.2_Module9_Subqueries.doc © 2009 Accenture. All Rights Reserved.

Module 9 Activity 6.2: Subqueries against the table

Estimated Completion Time: 100 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the subqueries.

Hints 1. Ensure the following while creating the subqueries on the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\subqueries.sql append.

23

Page 176: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Subqueries

IDCGRF002 Activity_6.2_Module9_Subqueries.doc © 2009 Accenture. All Rights Reserved.

Subqueries

Subqueries returning 1 row

1) Display the course_no, description and cost. Those records should be displayed whose cost is equal to the minimum cost.

2) Display the name of the students enrolled in section no 8 and course number 20.

3) Display the student id’s who registered first.

4) Display the course_no and sum of capacity where the total capacity is less than the average capacity.

Subqueries returning multiple rows

1) Display the course number and description whose cost is same as that of the course whose prerequisite is 20.

2) Modify the above query to display the records whose cost is not same as that of the course whose prerequisite is 20.

3) Display the course description and cost of the courses where the capacity is less than or equal to the average capacity and cost is equal to minimum cost.

4) Display the student id and section id who are living in zip 06820.

5) Display the course no and description taught by instructor Frank Hank.

6) Display the students enrolled in course 'Introduction to Java'.

7) Display the last_name and enrollment_date from student_info of those students who have enrolled on 22nd of Jan 2001.

8) Display the student names who have enrolled on Tuesday.

Co-related subqueries with exists

1) Display the student id and section id along with numeric grade of those students where the numeric grade is less than the average numeric grade for that section.

2) Display the instructor details only if the instructor teaches a section.

3) Display the details of those instructors who do not teach a section.

4) Display the names of the students who are enrolled.

5) Display the courses enrolled by the students.

6) Display the courses who do not have sections.

7) Display the sections in which no student is enrolled.

24

Page 177: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Subqueries

IDCGRF002 Activity_6.2_Module9_Subqueries.doc © 2009 Accenture. All Rights Reserved.

Subqueries using Any and All

1) Display the section id and numeric grade whose numeric grade is less then the average numeric grade of either of student id 280 and 283.

2) Display the section id and numeric grade whose numeric grade is less then the average numeric grade of both student id 280 and 283.

25

Page 178: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Joins

IDCGRF002 Activity_6.3_Module9_Joins.doc © 2009 Accenture. All Rights Reserved.

Module 9 Activity 6.3 – Joins against the table

Estimated Completion Time: 150 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the joins on the tables.

Hints 1. Ensure the following while creating the joins on the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\joins.sql append.

26

Page 179: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Joins

IDCGRF002 Activity_6.3_Module9_Joins.doc © 2009 Accenture. All Rights Reserved.

Joins

Equi Join

1) Display the course and the section information.

2) Display the instructor details along with the city and the state that they live in.

3) Display the student details of all students and city and state. Sort the result on the basis of zip code.

4) Write a query to display the first and last names of only the enrolled students and order on the basis of last name in descending order.

5) Display the zip, city and state and instructor names who are living in state 'NY'.

6) Write a query to display the student number, course number, enrollment date and section id for students who are enrolled in course number 20 on January 30 2000.

7) Display the course number, description, cost, section id, and the instructor names who are teaching the course.

8) Display the student number, section id and grade type code along with numeric grade and the month of enroll date for student id =220 and section id =119.

9) Display the student id, course number and section number of enrolled students where the instructor of the section lives in zip code 10025. Also, the course should not have any pre-requisites.

10) Display the instructor details along with the city, state who are teaching the section 2.

11) Display the list of enrolled student numbers who are living in state 'CT'.

12) Write a query to display the details of student 'Fenny Crawford' for section id 86.

13) Display the final examination numeric grade and details of all enrolled students living in state 'NY' of course number 300.

14) Display the student number, section id, numeric grade and last name who received grade less than 75 or less in class project.

Outer Join

1) Display the course number, description and pre-requisite along with section id. Those courses who do not have sections defined should also be displayed.

2) For the above query also include courses where no instructor is assigned.

3) For students with id's 102 and 301 display the student id, section id and numeric grade and the grade type. Display the details even if the student is not enrolled or has not received any grade.

27

Page 180: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 9: Joins

IDCGRF002 Activity_6.3_Module9_Joins.doc © 2009 Accenture. All Rights Reserved.

Self Join

1) Many courses have pre-requisite. Display the course no and the description along with the pre-requisite and the description.

e.g. - 20 Intro to Java 10 Java Programming where 20 is the course no and 10 is the pre-requisite.

2) For the students who have enrolled in section id 86 find the students who have received a lower grade in their final examination than in their mid term. In the result set, display the student id, grade type code and numeric grade.

e.g. .studentid grade_type numeric_grade grade_type numeric_grade

100 FI 70 MI 75

3) Display the names of the students living at the same address and their zipcode.

28

Page 181: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 10: Views

IDCGRF002 Activity_7.0_Module10_Views.doc © 2009 Accenture. All Rights Reserved.

Module 10 Activity 7.0: Views against the table

Estimated Completion Time: 45 minutes

Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.

Instructions Querying records in tables should be done in Oracle SQL PLUS.

1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the views on the tables.

Hints 1. Ensure the following while creating the views on the table:

Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\views.sql append.

29

Page 182: Introduction to RDBMS Participant Guide

Introduction To RDBMS and SQL Module 10: Views

IDCGRF002 Activity_7.0_Module10_Views.doc © 2009 Accenture. All Rights Reserved.

Views

1) Create a view named stud_enroll that displays student id, lastname and number of sections that the student is enrolled.

2) Create a view named stud_zip that has stduent_id, names of students (first and last name), city and state. In this view students not living in state New Jersey, New York and Connecticut should be displayed.

3) Create a view named lowcost_course that has the course number, course name and cost less than 4000.

4) Issue an insert command on this view and insert cost more than 4000 and check if the record gets inserted.

5) Modify the view to include the WITH CHECK OPTION and try inserting the record again.

6) Modify the above view in such a way that it should not allow you to perform any DML statement.

30