You are on page 1of 182

Introduction to RDBMS & SQL

Course Map

WEEK 1
9:00 - 9:15 9:15 - 9:30 9:30 - 9:45 9:45 10:00 10:00 10:15 10:15 10:30 10:30 10:45 10:45 11:00 11:00 11:15 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 2:00 - 2:15 2:15 - 2:30 2:30 - 2:45 2:45 - 3:00 3:00 - 3:15 3:15 - 3:30 3:30 - 3:45 3:45 - 4:00 4:00 - 4:15 4:15 - 4:30 4:30 - 4:45 4:45 - 5:00 5:00 - 5:15 5:15 - 5:30 5:30 - 5:45 5:45 - 6:00

Day 1 M1: Introduction 1.1 School Opening (1:00)

Day 2 Morning Review

Day 3 Morning Review

M8: Constraints (0:15) Activity 5 (0:45) M6: Data Definition Language (1:00) Activity 3(0:45)

M2 : Introduction to RDBMS (1:00)

M9: Aggregate Functions, Joins and Sub queries (2:30) Activity (0:15) M3 : The E-R Model of the Database ( 1:45) Activity (0:15) M7 : Data Manipulation Language (2:00)

LUNCH Knowledge Check 1 & 2 M4 : Database Design Techniques (0:45) Activity 2 (0:15)

LUNCH

LUNCH

M7 : Data Manipulation Language (continued) Activity 4 (2:30)

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

M5: Introduction to SQL (1:00)

Knowledge Check 3 & 4 Team Buliding Activity Day 1 Summary

Knowledge Check 5 & 6 M8: Constraints (0:45) Day 2 Summary

M10: Views (0:45) Knowledge Check 7, 8 & 9 Day 3 Summary

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

CourseMap.doc

Introduction to RDBMS and SQL

1_Course Overview.ppt

Introduction to RDBMS and SQL


Module 1: Course Overview

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

Agenda
Welcome Objectives Introductions Expectations of Participants Ground Rules Course Objectives Course Approach and Outline

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Welcome
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 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 DML DCL etc.

Copyright 2009 Accenture All Rights Reserved.

Objectives
At the end of this presentation, you should be able to: Understand the expectations and ground rules 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Introductions
Name Your self assessment based on:
Wh I h Why Im 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 Techniques. T h i

One interesting note about yourself (e.g., a hobby or talent) Your expectations from the course
Copyright 2009 Accenture All Rights Reserved.

Expectations of participants
You will work as a team to complete the deliverables of the course. You should be resourceful and creative Utilize the tools creative. and materials that have been provided. Participate in discussions, ask questions to clarify if necessary.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Course Objectives
Participants who have completed this school, will be able to: List the types of data used in a Oracle database and yp explain 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 Language Language Describe the database constraints Describe Aggregate functions, joins and sub queries, Views
Copyright 2009 Accenture All Rights Reserved.

Course Approach
Learn by Doing
Hands-on programming

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 Environment
U available resources (i Use il bl (i.e., online/offline materials, h li / ffli t i l human resources, etc) Encourage research and learning on your own

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Course Approach (Cont.)


Teaching Method
This is not a lecture course! Lessons serve only as guideposts and reminders and are not reminders, expected to be complete classes on these topics Instructors serve mainly as facilitators and knowledge coaches

Performance Evaluation
Each participant will be evaluated

Participate P ti i t
Dont just listen to discussions, interact! If in doubt, ask questions to clarify. Spot problems and suggest alternatives or workarounds.

Copyright 2009 Accenture All Rights Reserved.

Course Approach (Cont.)


Teamwork
Cooperate, coordinate, collaborate! Work together to complete the deliverables for the course.

Be resourceful
Dont ask for answers or solutions, find them! The course environment provides all the necessary tools and materials t l d t i l to learn, utilize th tili them well. ll

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Course Approach - Learn By Doing


One of the tenets of the school is that the best way to learn is to take a more active, hands-on approach. hands on The majority of the activities consist of participants working to complete the appropriate deliverables. The faculty will act as knowledge coaches and technical consultants. This course encourages participants to be resourceful and inquisitive.
Copyright 2009 Accenture All Rights Reserved.

11

Course Approach - Tiers of Support


Level 1 You
Try to resolve the problem on your own. 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


Try to resolve problem with other teams. Share tips, guides, resolutions, workarounds

Level 4 Faculty
Try to resolve problem with your faculty members.
Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Course Map
Day 1 Course Introduction Module 1: School Opening Module 2: Introduction to RDBMS Module 3: Database Design Techniques Day 2 M6: Data Definition Language M7:Constraints Day 3 M9: Aggregate Functions, Joins and Subqueries

Lunch Module 4:The E-R Model of the Database

Lunch M7: Constraints (cont) M8: Data Manipulation Language

Lunch M9: Aggregate Functions, Joins and Sub queries (cont) Module 10: Views

Module 5: Introduction to SQL

Copyright 2009 Accenture All Rights Reserved.

13

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. 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.
Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Ground Rules (Cont.)


No unauthorized software especially games should be installed in workstations Landline is strictly for business purposes or emergency calls only Observe proper dress code Proper use of Accenture resources and facilities (e.g. desktops, training room, pantry) Maintain confidentiality of company and client-related matters
Copyright 2009 Accenture All Rights Reserved.

15

Training Resources
Be aware there will be Knowledge Checks (quizzes) to test your understanding of the information presented. 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. Get to know your fellow students and the resources they offer. Tell your fellow students about your strengths and the resources you bring.
16

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

1_Course Overview.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

17

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Introduction to RDBMS and SQL


Module 2: Introduction to RDBMS

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

Code #IDCGF002

Agenda
Data and Storage. Drawbacks with File Systems. Introduction to DBMS and its benefits. Multi-tier Architecture Data Models Hierarchical Model. Network Model. Relational Data Model. Relational Data Model concepts. Codds 12 rules.
Accenture 2009 All Rights Reserved
2

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

10

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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

Accenture 2009 All Rights Reserved

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 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.
Accenture 2009 All Rights Reserved
4

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

11

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Drawbacks with File Systems


Drawbacks Data Dependency Description Data dependency means that the application program is dependant on the data. data So any modifications made on the data affects the application program using it, forcing it to be rewritten. Redundancy is the repetition of data. Data duplication was allowed in the traditional approach. Data redundancy caused data inconsistency to occur in the data. Data Sharing was difficult or impossible with traditional systems. Data stored on the computer must be secured. It was difficult to enforce independent information security in traditional approach. 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.
5

Redundancy

Sharing Security

Transaction Control

Accenture 2009 All Rights Reserved

Introduction to DBMS
DBMS is Data Base Management System. It 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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

12

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Data Concurrency Databases allow multiple users to access the same database simultaneously. Data Redundancy A properly set-up database minimizes data redundancy. It will avoid data repetition in the databases. Data Validity Databases allow you to set up rules that ensure that data remains consistent when add or modify d t dif data. Data Sharing Sharing 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 Security One 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 databases 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 specific as to what a user can do.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

13

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

14

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

15

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Two tier architecture Two 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 process development, 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 the general, 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 connectivity between tiers can be dynamically changed depending upon the user's request for data and services.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

16

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

17

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

18

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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 by IBM. b 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. Row is known as a tuple. Column is known as an attribute. Dr. Codd modified his model by defining 12 rules (Codds Rules), that a DBMS must meet in order to be considered a relational database.
Accenture 2009 All Rights Reserved
14

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

19

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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. The presentation of data as tables is a logical construct - it is independent of the way the data is physically stored on disk.

Accenture 2009 All Rights Reserved

15

Basic Terms and Definitions (Contd )


The two most prominent characteristics of a relational database are 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 o att bute) represents t e c a acte st cs co u ( e d or attribute) ep ese ts the characteristics of an item (e.g., the customer's name or phone number). A relationship (join) is a logical link between two tables.

Accenture 2009 All Rights Reserved

16

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

20

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Codds 12 rules
Rule No.
#1 #2

Rule
Information rule Guaranteed access Rule Systematic treatment of null values Dynamic on-line catalog based on the relational model l ti l d l

Description
Database must consist of tables related to each other and data should be stored in the form of tables only. 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. A Null is an unknown value and every database must have a provision for storing NULL values. In addition to user data, a relational database contains data about itself, there are 2 types of tables. 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.

#3 #4

Accenture 2009 All Rights Reserved

17

Codds 12 rules (Contd)


Rule No. #5 Rule Description

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. 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 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.

#6

View Updating Rule

Accenture 2009 All Rights Reserved

18

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

21

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

Codds 12 rules (Contd)


Rule No.
#7

Rule
High-level i Hi h l l insert, t update and delete

Description
Rows are treated as sets for data manipulation operations. R t t d t f d t i l ti ti A relational database should support basic operations like subqueries, 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). Any changes in the data storage should not affect the application that accesses it. 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. 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).
19

#8

Physical Data Independence Logical Data Independence Integrity Independence

#9

# 10

Accenture 2009 All Rights Reserved

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

22

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

0. Foundation Rule Interestingly 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 might means 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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

23

Introduction to RDBMS and SQL

2_IntroductionToRDBMS.ppt

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 doesnt corrupt the database. Databases are part of a larger software application called a database management system (DBMS). A database to be called as RDBMS, should adhere to Codds Rules.

Accenture 2009 All Rights Reserved

21

Questions and Comments What questions or comments do you have? ?

Accenture 2009 All Rights Reserved

22

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

24

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Introduction to RDBMS and SQL


Module 3: Database Design Techniques

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 Form. Transitive Dependency. Third Normal Form. Denormalization.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

25

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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. It removes duplicated data from the relational tables. Normalization theory is based on the concepts of normal forms.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

26

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

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 ( st o a o (1NF) ) Third Normal Form (3NF) Fourth Normal Form (4NF) Seco d o a o (2NF) Second Normal Form ( ) Boyce Codd Normal Form (BCNF) Fifth Normal Form (5NF)

The Third Normal Form is quite sufficient for most business database design purposes.
Copyright 2009 Accenture All Rights Reserved.

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

Watches

3000

M1001

Aqua Marine

D1001

Marine World

10010 10011

12-May-07

20

Pens

1000

M1002

Magnum

D1002

Water World

10011 10012

14-May-07

10

Mobiles

4000

M1003

Coral

D1003

Alpha Company

10010 10012

16-May-07

15

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

27

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

A design is in the first normal form if:


There are no repeating groups All the key attributes are defined All 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 E101 DEPT System Projecode p27 p51 p20 E305 Sales p27 p22 E508 Admin p51 p27 Hours 90 101 60 109 98 null 72

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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

28

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Content continued: By applying the 1NF definition to the Project table, you arrive at the following table. ECODE E101 E101 E101 E305 E305 E508 E508 DEPT Systems S t Systems Systems Sales Sales Admin Admin Projecode p27 p51 51 p20 p27 p22 p51 p27 Hours 90 101 60 109 98 Null 72

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

29

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

30

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Consider the example: EmployeeID E100 E101 E102 E103 E104 E105 EmpName Reshma Kshitij Asha Shivraj Neeta Naveen Loc MDC DDC PDC HDC CDC BDC -------------------------------------------------------------------------------------------------

p , p y p y p y In the example, Employee Name has a functional dependency on Employee ID, 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

31

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Content Continued:

Find the functional dependency between the attributes.

CourseCode

CourseName

Duration

-----------------------------------------------------------------------------------------C_101 C_102 C_103 C_104 C 104 C_105 Unix Oracle SQL Oracle-PLSQL C C++ 16 24 32 24 40

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

32

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

33

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

34

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Let us take another example to understand Full functional dependence and Partial functional dependence. Suppose we have a transaction relation as shown 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) Cname i not f ll f C is t fully functionally d ti ll dependent on (C# P# D t ) it i only d t (C#, P#, Date), is l partially dependent on it (and similarly for Ccity and Cphone).

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

35

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

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 or A 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 Second form. 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

36

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

Example : Lets 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

37

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

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 Form A relational table is in the fourth normal form (4NF) if it is in BCNF and all multivalued dependencies are also functional dependencies. Fifth Normal Form A table is in the fifth normal form (5NF) if it cannot have a lossless decomposition into any number of smaller tables.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

38

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

39

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

40

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

In the example the relation Item, item_id is the primary key. The item_id determines the values for all the other fields Item_Desc, Price, manufacturer_id, Distributor_id.Manufacturer name is dependent on manufacturer_id which is not a candidate key. The attribute manufacturer_name is dependent on the manufacturer_id and manufacturer_id is dependent on the item_id. This is transitive dependency. The manufacturer_id is not a candidate key since the same manufacturer can supply many items. Same is the case with Distributor_id and Distributor_name. The attribute distributor_name is dependent on the Distributor_id and Distributor_id is y dependent on the item_id. This is transitive dependency. The Distributor_id is not a candidate key since the same distributor can supply many items.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

41

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

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 modeling 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. 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.

Copyright 2009 Accenture All Rights Reserved.

21

Denormalization (Contd)

Copyright 2009 Accenture All Rights Reserved.

22

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

42

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

3: Database Design Techniques Activity


Input documents: Activity_1.0_Module3_Datab aseDesignTechniques.doc Output document: Activity_1.0_Module3_Datab aseDesignTechniquesOutput .doc

60 Minutes
Copyright 2009 Accenture All Rights Reserved.

23

3: Database Design Techniques Key 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. Typically a database will be in Third Normal Form.

Copyright 2009 Accenture All Rights Reserved.

24

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

43

Introduction to RDBMS and SQL

3_DatabaseDesignTechniques.ppt

3: Database Design Techniques Key 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 key 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 field is fi ld i not a candidate k did key.

Copyright 2009 Accenture All Rights Reserved.

25

3: Database Design Techniques Questions and Comments What questions or comments do you have? ?

Copyright 2009 Accenture All Rights Reserved.

26

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

44

Introduction to RDBMS and SQL

4_ERModel.ppt

Introduction to RDBMS and SQL


Module 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, Entities Attributes and Relationships Relationships. Mapping cardinalities
One to one. One to many. Many to one. Many to many. Primary Key. Candidate Keys. Alternate Key. Foreign Key. Composite key.
2

Keys

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

45

Introduction to RDBMS and SQL

4_ERModel.ppt

Learning Objectives
Understand the Entity-Relationship (ER) model Understand 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.

E-R Model
E-R model means Entity Relationship Model. j It describes basic objects called entities as understood in 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 the System E-R model facilitates easy design of the database to represent the logical structure of the database

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

46

Introduction to RDBMS and SQL

4_ERModel.ppt

Entity Relationship Diagram (ERD)


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

ERD

Definition An entity is an any object or activity which an enterprise records. Instantiated from an object object.

Symbol

Property

Attribute

Relationship

Relationship

Association between two dependent objects.

Copyright 2009 Accenture All Rights Reserved.

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

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

Employee

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

47

Introduction to RDBMS and SQL

4_ERModel.ppt

Attributes
Attributes are the significant properties or y p g characteristics of an entity that help in describing the entity and provide the information needed to interact with it or use it.
Birth date First Age Middle Name Employee SSN Last Projects

Copyright 2009 Accenture All Rights Reserved.

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

Dept

Assigned

DeptHead

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

48

Introduction to RDBMS and SQL

4_ERModel.ppt

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. One to many. Many to one. Many to Many.
Copyright 2009 Accenture All Rights Reserved.

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:

EMPLOYEE
Entity A

WORKSTATION
Entity B

Represents 1

Every Employee is assigned to One Workstation.

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


Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

49

Introduction to RDBMS and SQL

4_ERModel.ppt

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 COURSE is taught by a single LECTURER; A STUDENT may enroll for many COURSES offered by . . . . .

different DEPARTMENTS.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

50

Introduction to RDBMS and SQL

4_ERModel.ppt

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:

State
Entity A

City
Entity B

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.
Copyright 2009 Accenture All Rights Reserved.

12

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:
STUDENT
Entity A

COURSE
Entity B

A Student can enroll for more than one course And each course. course will contain more than one student Example 2: Many products purchased by many customers

Copyright 2009 Accenture All Rights Reserved.

13

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

51

Introduction to RDBMS and SQL

4_ERModel.ppt

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_OF between LECTURER & DEPARTMENT; N:1 relationship IS_IN between LECTURER & DEPARTMENT 1:N relationship OFFERS between DEPARTMENT & COURSE; M:N relationship ENROLLS between STUDENT & COURSE 1:N l ti 1 N relationship TEACHES hi between LECTURER & COURSE.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

52

Introduction to RDBMS and SQL

4_ERModel.ppt

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 Alternate Key Composite key

Copyright 2009 Accenture All Rights Reserved.

15

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

Emp No 1000 2000 3000


Copyright 2009 Accenture All Rights Reserved.

Name Venkat Ramesh Poornima

Designation SSE Team Leader ASE


16

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

53

Introduction to RDBMS and SQL

4_ERModel.ppt

Candidate key
Candidate key is a Key that helps to uniquely identify row in a table It could potentially serve as the primary Key.
Primary Key The example shows the columns that either EmpNo or WS# can be identified as 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. Copyright 2009 Accenture All Rights Reserved.
Emp No 4561 4562 4563 WS# WS.A.1 WS.B.2 WS.C.3 WS C 3 PrjName Greenfield Am Express Avanande A d

Candidate Key (All rows are Unique)

17

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 4561 4562 4563 WS# WS.A.1 WS.B.2 WS.C.3 PrjName Greenfield Am Express 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.
Copyright 2009 Accenture All Rights Reserved.

18

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

54

Introduction to RDBMS and SQL

4_ERModel.ppt

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

Foreign Key
Foreign key :It provides relationship between table in the 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 Referential I t R f ti l Integrity it

Copyright 2009 Accenture All Rights Reserved.

20

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

55

Introduction to RDBMS and SQL

4_ERModel.ppt

Composite Key
A key composed of more then one column is p y y called composite key or concatenated Key
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

4563

AS14

13/11/2005

13/11/2005

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


Copyright 2009 Accenture All Rights Reserved.

21

Activity
Input documents: Activity_2.0_Module4_ER Model.doc Output document: Activity_2.0_Module4_ER ModelOutput.doc

60 Minutes
Copyright 2009 Accenture All Rights Reserved.

22

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

56

Introduction to RDBMS and SQL

4_ERModel.ppt

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. y y q y Candidate key is a Key that uniquely identifies row in a table. Key Composed more then one column is called composite key or concatenated Key
Copyright 2009 Accenture All Rights Reserved.

23

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

24

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

57

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

Introduction to RDBMS and SQL


Module 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

58

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

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

Copyright 2009 Accenture All Rights Reserved.

Structured Query Language (SQL)


SQL is Structured Query Language. It is a special-purpose, nonprocedural language that supports the d fi iti t th definition, manipulation, and control of i l ti d t l f 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. SQL was designed by IBM during 1970s. Word SQL is derived from Sequel.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

59

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

Structured Query Language (SQL) (Contd)


Depending on the functionality SQL is classified as follows:
Data Definition Lang age (DDL) Language Data modification Language (DML) Data Control Language (DCL Transaction Control Language (TCL)

Copyright 2009 Accenture All Rights Reserved.

Sub-languages of SQL
SQL is segregated into DDL,DML, DCL and TCL. Data t i D t retrieval : SELECT l
DDL CREATE ALTER DROP TRUNCATE DML INSERT UPDATE DELETE DCL GRANT REVOKE COMMIT ROLLBACK SAVEPOINT TCL

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

60

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

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 the structure of an object and also to drop the object created.The concept Relating to Data Definition Language are explained in paragraph. DDL is a language used by a database management system which allows users to define the database and its objects, specifying data types, structures and constraints 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 organized by the appropriate data model or manipulate data as

DML Manipulation commands are the most frequently used SQL commands. They are used to query and Manipulate existing objects like tables

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

61

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

Data Manipulation Language (DML)


It is a language that enables users to access or manipulate data as organized by the appropriate data model. model 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.

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 (insert, others, 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.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

62

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

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. 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.
Copyright 2009 Accenture All Rights Reserved.

10

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 DCL Transaction Control

Copyright 2009 Accenture All Rights Reserved.

11

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

63

Introduction to RDBMS and SQL

5_IntroductionToSQL.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

64

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Introduction to RDBMS and SQL


Module 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 creating, altering and deleting a table.

Accenture 2009 All Rights Reserved

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

65

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

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

Accenture 2009 All Rights Reserved

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

66

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

67

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Data types
Data Type
BLOB

Description
Binary L Bi Large Obj t Objects. It stores Bi t Binary Data like storing Images Character Large Object. It stores Character Data like large documents in any character set. Binary data stored in an external file outside of oracle database Is a 64 base number system representing th unique address of a ti the i dd f row in its table. 4 GB

Max.Size

CLOB

4 GB

BFILE

4 GB

ROWID

-N/A (as it is internally managed b th oracle system). d by the l t )

Accenture 2009 All Rights Reserved

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. scott Syntax to create the user:

Create user <username>


identified by <password>;

Note: To create a new user, you should have the DBA or create user privilege. You can also d thi b t i il Y l do this by logging in as System or sys.

Ex: Create user sam identified by admin;


Accenture 2009 All Rights Reserved
6

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

68

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

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. p Example :

alter user sam identified by admin;

Accenture 2009 All Rights Reserved

Dropping a User
The DBA can drop or remove the user from the oracle database. Syntax: Drop user <username>; Example: drop user sam; The user is dropped from the oracle database.
8

Accenture 2009 All Rights Reserved

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

69

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

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>; Note: Grant is a DCL command used to grant the privilege to a user.

Accenture 2009 All Rights Reserved

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: SQL>grant connect, resource to SAM;

Accenture 2009 All Rights Reserved

10

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

70

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Revoking the Privileges:


A privilege can be revoked by using Revoke. It is a DCL command. Syntax: revoke <privilege> from <username>; Example: revoke resource from sam; Note: to revoke the privilege the user should be a dba or have dba privilege.
Accenture 2009 All Rights Reserved
11

6: Data Definition Language Activity (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 class l

10 Minutes
Accenture 2009 All Rights Reserved
12

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

71

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Creating Table
Syntax CREATE TABLE table_name ( name_of_column column_datatype, name of column column datatype [name_of_column column_datatype,] . . . . . . . . . )

Example E l

CREATE TABLE dept info dept_info ( Deptno Number(2), Dname Varchar2(20), Loc Varchar2(20), );
13

Accenture 2009 All Rights Reserved

6: Data Definition Language Activity (2 of 3)


Input documents:
Activity_3.0_Module6_DataDefi nationLanguage.doc ti L d

Output documents:
Activity_3.0_Module6_DataDefi nationLanguageOutput.doc

60 Minutes
Accenture 2009 All Rights Reserved
14

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

72

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Alter Table Statement


Alter command is used to add, modify and drop columns It is used To add constraints To add a new column
Syntax: y ALTER TABLE table_name ADD name of field data type; name_of_field data_type; ALTER TABLE dept_info ADD state varchar2(2);

Example:

Accenture 2009 All Rights Reserved

15

Alter Table Statement


Syntax to Modify Column : ALTER TABLE table_name MODIFY name_of_field data_type;

Example:

ALTER TABLE dept_info MODIFY dname varchar2(25);

ALTER TABLE table_name Syntax to name_of_field; Drop column DROP COLUMN name of field; D l

Example: ALTER TABLE Train_times


DROP COLUMN state;

Accenture 2009 All Rights Reserved

16

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

73

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

6: Data Definition Language Activity (3 of 3)


Input documents:
Activity_3.1_Module6_DataDefi nationLanguage.doc ti L d

Output documents:
Activity_3.1_Module6_DataDefi nationLanguageOutput.doc

45 Minutes
Accenture 2009 All Rights Reserved
17

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; 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
Accenture 2009 All Rights Reserved
18

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

74

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

To Remove Table

DROP is used to remove a table. Syntax DROP TABLE table_name Example: DROP TABLE dept_info

Accenture 2009 All Rights Reserved

19

6: Data Definition Language Question:


What is the difference between truncate and the delete command?

Accenture 2009 All Rights Reserved

20

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

75

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

6: Data Definition Language Key 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. Truncate command is used for deleting the rows from a specified table. DROP is used to drop of a Table.
Accenture 2009 All Rights Reserved
21

6: Data Definition Language Key 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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

76

Introduction to RDBMS and SQL

6_DataDefinitionLanguage.ppt

Questions/ Comments
What questions or comments do you have?

Accenture 2009 All Rights Reserved

23

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

77

Introduction to RDBMS and SQL

7_Constraints.ppt

Introduction to RDBMS and SQL Module 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 Understand how to add default value to a column

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

78

Introduction to RDBMS and SQL

7_Constraints.ppt

Agenda
Constraints Primary Key Constraint Foreign Key Constraint UNIQUE constraint CHECK constraint NOT NULL Constraint Default Defa lt

Copyright 2009 Accenture All Rights Reserved.

Constraints
Constraint is a rule or set of rules that are applied to a column or combination of columns 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 without the need to write an external program.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

79

Introduction to RDBMS and SQL

7_Constraints.ppt

Types of Constraints
Different Types of Constraints are as below Primary key Foreign key Check Unique Not null
Constraints can be created at the time of creating the table using CREATE TABLE or after creating the table using ALTER TABLE.

Copyright 2009 Accenture All Rights Reserved.

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 constraints 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))

The above example creates the EMP_INFO table by adding a primary key constraint PK_EMPNO on the column EMPNO.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

80

Introduction to RDBMS and SQL

7_Constraints.ppt

Primary Key Constraint (Contd)


Example- Create and modify the EMP_INFO1 table by adding a primary key constraint PK_EMPNO1 on the column EMPNO EMPNO.

Example
The example creates and modifies the EMP_INFO1 table by adding a primary key constraint PK_EMPNO1 on the column EMPNO EMPNO.
It also modifies the DEPT_INFO table with the primary key PK_DEPTNO on the deptno column.
Copyright 2009 Accenture All Rights Reserved.

CREATE TABLE EMP_INFO1 (EMPNO NUMBER(4), ENAME VARCHAR2(20), DEPTNO NUMBER (2)) ALTER TABLE EMP_INFO1 ADD CONSTRAINT PK EMPNO1 PRIMARY PK_EMPNO1 KEY (EmpNo); ALTER TABLE DEPT_INFO ADD CONSTRAINT PK_DEPTNO PRIMARY KEY (DEPTNO);
7

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 through Foreign Key constraint. Example- create a table EMP_INFO2 to add a foreign key constraint: The example adds a CREATE TABLE EMP_INFO2 (EMPNO NUMBER(4) CONSTRAINT foreign key constraint PK_EMPNO2 PRIMARY KEY, FK_DEPTNO1 to the ENAME VARCHAR2(20) , DEPTNO EMP_INFO2 table on the CONSTRAINT FK_DEPTNO1 deptno column which REFERENCES DEPT_INFO references DEPTNO -the (DEPTNO)) primary key of the DEPT_INFO Table.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

81

Introduction to RDBMS and SQL

7_Constraints.ppt

Foreign Key Constraint (Contd)


Example- Modify the EMP_INFO1 table by adding a foreign key constraint FK_DEPTNO1 on the column DEPTNO:

Example :

ALTER TABLE EMP_INFO1 ADD CONSTRAINT FK_DEPTNO2 FOREIGN KEY(DEPTNO) REFERENCES DEPT_INFO(DEPTNO);

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.
9

Copyright 2009 Accenture All Rights Reserved.

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 it, 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. The example adds a CREATE TABLE EMP_SAL unique key q y (EMPNO NUMBER(4), NUMBER(4) constraint UK_ACTNO ENAME VARCHAR2(20), on the ACTNO ACTNO NUMBER (8) CONSTRAINT columns of the UK_ACTNO UNIQUE, EMP_SAL table.
JOB VARCHAR2(20), HIREDATE DATE)

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

82

Introduction to RDBMS and SQL

7_Constraints.ppt

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);

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

Copyright 2009 Accenture All Rights Reserved.

11

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 column, that column will contain only values specified in that domain.

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

83

Introduction to RDBMS and SQL

7_Constraints.ppt

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. ALTER TABLE EMP_SAL add CONSTRAINT CHK_JOB CHECK (job IN ('ANALYST', 'CLERK'))
Copyright 2009 Accenture All Rights Reserved.

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

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 constraint. Example : CREATE TABLE PRODUCTS (PRODUCT_NO NUMBER(2) CONSTRAINT NN_PROFNO NOT NULL, NAME VARCHAR2(40) CONSTRAINT ( ) 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.
Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

84

Introduction to RDBMS and SQL

7_Constraints.ppt

Removing Constraints
A constraint can be removed as shown below Example :
ALTER TABLE EMP_INFO DROP CONSTRAINT PK_EMPNO

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

Copyright 2009 Accenture All Rights Reserved.

15

Default
The default keyword is assigned to a column of a table at the time of creating a table or altering it. y pp The value in the default keyword is applied when no value is 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) (PRODUCT_NO,NAME) VALUES(1, 'PENS')
The above example adds a default value of MH into the state field as no explicit value is provided while inserting.
Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

85

Introduction to RDBMS and SQL

7_Constraints.ppt

7: Constraints

Activity
Input documents: Activity_4.0_Module7_Constr aints.doc Output : Activity_4.0_Module7_Constr aintsOutput.doc

45 Minutes
Copyright 2009 Accenture All Rights Reserved.

17

Key Points Constraint is a rule or set of rules that apply to a column or combination of columns C Constraints ensure data integrity Important constraints are Primary Key Foreign Key CHECK UNIQUE NOT NULL

Copyright 2009 Accenture All Rights Reserved.

18

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

86

Introduction to RDBMS and SQL

7_Constraints.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

19

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

87

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Introduction to RDBMS and 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 Objectives
At 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, Char Number and Date Functions Handling NULL data using NVL Understanding DECODE function Understand the use of ESCAPE sequence and SPOOL option
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

88

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Module 8: Agenda
Inserting New Data Updating Existing Data Deleting Existing Data Retrieving data using SELECT Basic SELECT statement Filtering rows using WHERE clause Operators and Operator Precedence Introducing NULL Data Using Aliases g Sorting Information TO_CHAR, TO_NUMBER, TO_DATE functions NVL function DECODE function ESCAPE sequence and SPOOL option
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

89

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Table Structure for Dept table is given below: DeptNo Number(2), DNAME VARCHAR2(25), Loc Varchar2(20), State varchar2(2);

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

90

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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 ; state=MH; It will update all the state as KANPUR from the dept table. UPDATE Dept SET state=MHWHERE DeptNo=1; It will update the state as a MH where DEPTNO is 1

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

91

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

92

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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 rows From 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 From where clause. 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

93

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Deleting Existing Data (Contd)


Syntax for deleting all the rows DELETE FROM <table_name> Example: DELETE FROM DEPT;

Copyright 2009 Accenture All Rights Reserved.

8: Data Manipulation Language

Activity (1 of 2)
Input documents: Activity_5.0_Module8_DataM anipulationLanguage.doc C:\RDBMS\Day2\createSche ma.sql Output : Execute the sql file mentioned above ti d b

15 Minutes
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

94

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Retrieving Columns
SELECT statement is used to retrieve data from the table It can be used to retrieve a column or multiple columns from a table. E Example: l

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 SELECT DNAME, LOC FROM DEPT; * is used to retrieve all columns from the table SELECT * from DEPT;
Copyright 2009 Accenture All Rights Reserved.

10

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 y column though ALL is not specified

Copyright 2009 Accenture All Rights Reserved.

11

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

95

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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.

12

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 get only the data which is required. Syntax : SELECT COL1,COL2,.........FROM TABLE_NAME WHERE < SEARCH CONDITION>; SELECT EMPNO,ENAME,DEPTNO FROM EMP WHERE JOB=ANALYST;

Example:

Sample output

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

Copyright 2009 Accenture All Rights Reserved.

13

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

96

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Operators in WHERE Clause


Operators can be used with WHERE clause Operator O t Description D i ti

<,>,<=,>=,=,<> It is used to compare values or != IN It selects from a list of values BETWEEN NULL LIKE
Copyright 2009 Accenture All Rights Reserved.

Selects from a range of values Compares with Null values Compares with the pattern
14

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 Relational Operators are: = , < , > , <= , >= , != or < > Example: To retrieve all the EMPNO,ENAME columns which belong to the DEPTNO 10 : Sample output SELECT EMPNO,ENAME FROM EMP EMPNO ENAME ===================== WHERE DEPTNO = 10;
7782 CLARK 7839 7934 KING MILLER

Copyright 2009 Accenture All Rights Reserved.

15

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

97

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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 a li t which contains multiple values t b Inclusive list is list hi h t i lti l l 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: SELECT EMPNO,ENAME FROM EMP WHERE JOB IN (MANAGER ,ANALYST);
Copyright 2009 Accenture All Rights Reserved.

Sample Output

EMPNO ENAME ================ 7566 JONES 7698 BLAKE 7782 CLARK 7788 SCOTT 7902 FORD
16

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 >= <= BETWEEN operator can be modified using AND

Example: To get EMPNO,ENAME,JOB,SAL where salary is in the range 1000 to 2000 (inclusive) : Sample output
SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL BETWEEN 1000 AND 2000;
Copyright 2009 Accenture All Rights Reserved.

EMPNO

ENAME

JOB

SAL

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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

98

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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. _ : This wildcard matches exactly one character.

Copyright 2009 Accenture All Rights Reserved.

18

Using LIKE Operator (Contd)


Examples : 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 data should be of 5 characters only.

Copyright 2009 Accenture All Rights Reserved.

19

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

99

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Using LIKE Operator (Contd)


Example: To get details of employees whose name begin with letter S : SELECT EMPNO, ENAME, JOB,SAL FROM EMP WHERE ENAME LIKE S%;
EMPNO ENAME JOB SAL ================================= 7369 SMITH CLERK 800 7788 SCOTT ANALYST 3000

Example: To get details of employees whose name starts with J, and the fourth letter as E ith J fo rth and the remaining can be anything. SELECT EMPNO, ENAME, JOB,SAL FROM EMP WHERE ENAME LIKE J__E%'
EMPNO ENAME JOB SAL ==================================== 7566 JONES MANAGER 2975 7900 JAMES CLERK 950

Copyright 2009 Accenture All Rights Reserved.

20

Using Logical operators


In WHERE statement AND and OR logical operators is used to test more than one condition Operator Description AND 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 left-hand evaluates to true, the next condition is not evaluated. NOT Negates the condition. It can be used with IN, BETWEEN and LIKE operator
Copyright 2009 Accenture All Rights Reserved.

21

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

100

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Using Logical operators (Contd)


Example: To get EMPNO, ENAME, JOB, SAL of all e p oyees a g sa a y o e employees having salary more than 2000 and working in DEPTNO 20. SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL >2000 AND DEPTNO=20
EMPNO ENAME SAL DEPTNO ============================== 7566 JONES 2975 20 7788 SCOTT 3000 20 7902 FORD 3000 20
Copyright 2009 Accenture All Rights Reserved.

Example: To get EMPNO, ENAME, JOB of all employees working as S o g SALESMAN or those S o ose employees whose names start with A. SELECT EMPNO,ENAME, JOB FROM EMP WHERE JOB= 'SALESMAN' OR ENAME LIKE 'A%'
EMPNO ENAME JOB ============================== 7499 ALLEN SALESMAN 7521 WARD SALESMAN 7654 MARTIN SALESMAN 7844 TURNER SALESMAN 7876 ADAMS CLERK
22 22

Using Logical operators (Contd)


Example: To get EMPNO, ENAME, JOB, SAL of all employees whose names do not start with A. SELECT EMPNO, ENAME,JOB FROM EMP WHERE ENAME 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 7839 KING PRESIDENT 7844 TURNER SALESMAN 7900 JAMES CLERK 7902 FORD ANALYST 7934 MILLER CLERK

Copyright 2009 Accenture All Rights Reserved.

23

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

101

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Using NULL Operator


NULL values are also known as unknown values. In RDBMS, inapplicable or missing information is known as NULL. NULL The IS NULL condition tests for nulls. Example: To get EMPNO, ENAME and SAL from EMP who do not receive a commission. SELECT EMPNO, ENAME, SAL FROM EMP WHERE COMM IS NULL;
Copyright 2009 Accenture All Rights Reserved.

Sample output
EMPNO ENAME SAL COMM =================================== 7369 SMITH 800 7566 JONES 2975 7698 BLAKE 2850 7782 CLARK 2450 7788 SCOTT 3000 7839 KING 5000 7876 ADAMS 1100 7900 JAMES 950 7902 FORD 3000 7934 MILLER 1300
24

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 contain values Example: To get EMPNO, ENAME and SAL from EMP who do not receive a commission. SELECT EMPNO, ENAME, SAL FROM EMP WHERE COMM IS NOT NULL;
Copyright 2009 Accenture All Rights Reserved.

Sample output
EMPNO ENAME SAL COMM ================================= 7499 ALLEN 1600 300 7521 WARD 1250 500 7654 MARTIN 1250 1400 7844 TURNER 1500 0

25

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

102

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Using Arithmetic Operators


Arithmetic operators along with the column names can be used to retrieve values 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 SELECT EMPNO,SAL+ COMM TOTALSAL FROM EMP WHERE COMM IS NOT NULL;
Copyright 2009 Accenture All Rights Reserved.

Sample output :
EMPNO TOTALSAL ================= 7499 1900 7521 1750 7654 2650 7844 1500
26

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

103

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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;

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

104

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Column standing position is the position of the column in the select statement. The column standing position comes handy when we are applying some aggregate functions 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;

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

105

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

106

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Try out different combinations for date. 1) Display month 2) Display only year 3) Display day 4) Display hour, min and seconds

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

107

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

To_number
It converts a char value which contains digits to a numeric value.
Sample Output : p p
MONTHNUMBER ============== 12 2 2 4 9 5 6 4 11 9 5 12 12 1
31

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

Copyright 2009 Accenture All Rights Reserved.

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 Sample Output :
MONTHSBETWEEN ================== 2.96264337

Copyright 2009 Accenture All Rights Reserved.

32

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

108

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

NVL Function
Converts a null value to a non-null value. Syntax : NVL(arg1, arg2) If argument1 is not null, then it displays its value. If argument 1 is null , then it displays arg2. Example: SELECT NVL(COMM,0) FROM EMP

Copyright 2009 Accenture All Rights Reserved.

33

NVL Function (Contd...)


SELECT NVL(COMM,0) AS COMMISION FROM EMP
COMMISION ============ 0 300 500 0 1400 0 0 0 0 0 0 0 0 0
Copyright 2009 Accenture All Rights Reserved.

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


COMMISION ============ NO COMMISION 300 500 NO COMMISION 1400 NO COMMISION NO COMMISION NO COMMISION NO COMMISION 0 NO COMMISION NO COMMISION NO COMMISION NO COMMISION
34

Sample O t t S l Output

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

109

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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 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.
Copyright 2009 Accenture All Rights Reserved.

35

DECODE (Contd...)
Example:
Sample Output :
JOB ===== C S S M S M M A P S C C A C
36

SELECT DECODE(JOB,'ANALYST','A ,'CLERK','C', 'MANAGER','M','PRESIDENT',' P','SALESMAN','S') AS JOB FROM EMP;

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

110

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

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. The ti Th option specifies what the escape character is when you want to ifi h t th h t i h tt 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:

LIKE Sr\_%

ESCAPE \;

SA_MAN SA_REP SA_REP SA_REP


37

Copyright 2009 Accenture All Rights Reserved.

Printing the SQL Output


The SQL output can be redirected using SPOOL command. By default the redirection is on the screen, but it can be changed to f or printer as file required.
SPOOL ON SELECT * FROM EMP; Redirection IS ON SCREEN SPOOL PRN PRN; SELECT * FROM EMP; Redirection IS ON PRINTER SPOOL OFF
Copyright 2009 Accenture All Rights Reserved.

38

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

111

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Printing the SQL Output (Contd...)


TO FILE: SPOOL FILE1 SELECT * FROM EMP; Redirected TO FILE1.LST [c:\ORACLE\BIN ] SPOOL OFF

Copyright 2009 Accenture All Rights Reserved.

39

8: Data Manipulation Language

Activity (2 of 2)
Input documents: Activity_5.1_Module8_DataM anipulationLanguage.doc Output documents: Activity_5.1_Module8_DataM anipulationLanguageOutput.d oc

120 Minutes
Copyright 2009 Accenture All Rights Reserved.

40

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

112

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Key Points
RDBMS allow to view tables and the records they hold. It allows to add, modify and delete the data add 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 to t combine conditions f a WHERE clause. bi diti for l ORDER BY can be used to sort the results from a SELECT statement.

Copyright 2009 Accenture All Rights Reserved.

41

8: Data Manipulation Language Key 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 The function b h ti behaves lik th IF THEN like the IF..THEN ..ELSE statement SQL output can be redirected by using SPOOL command.
Copyright 2009 Accenture All Rights Reserved.

42

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

113

Introduction to RDBMS and SQL

8_DataManipulationLanguage.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

43

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

114

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Introduction to RDBMS and 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

115

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Module 9: Agenda
Aggregate Functions Retrieval Using GROUP BY and HAVING Clause Set Operators Union. Intersect. Minus. Subqueries Non-Corelated Subqueries. Correlated Subqueries. Joins Inner Join Self Join Outer Join Copyright 2009 Accenture All Rights Reserved. Use of EXISTS

Aggregate functions
Aggregate functions are functions that take a collection (a set or multiset) of values as input and return a single value. al e 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. Aggregate functions cannot be used with the WHERE clause.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

116

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Aggregate functions (Contd..)


Function Name
SUM() AVG() MAX() MIN() COUNT(Qty) COUNT(*)

Description
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. Returns the average of all the values in the specified column. Column must be numeric data type. Returns the largest value that occurs in the specified column. Column need not be numeric data type. Returns the smallest value that occurs in the specified column. Column need not be numeric data type. Returns the number of rows that do not have NULL Value in the column Qty. Returns the number of rows in the table.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

117

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subqueries.ppt

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. With the use of NVL function, the null values are converted to 0 and hence they are used while performing the average function.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

118

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 column 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 g p column. g grouped 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
Copyright 2009 Accenture All Rights Reserved.

Example - GROUP BY Clause


Example: Display JOB, TOTALSAL of each employee.
SELECT JOB, SUM(SAL) TOTALSAL FROM EMP GROUP BY JOB;

Sa p e Sample Output :

JOB TOTALSAL ===================


ANALYST CLERK MANAGER PRESIDENT SALESMAN 6000 4150 8275 5000 5600

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

119

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 clause i used i situations where th filt i i l is d in it ti h the filtering is required on the aggregate columns. Syntax: SELECT column_list FROM table GROUP BY column HAVING condition
9

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

120

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subqueries.ppt

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;

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

121

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

9: Aggregate Functions, Joins and Sub queries

Activity (1 of 4)
Input documents:
Activity_6.0_Module9_Aggregate.d oc

Output documents:
Activity_6.0_Module9_AggregateO utput.doc

60 Minutes
Copyright 2009 Accenture All Rights Reserved.

11

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 tables q 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 correctly, 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.
Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

122

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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.

Syntax: S t

SELECT column-list FROM table column list UNION SELECT column-list FROM table

Copyright 2009 Accenture All Rights Reserved.

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 no employees are working in it. SELECT DEPTNO FROM UNION SELECT DEPTNO FROM DEPT EMP
DEPTNO ================= 10 20 30 40
14

Sample Output :

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

123

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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

Syntax: SELECT column-list FROM table1 INTERSECT SELECT column-list FROM table2

Copyright 2009 Accenture All Rights Reserved.

15

Using INTERSECT (Contd)


Example: To get a list of all deptno which has employees working in it. SELECT DEPTNO FROM DEPT INTERSECT SELECT DEPTNO FROM EMP
DEPTNO ================= 10 20 30

Sample O t t : S l Output

Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

124

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Using Minus
MINUS operator returns only rows that are unique in the first table. Syntax: SELECT column-list FROM table1 MINUS SELECT column-list FROM t bl 2 l li t table2

Copyright 2009 Accenture All Rights Reserved.

17

Using Minus (Contd)


Example: To get a list of all deptno which does not have any employees working in it. SELECT DEPTNO FROM DEPT MINUS SELECT DEPTNO FROM EMP
DEPTNO ================= 40

Sample O t t : S l Output

Copyright 2009 Accenture All Rights Reserved.

18

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

125

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

9: Aggregate Functions, Joins and Sub queries Activity (2 of 4) Input documents: Activity_6.1_Module9_Union_ Intersect_Minus.doc Output documents: Activity_6.1_Module9_Union_ Intersect_Minus.doc

45 Minutes
Copyright 2009 Accenture All Rights Reserved.

19

Subqueries
Subqueries are also called as Nested queries which means SELECT statement can be nested inside i id another SELECT statement. th t t t 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: Independent/Non-correlated sub queries and Correlated sub queries Subqueries can return either a single row or multiple rows.
Copyright 2009 Accenture All Rights Reserved.

20

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

126

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 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. 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.
Copyright 2009 Accenture All Rights Reserved.

21

Operators used in Sub queries


Operator Comparison Operator IN Description (=,<>,<,>,<=,>=). (= <> < > <= >=) Used when subquery returns a single value. It is used to select rows that match the value in a list. Used when subquery returns multiple rows. It compares a value to either each value returned by a sub que y o a values returned e u ed query or all a ues e u ed by the subquery. Used when subquery returns multiple rows along with comparison operators. It always returns data in terms of TRUE or False value. Used with co-related subqueries.
22

ANY or SOME ALL

EXISTS

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

127

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subqueries.ppt

Contents: If the option of subquery was not available then to solve the query of finding the employees who are receiving the salary less than the average salary, 2 separate queries 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 names names.
SELECT ENAME FROM EMP WHERE SAL < 2073.21

Instead of executing these two queries separately, you can execute it through a subquery. The advantage here is that if there are any change in the EMP table, i,e new 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 changed changed. So, for every change in the EMP table, the first query has to be run first, the average has to be noted and then execute the second query. To avoid this situatuion subquery can be used as shown below:
SELECT ENAME FROM EMP WHERE SAL < (SELECT AVG(SAL) FROM EMP);

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

128

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Non-Corelated Sub queries (Contd)


Subqueries returning multiple rows. Example: To display the names of the employees working in dept ACCOUNTING and SALES. Sample Output : SELECT ENAME,JOB,SAL FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM ( DEPT WHERE DNAME IN ('ACCOUNTING','SALES'))
ENAME JOB SAL ============================ ALLEN SALESMAN 1600 WARD SALESMAN 1250 MARTIN SALESMAN 1250 BLAKE MANAGER 2850 CLARK MANAGER 2450 KING PRESIDENT 5000 TURNER SALESMAN 1500 JAMES CLERK 950 MILLER CLERK 1300
24

Copyright 2009 Accenture All Rights Reserved.

Non-Corelated Sub queries (Contd)


Subqueries with ANY/ALL operators
Example: To find the names of the employees who receive salary less than every average salary for each type of job. SELECT ENAME,JOB, SAL FROM EMP WHERE SAL <ALL (SELECT AVG(SAL)FROM EMP GROUP BY JOB) ) Sample Output :
ENAME JOB SAL ======================== SMITH CLERK 800 JAMES CLERK 950
Copyright 2009 Accenture All Rights Reserved.

Example: To find the names of the l h i l less employees who receive salary l than either of average salary for each type of job. SELECT ENAME,JOB, SAL FROM EMP WHERE SAL <ANY (SELECT AVG(SAL)FROM EMP GROUP BY JOB) ) Sample Output :
ENAME JOB SAL =========================== SMITH CLERK 800 ALLEN SALESMAN 1600 .. .
25

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

129

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Correlated Sub queries


Correlated subquery is a subquery that references q y the outer query. 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 E2 WHERE E1.DEPTNO=E2.DEPTNO); Sample Output : p p
EMPNO 7499 7566 7698 7788 7839 7902
Copyright 2009 Accenture All Rights Reserved.

ENAME ALLEN JONES BLAKE SCOTT KING FORD

SAL DEPTNO 1600 2975 2850 3000 5000 3000 30 20 30 20 10 20


27

============================

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

130

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Example Correlated sub query


To get employee names who have a reporting authority. Sample Output : SELECT ENAME FROM EMP E1 WHERE MGR =(SELECT EMPNO FROM EMP E2 WHERE E1.MGR E2.EMPNO); E1 MGR=E2 EMPNO);
ENAME ========= SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT TURNER ADAMS JAMES FORD MILLER
28

Copyright 2009 Accenture All Rights Reserved.

Using EXISTS
Exists clause checks for the existence of rows and does not compare columns or its values. It i used t check th existence of d t rows according t is d to h k the i t f data di 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. operator The inner query need not specify any columns in the select statement.

Copyright 2009 Accenture All Rights Reserved.

29

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

131

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Example using Exists


Example To list the employee details who directly p g report to manager KING.
SELECT ENAME FROM EMP E1 WHERE EXISTS (SELECT * FROM EMP E2 WHERE E1.MGR=E2.EMPNO AND E2.ENAME=KING);

Sample Output :

ENAME ======= JONES BLAKE CLARK

Copyright 2009 Accenture All Rights Reserved.

30

9: Aggregate Functions, Joins and Sub queries Activity (3 of 4) Input documents:


Activity_6.2_Module9_Subqueries. doc

Output documents:
Activity_6.2_Module9_Subqueries. doc

100 Minutes
Copyright 2009 Accenture All Rights Reserved.

31

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

132

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

JOINS
Joins are normally used to retrieve data from more than one table. 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 join Outer join Left-outer join Right-outer join Full outer join Self join

Copyright 2009 Accenture All Rights Reserved.

33

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

133

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 working p y g SELECT ENAME, JOB,SAL, DNAME FROM DEPT D,EMP E WHERE D.DEPTNO=E.DEPTNO; D 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 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

Sample Output

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

134

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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.

36

Left Outer Join


In left outer join, all the records from the table on the left of the OUTER JOIN statement are returned Syntax
SELECT column_list FROM left_table LEFT [OUTER] JOIN right_table ON condition

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

Copyright 2009 Accenture All Rights Reserved.

37

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

135

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 working working. ENAME JOB SAL DNAME SELECT ENAME, JOB,SAL, DNAME FROM DEPT D LEFT JOIN EMP E ON D.DEPTNO = E.DEPTNO;
===================================== 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 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

Sample Output

Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

136

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subqueries.ppt

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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

137

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

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 working working. ENAME JOB SAL DNAME SELECT ENAME, JOB,SAL, DNAME FROM EMP E RIGHT JOIN DEPT D ON E.DEPTNO = D.DEPTNO;
===================================== 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 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
40

Sample Output

Copyright 2009 Accenture All Rights Reserved.

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 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:
SELECT column_list FROM left_table FULL [OUTER] JOIN right_table ON condition

Copyright 2009 Accenture All Rights Reserved.

41

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

138

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Full Outer Join (contd...)


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

Sample Output :
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 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
42

Copyright 2009 Accenture All Rights Reserved.

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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

139

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Self Join (Contd)


Example: To find out the manager names for each of the employee Sample Output : S l O t t
SELECT E1.ENAME||' REPORTS TO '|| E2.ENAME AS REPORTS FROM EMP E1, EMP E2 WHERE E1.MGR=E2.EMPNO;
REPORTS ============== SMITH REPORTS TO FORD ALLEN REPORTS TO BLAKE WARD REPORTS TO BLAKE JONES REPORTS TO KING MARTIN REPORTS TO BLAKE 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 :

Copyright 2009 Accenture All Rights Reserved.

9: Aggregate Functions, Joins and Sub queries Activity (4 of 4) Input documents:


Activity_6.3_Module9_Joins.doc

Output documents:
Activity_6.3_Module9_JoinsOutput. doc

150 Minutes
Copyright 2009 Accenture All Rights Reserved.

45

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

140

Introduction to RDBMS and SQL

9_AggregateFunctions_Joins_Subquries.ppt

Key Points
Aggregate Functions are applied on rows and return single value. 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. yp Different types of JOINS Inner Join. Outer Join (Left Outer Join, Right Outer Join and Full Outer Join). Self Join.
Copyright 2009 Accenture All Rights Reserved.

46

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

47

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

141

Introduction to RDBMS and SQL

10_Views.ppt

Introduction to RDBMS and SQL


Module 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

142

Introduction to RDBMS and SQL

10_Views.ppt

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

Copyright 2009 Accenture All Rights Reserved.

Introduction to Views
Views are virtual tables (tables which dont occupy memory) whose contents are taken or derived from 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 Views can be used as a security mechanism to restrict the data available to end users Views can also be used to aggregate data.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

143

Introduction to RDBMS and SQL

10_Views.ppt

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 wont be able to see the entire EMP table won t table.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

144

Introduction to RDBMS and SQL

10_Views.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

145

Introduction to RDBMS and SQL

10_Views.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

146

Introduction to RDBMS and SQL

10_Views.ppt

The syntax of Complex view is similar to Create View Complex 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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

147

Introduction to RDBMS and SQL

10_Views.ppt

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

148

Introduction to RDBMS and SQL

10_Views.ppt

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.

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

149

Introduction to RDBMS and SQL

10_Views.ppt

Activity
Input documents:
Activity_7.0_Module10_Views.doc

Output documents:
Activity_7.0_Module10_ViewsOutp ut.doc

45 Minutes
Copyright 2009 Accenture All Rights Reserved.

11

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

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

150

Introduction to RDBMS and SQL

10_Views.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

13

IDCGRF002 Copyright 2009 Accenture All Rights Reserved

151

Introduction To RDBMS and SQL

Module 3: Database Design Techniques

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_1.0_Module3_DatabaseDesignTechniques.doc

Introduction To RDBMS and SQL

Module 3: Database Design Techniques

Data Structure
Field Name 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 Primary Key

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_1.0_Module3_DatabaseDesignTechniques.doc

Introduction To RDBMS and SQL

Module 4: E-R Mode

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_2.0_Module4_ER Model.doc

Introduction To RDBMS and SQL

Module 4: E-R Mode

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

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_2.0_Module4_ER Model.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_3.0_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

Tables
1) Table Name: ZIPCODE_INFO

Field Name ZIP_CODE CITY

Type VARCHAR2 VARCHAR2

Length 5 10

2) Table Name: INSTRUCTOR_INFO

Field Name INSTRUCTOR_ID INSTRUCTOR_FIRST_NAME INSTRUCTOR_LAST_NAME

Type NUMBER VARCHAR2 VARCHAR2

Length 8,0 15 15

3) Table Name: COURSE_INFO

Field Name COURSE_NO COST

Type NUMBER NUMBER

Length 8,0 5,2

4) Table Name: STUDENT_INFO

Field Name STUDENT_ID STUDENT_FIRST_NAME STUDENT_LAST_NAME

Type NUMBER VARCHAR2 VARCHAR2

Length 8,0 15 15

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_3.0_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

5) Table Name: SECTION_INFO

Field Name SECTION_ID COURSE_NO SECTION_NO INSTRUCTOR_ID

Type NUMBER NUMBER NUMBER NUMBER

Length 8,0 8,0 5 8,0

6) Table Name: ENROLLMENT_INFO

Field Name STUDENT_ID SECTION_ID

Type NUMBER NUMBER

Length 8,0 8,0

7) Table Name: GRADE_INFO

Field Name STUDENT_ID SECTION_ID GRADE_TYPE_CODE GRADE_CODE_OCCURANCE

Type NUMBER NUMBER CHAR NUMBER

Length 8,0 8,0 2 5

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_3.0_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_3.1_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

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 ZIP_CODE CITY STATE

Type VARCHAR2 VARCHAR2 VARCHAR2

Length 5 25 2

2) Table Name: INSTRUCTOR_INFO

Field Name INSTRUCTOR_ID INSTRUCTOR_FIRST_NAME INSTRUCTOR_LAST_NAME STREET_ADDRESS ZIP_CODE

Type NUMBER VARCHAR2 VARCHAR2 VARCHAR2 VARCHAR2

Length 8,0 25 25 50 5

3) Table Name: COURSE_INFO Field Name COURSE_NO COURSE_NAME COURSE_PREREQUISITE COST Type NUMBER VARCHAR2 NUMBER NUMBER Length 8,0 50 8,0 9,2

4) Table Name: STUDENT_INFO Field Name STUDENT_ID STUDENT_FIRST_NAME STUDENT_LAST_NAME STREET_ADDRESS ZIP_CODE Type NUMBER VARCHAR2 VARCHAR2 VARCHAR2 VARCHAR2 Length 8,0 25 25 50 5

IDCGRF002 2009 Accenture. All Rights Reserved.

Activity_3.1_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 6: Data Definition Language

5) Table Name: SECTION_INFO

Field Name SECTION_ID COURSE_NO SECTION_NO INSTRUCTOR_ID LOCATION CAPACITY

Type NUMBER NUMBER NUMBER NUMBER VARCHAR2 NUMBER

Length 8,0 8,0 3,0 8,0 50 3,0

6) Table Name: ENROLLMENT_INFO Syntactical Field Name STUDENT_ID SECTION_ID ENROLLMENT_DATE Type NUMBER NUMBER DATE Length 8,0 8,0

7) Table Name: GRADE_INFO

Field Name STUDENT_ID SECTION_ID GRADE_TYPE_CODE GRADE_CODE_OCCURANCE NUMERIC_GRADE

Type NUMBER NUMBER CHAR NUMBER NUMBER

Length 8,0 8,0 2 38,0 3,0

IDCGRF002 2009 Accenture. All Rights Reserved.

10

Activity_3.1_Module6_DataDefinationLanguage.doc

Introduction To RDBMS and SQL

Module 7: Constraints

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

IDCGRF002 2009 Accenture. All Rights Reserved.

11

Activity_4.0_Module7_Constraints.doc

Introduction To RDBMS and SQL

Module 7: Constraints

Tables
Below are the constraints to be made on the tables. 1) Table Name: ZIPCODE_INFO

Field Name ZIP_CODE CITY STATE

Type VARCHAR2 VARCHAR2 VARCHAR2

Length 5 25 2

Constraint Name PRIMARY KEY ZIP_PK NOT NULL ZIP_CITY_NN NOT NULL ZIP_STATE_NN

2) Table Name: INSTRUCTOR_INFO Field Name INSTRUCTOR_ID INSTRUCTOR_FIRST_NAME INSTRUCTOR_LAST_NAME STREET_ADDRESS ZIP_CODE Type NUMBER VARCHAR2 VARCHAR2 VARCHAR2 VARCHAR2 Length 8,0 25 25 50 5 FOREIGN KEY ZIP_INSTRUCTOR_FK CONSTRAINT NAME PRIMARY KEY INSTRUCTOR_ID_PK NOT NULL INSTRUCTOR_FN_NN NOT NULL INSTRUCTOR_LN_NN

3) Table Name: COURSE_INFO Field Name COURSE_NO COURSE_NAME COURSE_PREREQUISITE COST Type NUMBER VARCHAR2 NUMBER NUMBER Length 8,0 50 8,0 9,2 NOT NULL COST_NN CONSTRAINT NAME PRIMARY KEY COURSE_NO_PK NOT NULL COURSE_NAME_NN

4) Table Name: STUDENT_INFO

Field Name STUDENT_ID STUDENT_FIRST_NAME STUDENT_LAST_NAME STREET_ADDRESS ZIP_CODE

Type NUMBER VARCHAR2 VARCHAR2 VARCHAR2 VARCHAR2

Length 8,0 25 25 50 5

CONSTRAINT NAME PRIMARY KEY STUDENT_ID_PK NOT NULL STUDENT_FN_NN NOT NULL STUDENT_LN_NN

FOREIGN KEY ZIP_STUDENT_FK

IDCGRF002 2009 Accenture. All Rights Reserved.

12

Activity_4.0_Module7_Constraints.doc

Introduction To RDBMS and SQL

Module 7: Constraints

5) Table Name: SECTION_INFO

Field Name SECTION_ID COURSE_NO SECTION_NO INSTRUCTOR_ID LOCATION CAPACITY

Type NUMBER NUMBER NUMBER NUMBER VARCHAR2 NUMBER

Length 8,0 8,0 3,0 8,0 50 3,0

CONSTRAINT NAME PRIMARY KEY SECTION_ID_PK FOREIGN KEY COURSE_SECTION_FK NOT NULL -SECTION_NO_NN FOREIGN KEY INSTRUCTOR_SECTION_FK

6) Table Name: ENROLLMENT_INFO Field Name STUDENT_ID SECTION_ID Type NUMBER NUMBER Length 8,0 8,0 CONSTRAINT NAME PRIMARY KEY (STUDENT_ID,SECTION_ID) ENROLLMENT_STUD_SECT_PK FOREIGN KEY-ENROLLMENT_STUDENT_ID_FK FOREIGN KEY-ENROLLMENT_SECTION_ID_FK ENROLLMENT_DATE DATE

7) Table Name: GRADE_INFO Field Name STUDENT_ID SECTION_ID GRADE_TYPE_CODE GRADE_CODE_OCCURANCE Type NUMBER NUMBER CHAR NUMBER Length 8,0 8,0 2 38,0 CONSTRAINT NAME PRIMARY KEY (STUDENTID,SECTIONID,GRADE_TYPE _CODE,GRADE_CODE_OCCURANCE) GRADE_STUD_SECT_TYPE_CODE_PK FOREIGN KEYGRADE_STUDENT_ID_FK FOREIGN KEYGRADE_SECTION_ID_FK CHECK - CHK_GRADE_TYPE_CODE CHECK VALID VALUES FOR GRADE TYPE CODE - FI,HM, MT,PA,PJ,QZ NUMERIC_GRADE NUMBER 3,0 NUMERIC_GRADE_NN DEFAULT 0

IDCGRF002 2009 Accenture. All Rights Reserved.

13

Activity_4.0_Module7_Constraints.doc

Introduction To RDBMS and SQL

Module 8: Data Manipulation Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

14

Activity_5.0_Module8_DataManipulationLanguage.doc

Introduction To RDBMS and SQL

Module 8: Data Manipulation Language

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

IDCGRF002 2009 Accenture. All Rights Reserved.

15

Activity_5.0_Module8_DataManipulationLanguage.doc

Introduction To RDBMS and SQL

Module 8: Data Manipulation Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

16

Activity_5.1_Module8_DataManipulationLanguage.doc

Introduction To RDBMS and SQL

Module 8: Data Manipulation Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

17

Activity_5.1_Module8_DataManipulationLanguage.doc

Introduction To RDBMS and SQL

Module 8: Data Manipulation Language

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

18

Activity_5.1_Module8_DataManipulationLanguage.doc

Introduction To RDBMS and SQL

Module 9: Aggregate Functions

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

19

Activity_6.0_Module9_Aggregate.doc

Introduction To RDBMS and SQL

Module 9: Aggregate Functions

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 prerequisite. 7) Display the date of the student who got recently enrolled.

Group by and Having Clause


1) 2) 3) 4) 5) 6) 7) 8) 9) 10) Display the count of cities for each state. Display the minimum numeric grade section wise for each student. Display the average numeric grade for each student. Display the count of students enrolled in each section. Display only those sections where the number of students enrolled is more than 5. Display the average numeric grade for each student and section. The average numeric grade should be more than 75. For the above query display the data for student_id more than 280. Display each prerequisite and its count from the course_info table. Display student_id and number of courses they are enrolled in. Those students who are enrolled in more than 2 courses should be displayed. Display the average capacity of each course. For the above query display those courses which have exactly 2 sections.

IDCGRF002 2009 Accenture. All Rights Reserved.

20

Activity_6.0_Module9_Aggregate.doc

Introduction To RDBMS and SQL

Module 9: Union-Intersect-Minus

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

21

Activity_6.1_Module9_Union_Intersect_Minus.doc

Introduction To RDBMS and SQL

Module 9: Union-Intersect-Minus

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

22

Activity_6.1_Module9_Union_Intersect_Minus.doc

Introduction To RDBMS and SQL

Module 9: Subqueries

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

23

Activity_6.2_Module9_Subqueries.doc

Introduction To RDBMS and SQL

Module 9: Subqueries

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 ids 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.

IDCGRF002 2009 Accenture. All Rights Reserved.

24

Activity_6.2_Module9_Subqueries.doc

Introduction To RDBMS and SQL

Module 9: Subqueries

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

25

Activity_6.2_Module9_Subqueries.doc

Introduction To RDBMS and SQL

Module 9: Joins

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

26

Activity_6.3_Module9_Joins.doc

Introduction To RDBMS and SQL

Module 9: Joins

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

27

Activity_6.3_Module9_Joins.doc

Introduction To RDBMS and SQL

Module 9: Joins

Self Join
1) Many courses have pre-requisite. Display the course no and the description along with the prerequisite 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.

IDCGRF002 2009 Accenture. All Rights Reserved.

28

Activity_6.3_Module9_Joins.doc

Introduction To RDBMS and SQL

Module 10: Views

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

29

Activity_7.0_Module10_Views.doc

Introduction To RDBMS and SQL

Module 10: Views

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.

IDCGRF002 2009 Accenture. All Rights Reserved.

30

Activity_7.0_Module10_Views.doc