You are on page 1of 120

1 2010 Wipro Ltd Internal & Restricted 2010 Wipro Ltd Internal & Restricted

Database Concepts

Gururaja Sedambi
2 2010 Wipro Ltd Internal & Restricted 2 2010 Wipro Ltd Internal & Restricted
Develop an understanding of the purpose of database systems
Become familiar with the structure of a relational database and
review relational database concepts and terms
Become acquainted with Structured Query Language (SQL)
Learn about Oracle9i user schemas and Learn how to define
Oracle9i database tables
Create ,Modify and Delete database tables using SQL*Plus
Learn how to run a script to create database tables automatically
Learn how to insert data , how to create database transactions and
commit data to the database, Create search conditions in SQL
queries
Understand how to update and delete database records, and how to
truncate tables and how to create and use sequences to generate
surrogate key values automatically
Learn how to grant and revoke database object privileges




Objectives
3 2010 Wipro Ltd Internal & Restricted
Before Databases
Information was kept in files:
Each field describes one piece of information about student
Fields are separated by commas
A record is a collection of related fields
Each record is a separate line
4 2010 Wipro Ltd Internal & Restricted
Problems with Files
Proliferation of
data management
programs to deal
with different file
formats
Redundant data
stored in files
Data files may
contain
inconsistent data
5 2010 Wipro Ltd Internal & Restricted
Database Approach
Database stores all organizational data in a central location

Good database design eliminates redundant data to reduce the
possibility of inconsistent data

Single application called the database management system
(DBMS) performs all routine data handling operations

Database administrator (DBA): person responsible for
installing, administering, and maintaining the database
6 2010 Wipro Ltd Internal & Restricted
Early Databases Hierarchical
Structure
7 2010 Wipro Ltd Internal & Restricted
Relational Databases
8 2010 Wipro Ltd Internal & Restricted
Relational Database Terms
Entity: an object about which you want to store data
Relationships: links that show how different records
are related
Key Fields: establish relationships among records in
different tables
Five main types of key fields:
primary keys
candidate keys
surrogate keys
foreign keys
composite keys
9 2010 Wipro Ltd Internal & Restricted
Primary Keys
Primary key
Value must be unique for each record
Serves to identify the record
Present in every record
Cant be NULL
Should be numeric
10 2010 Wipro Ltd Internal & Restricted
Candidate Keys
Candidate key
Any field that could be used as the primary key
Should be a unique, unchanging numeric field

11 2010 Wipro Ltd Internal & Restricted
Surrogate Keys
Surrogate key: created to be the records primary key identifier when
no suitable primary key exists

Surrogate key has no real relationship to the record to which it is
assigned, other than to identify the record uniquely

Developers configure the database to generate surrogate key values
automatically

In an Oracle database, you can automatically generate surrogate key
values using a sequence

Surrogate keys are always numerical fields, because the database
generates surrogate key values automatically by incrementing the
previous value by one

12 2010 Wipro Ltd Internal & Restricted
Foreign Keys
Foreign key: a field in a table that is a primary key in another table
Foreign key creates a relationship between the two tables
Foreign key value must exist in the table where it is a primary key
13 2010 Wipro Ltd Internal & Restricted
Composite Keys
Composite key: a unique key that you create by
combining two or more fields

Usually comprised of fields that are primary keys in
other tables
14 2010 Wipro Ltd Internal & Restricted
Personal Database
Management Systems
DBMS and database applications run on the same workstation and
appear to the user as a single integrated application

Personal databases used primarily for creating single-user database
applications

Support small multiuser database applications by storing the database
application files on a file server instead of on a single users workstation
and then transmitting the files or the parts of files containing the desired
data to various users across a network

Database developers should use a personal database only for non-
mission-critical applications

15 2010 Wipro Ltd Internal & Restricted
Client/Server Database
Management Systems
Client/server database
Takes advantage of distributed processing and networked
computers by distributing processing across multiple computers
DBMS server process runs on one workstation, and the database
applications run on separate client workstations across the network
Preferred for database applications that retrieve and manipulate
small amounts of data from databases containing large numbers of
records because they minimize network traffic and improve
response times
Organizations generally use a client/server database if the
database will have more than 10 simultaneous users and if the
database is mission critical

16 2010 Wipro Ltd Internal & Restricted
Client/Server Database Architecture
17 2010 Wipro Ltd Internal & Restricted
The Oracle9i Client/Server Database
Oracle9i is the latest release of Oracle Corporations relational
database
All Oracle server- and client-side programs use Oracle Net, a
utility that enables the network communication between the
client and the server

18 2010 Wipro Ltd Internal & Restricted
Client-Side Utilities
SQL*Plus
for creating and testing command-line SQL queries and executing
PL/SQL procedural programs
Oracle9i Developer Suite
for developing database applications including the following
Developer tools:
Forms Builder
for creating custom user applications
Reports Builder
for creating reports for displaying, printing, and distributing
summary data
Enterprise Manager
for performing database administration tasks such as creating new
user accounts and configuring how the DBMS stores and manages
data

19 2010 Wipro Ltd Internal & Restricted
Design Principles
To avoid creating tables that contain redundant data, group
related items that describe a single entity together in a common
table

Do not create tables that duplicate values many times in
different rows

When creating a database and inserting data values, you must
specify the data type for each column

Recall that primary key fields should use a number data type to
avoid typographical, punctuation, and case variation errors

20 2010 Wipro Ltd Internal & Restricted
The Clearwater Traders
Sales Order Database
Clearwater Traders
Markets a line of clothing and sporting goods via mail-order
catalogs
Accepts customer orders via telephone, mail, and fax
Wants to begin accepting orders using its Web site
Has decided to offer 24-hour customer order service
Existing microcomputer-based database system cannot handle
current transaction volume
Managers concerned that the current database does not have
the failure-handling and recovery capabilities needed for an
ordering system that cannot tolerate failures or downtime
21 2010 Wipro Ltd Internal & Restricted
Clearwater Traders Data
Requirements
Customer name, address, daytime and evening telephone numbers,
user names, and passwords

Order date, payment method (check or credit card), order source
(catalog description or Web site), and associated item numbers, sizes,
colors, and quantities ordered

Item descriptions and photo images, as well as item categories
(womens clothing, outdoor gear, and so on), prices, and quantities on
hand. Many clothing items are available in multiple sizes and colors.
Sometimes the same item has different prices depending on the item
size

Information about incoming product shipments

22 2010 Wipro Ltd Internal & Restricted
Clearwater Traders
Table Relationships
23 2010 Wipro Ltd Internal & Restricted
The Northwoods University
Student Registration Database
Northwoods University
Decided to replace its aging mainframe-based
student registration system with a more modern
client/server database system

School officials want students to be able to retrieve
course availability information, register for courses,
and print transcripts using personal computers
located in the student computer labs

24 2010 Wipro Ltd Internal & Restricted
The Northwoods University
Student Registration Database (cont)
Faculty members must be able to retrieve student
course lists, drop and add students, and record
course grades

Faculty members must also be able to view records
for the students they advise

Security is a prime concern, so student and course
records must be protected by password access

25 2010 Wipro Ltd Internal & Restricted
Northwoods University
Data Requirements
Student name, address, telephone number, class (freshman,
sophomore, junior, or senior), date of birth, PIN (personal
identification number), and advisor ID

Course call number (such as MIS 101), course name, credits,
location, duration, maximum enrollment, instructor, and term
offered

Instructor name, office location, telephone number, rank, and
PIN

Student enrollment and grade information


26 2010 Wipro Ltd Internal & Restricted
Northwoods University
Table Relationships
27 2010 Wipro Ltd Internal & Restricted
The Software Experts Project
Management Database
Software Experts
Consulting firm that creates custom software applications

Managers determine the number and the skill sets of the consultants
that a given project requires

Managers locate available consultants with the necessary skills

One consultant is named project manager

When completed, the project manager evaluates all the other
consultants and all the consultants evaluate the project manager

A project can be subdivided into multiple subprojects

28 2010 Wipro Ltd Internal & Restricted
Software Experts Requirements
Consultant information, including name, address, city,
state, ZIP code, phone number, and e-mail address

Descriptions of consultant skills

Client information, including the client name, client contact
name, and contact phone number
29 2010 Wipro Ltd Internal & Restricted
Software Experts Requirements
Project information, including the project name, the client
associated with the project, associated subprojects, the
project manager, and required skill sets

Dates that a consultant started and finished working on a
specific project and total days that the consultant spent
working on the project

Consultant evaluation information, including the date the
evaluation was completed, who performed the evaluation,
and the evaluation score and comments
30 2010 Wipro Ltd Internal & Restricted
Software Experts Table
Relationships
31 2010 Wipro Ltd Internal & Restricted
Introduction to SQL
Structured Query Language (SQL): the
standard query language for relational
databases
Data definition language (DDL)
Create new database objects
Modify or delete existing objects.
Data manipulation language (DML)
Insert, update, delete, and view database data.
32 2010 Wipro Ltd Internal & Restricted
Oracle9i User Accounts
User account - identified by a unique
username and password

User schema - all of the objects that the user
creates and stores in the database

Object owner has privileges to perform all
possible actions on an object
33 2010 Wipro Ltd Internal & Restricted
Defining Oracle9i Database Tables
To create a new table specify:
Table name
Name of each data field
Data type and size of each data field
Constraints: restrictions on the data values that a field can store
Oracle Naming Standard:
Series of rules Oracle Corporation established for naming all
database objects
Objects must be from 1 to 30 characters long
Can contain letters, numbers, and the special symbols $, _, and #
Must begin with a character
34 2010 Wipro Ltd Internal & Restricted
Creating a Table
CREATE TABLE tablename
(fieldname1data_type,
(fieldname2 data_type,
)
35 2010 Wipro Ltd Internal & Restricted
Oracle9i Data Types
Data type: specifies the kind of data that a field
stores

Assigning a data type provides a means for error
checking

Data types enable the DBMS to use storage space
more efficiently by internally storing different types of
data in different ways
36 2010 Wipro Ltd Internal & Restricted
Character Data Types
VARCHAR2
Stores variable-length character data up to a
maximum of 4,000 characters
Values in different records can have a different
number of characters
fieldname VARCHAR2(maximum_size)
37 2010 Wipro Ltd Internal & Restricted
Character Data Types
CHAR
Fixed-length character data up to a maximum size
of 2,000 characters
Data values for different records all have the same
number of characters
DBMS adds trailing blank spaces to the end of the
entry to make the entry fill the maximum_size
value
Data longer than maximum_size causes an error
fieldname CHAR[(maximum_size)]
38 2010 Wipro Ltd Internal & Restricted
Character Data Types
NVARCHAR2 and NCHAR
Analogous to VARCHAR2 and CHAR but use
Unicode rather than ASCII
Used to hold character data in languages other
than English
39 2010 Wipro Ltd Internal & Restricted
Number Data Types
Stores negative, positive, fixed, and floating point
numbers between 10130 and 10125, with precision
up to 38 decimal places
General Syntax: fieldname NUMBER [([precision,]
[scale])]
Integer: fieldname NUMBER(precision)
Fixed point: fieldname NUMBER[([precision],[scale])]
Floating point: fieldname NUMBER
40 2010 Wipro Ltd Internal & Restricted
Date and Time Data Types
DATE
Dates from December 31, 4712 BC to December 31, 4712
AD
Default format DD-MON-YY
Default time format HH:MI:SS A.M.
fieldname DATE
TIMESTAMP
Similar to DATE but stores fractional seconds
fieldname TIMESTAMP (fractional_seconds_precision)
41 2010 Wipro Ltd Internal & Restricted
Date and Time Data Types
INTERVAL YEAR TO MONTH
Time interval, expressed in years and months
+02-11 specifies a positive time interval of 2 years and 11 months
fieldname INTERVAL YEAR[(year_precision)] TO MONTH
INTERVAL DAY TO SECOND
Time interval, expressed in days, hours, minutes, and seconds
-04 03:20:32.00: 4 days, 3 hours, 20 minutes, and 32 seconds
fieldname INTERVAL DAY[(leading_precision)] TO
SECOND[(fractional_seconds_precision)]
42 2010 Wipro Ltd Internal & Restricted
Large Object (LOB) Data Types
43 2010 Wipro Ltd Internal & Restricted
Constraints
Rules that restrict the data values that you can enter into a field in a
database table

Integrity constraints: define primary and foreign keys

Value constraints: define specific data values or data ranges that
must be inserted into columns and whether values must be unique or
not NULL

Table constraint: restricts the data value with respect to all other
values in the table

Field constraint: limits the value that can be placed in a specific field,
irrespective of values that exist in other table records
44 2010 Wipro Ltd Internal & Restricted
Oracle Constraint Naming Convention
tablename_ fieldname_constraintID
45 2010 Wipro Ltd Internal & Restricted
Integrity Constraints
Define primary key fields

Specify foreign keys and their corresponding
table and column references

Specify composite keys
46 2010 Wipro Ltd Internal & Restricted
Value Constraints
Check conditions: field value must be a specific value or fall
within a range of values

NOT NULL constraints: specify whether a field value can be
NULL

Default constraints: specify that a field has a default value that
the DBMS automatically inserts for every record, unless the user
specifies an alternate value

Unique constraints: specify that a field must have a unique value
for every table record
47 2010 Wipro Ltd Internal & Restricted
Creating Database Tables Using
SQL*Plus
Type SQL commands at the SQL prompt

End each command with a semicolon (;)

Not case sensitive
48 2010 Wipro Ltd Internal & Restricted
Log On to SQL*Plus
49 2010 Wipro Ltd Internal & Restricted
SQL*Plus Program Window
50 2010 Wipro Ltd Internal & Restricted
Create a Table
51 2010 Wipro Ltd Internal & Restricted
Table Creation Sequence
When creating tables with foreign key references,
create referenced tables first

Always create tables without foreign keys before
those with foreign keys
52 2010 Wipro Ltd Internal & Restricted
Using Notepad
Useful to use Notepad to edit sql commands
Commands can be edited without retyping
Commands can be saved
Saving multiple sql commands in a file creates a
script
53 2010 Wipro Ltd Internal & Restricted
Errors
When an error occurs error information is displayed:
Line number
Position on line
Error code
Description of error
Error codes
3 letter prefix (I.e. ORA)
5 digit code
More information on errors can be found at
http://otn.oracle.com
54 2010 Wipro Ltd Internal & Restricted
Exiting SQL*Plus
Three ways to exit SQL*Plus:
Type exit at the SQL prompt
Click File on the menu bar, and then click Exit
Click the Close button on the program window title
bar
Database session ends when SQL*Plus exits
55 2010 Wipro Ltd Internal & Restricted
Create Table with Foreign Key
Constraint
56 2010 Wipro Ltd Internal & Restricted
Viewing Information About Tables
describe tablename: displays column names and
data types
Data dictionary: tables that contain information
about the structure of the database.
USER: shows the objects in the current users schema
ALL: shows both objects in the current users schema and
objects that the user has privileges to manipulate
DBA: allows users who are database administrators to view
information about all database objects
57 2010 Wipro Ltd Internal & Restricted
Viewing Tables in the Database
58 2010 Wipro Ltd Internal & Restricted
Viewing Constraints on One Table
59 2010 Wipro Ltd Internal & Restricted
Modifying and Deleting Database
Tables
Modify existing database tables by:
Changing the name of a table
Adding new columns
Deleting columns that are no longer needed
Changing the data type or maximum size of an existing
column
Unrestricted action: some specifications can always
be modified
Restricted action: specifications modified only in
certain situations
60 2010 Wipro Ltd Internal & Restricted
Unrestricted Action
61 2010 Wipro Ltd Internal & Restricted
Restricted Actions
62 2010 Wipro Ltd Internal & Restricted
Deleting and Renaming Tables
To delete:
Drop table [tablename]
Use with caution
To delete foreign key constraints, add cascade constraints
To rename:
Rename old_tablename to new_tablename
DBMS automatically transfers to the new table integrity
constraints, indexes, and privileges that referenced the old
table.
63 2010 Wipro Ltd Internal & Restricted
Adding Fields to Existing Tables
To add a field:
ALTER TABLE tablename ADD(fieldname
data_declaration constraints);
64 2010 Wipro Ltd Internal & Restricted
Modifying Existing Field Data
Definitions
Can only change datatype to compatible data
type (i.e. varchar2 to char)

ALTER tablename MODIFY(fieldname
new_data_declaration);
65 2010 Wipro Ltd Internal & Restricted
Deleting a Field
ALTER TABLE tablename DROP COLUMN
fieldname;

Can be used to rename a field first drop,
then add
66 2010 Wipro Ltd Internal & Restricted
Adding and Deleting Constraints
Add a constraint: ALTER TABLE tablename
ADD CONSTRAINT constraint_name
constraint_definition;

Remove a constraint: ALTER TABLE
tablename DROP CONSTRAINT
constraint_name;
67 2010 Wipro Ltd Internal & Restricted
Enabling and Disabling Constraints
When modifying a database it can be useful to
disable constraints

Constraints are enabled by default

To disable a constraint: ALTER TABLE tablename
DISABLE CONSTRAINT constraint_name;

To enable a constraint: ALTER TABLE tablename
ENABLE CONSTRAINT constraint_name;
68 2010 Wipro Ltd Internal & Restricted
Using Scripts to Create Database
Tables
One or more SQL commands saved in a text
file
Usually have .sql extension
To run from SQL*Plus:
Start full file path (c:\temp\myfile.sql)
@full file path (@c:\temp\myfile.sql)
Extension can be omitted if it is .sql
69 2010 Wipro Ltd Internal & Restricted
Inserting Data into Tables
INSERT command adds new records
Field values should match column order, or be
specified in command
INSERT INTO faculty (F_ID, F_LAST, F_FIRST,
F_MI, LOC_ID) VALUES (1, 'Cox', 'Kim', 'J', 9);
70 2010 Wipro Ltd Internal & Restricted
Format Models
Used to format data retrieved from database
Can be used to format a date to display time
or a number to display as a currency
71 2010 Wipro Ltd Internal & Restricted
Numerical Format Models
72 2010 Wipro Ltd Internal & Restricted
Date Format Models
73 2010 Wipro Ltd Internal & Restricted
Date Format Models
74 2010 Wipro Ltd Internal & Restricted
Inserting Date and Interval Values
Use to_date function to convert a character string to a date
Specify date string and matching format model
TO_DATE('08/24/2004', 'MM/DD/YYYY')
TO_DATE('10:00 AM', 'HH:MI AM')
Use functions to convert character strings to intervals
TO_YMINTERVAL('4-9') inserts a positive interval of 4 years, 9
months
TO_DSINTERVAL('0 01:15:00') inserts a positive interval of 4 days,
1 hour, 15 minutes, 0 seconds
75 2010 Wipro Ltd Internal & Restricted
Inserting LOBs
Before inserting LOB must insert a LOB locator

LOB locator: a structure that contains information
that identifies the LOB data type and points to the
alternate memory location

Write a program or use a utility to add LOB data to
database

Use EMPTY_BLOB() function to insert a LOB locator
76 2010 Wipro Ltd Internal & Restricted
Creating Transactions and
Committing New Data
Transaction: series of action queries that represent a logical
unit of work

User can commit (save) changes

User can roll back (discard) changes

Pending transaction: a transaction waiting to be committed or
rolled back

Oracle DBMS locks records associated with pending
transactions

Other users cannot view or modify locked records
77 2010 Wipro Ltd Internal & Restricted
Commit and Roll Back in SQL*Plus
Transactions begin automatically with first command
Type COMMIT to commit changes
Type ROLLBACK to roll back changes
78 2010 Wipro Ltd Internal & Restricted
Savepoints
A bookmark that designates the beginning of an individual
section of a transaction
Changes are rolled back to savepoint
79 2010 Wipro Ltd Internal & Restricted
Creating Search Conditions
in SQL Queries
An expression that seeks to match specific table
records
Used in SELECT, UPDATE and DELETE statements
WHERE fieldname comparison_operator
search_expression
WHERE S_ID = 1
80 2010 Wipro Ltd Internal & Restricted
Comparison Operators
81 2010 Wipro Ltd Internal & Restricted
Defining Search Expressions
Character strings
Must be enclosed in single quotes
Case sensitive
Dates
Use to_date function with date string and format model
Intervals
Use to_yminterval and to_dsinterval with interval string
format model
82 2010 Wipro Ltd Internal & Restricted
Creating Complex Search Conditions
Combines multiple search conditions using the
AND,OR, and NOT logical operators.
AND both conditions must be true
OR one or both condition must be true
NOT opposite of actual value
Use () to group logical operators
83 2010 Wipro Ltd Internal & Restricted
Updating and Deleting
Existing Table Records
UPDATE:
Updates field values in one or more records in a table
Only one table may be updated at a time
UPDATE tablename SET field1= new_value1, field2 = new_value2,
... WHERE search condition;
DELETE:
Removes specific records from a database table
If search condition is omitted, entire table data is removed
DELETE FROM tablename WHERE search condition;
84 2010 Wipro Ltd Internal & Restricted
Updating and Deleting
Existing Table Records
TRUNCATE
Removes all of the table data without saving any
rollback information
Must disable foreign key constraints before
truncating table
TRUNCATE TABLE tablename;
85 2010 Wipro Ltd Internal & Restricted
Sequences
Sequential lists of numbers to create unique surrogate
key values
To use a sequence:
SELECT sequence_name.NEXTVAL FROM DUAL;
INSERT INTO location LOC_ID)
VALUES(loc_id_sequence.NEXTVAL);
86 2010 Wipro Ltd Internal & Restricted
Database Object Privileges
Privileges must be granted so that other users can access objects in
user schema
GRANT privilege1, privilege2,ON object_name TO user1,user2,...;
REVOKE privilege1, privilege2,... ON object_name FROM user1,
user2, ...;
To grant or revoke privileges for everyone use PUBLIC as user
87 2010 Wipro Ltd Internal & Restricted
Lesson B Objectives
Learn how to write SQL queries to retrieve data from
a single database table
Create SQL queries that perform calculations on
retrieved data
Use SQL group functions to summarize retrieved
data
88 2010 Wipro Ltd Internal & Restricted
Retrieving Data from
a Single Database Table
SELECT fieldname1, fieldname2, ... FROM
ownername.tablename WHERE search_condition;
To select:
All rows omit where clause
All fields, use *: SELECT * FROM
Only unique field values: SELECT DISTINCT fieldname
Search condition:
Use comparison and logical operators
IS NULL/IS NOT NULL to match/exclude NULL values
IN/NOT IN to match set values
LIKE with wildcards % and _ to match character strings
89 2010 Wipro Ltd Internal & Restricted
Sorting Query Output
Use ORDER BY sort_key_field(s)
Default order is ascending, use DESC to sort descending
90 2010 Wipro Ltd Internal & Restricted
Using Calculations in SQL Queries
Calculations are performed by DBMS, result only sent to client
Can use arithmetic operators (+, -, *, /)
Place calculation in select clause: SELECT price * quantity
FROM
Calculations can be performed on NUMBER, DATE and
INTERVAL fields only
Single-row functions: built in Oracle functions to perform
calculations and manipulate retrieved data values
91 2010 Wipro Ltd Internal & Restricted
Oracle9i SQL Group Functions
Group functions: perform an operation on a group of queried
rows and returns a single result
92 2010 Wipro Ltd Internal & Restricted
Group By
Use to group output by the field with duplicate values and apply
group functions to the grouped data
93 2010 Wipro Ltd Internal & Restricted
Having
Use to place a search condition on results of group function
calculations
Like WHERE for group functions
HAVING group_function comparison_operator value
HAVING SUM(capacity) >= 100
94 2010 Wipro Ltd Internal & Restricted
Formatting Output in SQL*Plus
To change default column headings:
Specify alternate column headings: SELECT fieldname1
"heading1_text", fieldname2 "heading2_text", ...
Use an alias for column headings: SELECT fieldname1 AS
alias_name1...
To change SQL*Plus line and page size settings
Select Options/Environment on menu bar
Modify linesize and pagesize to desired values
95 2010 Wipro Ltd Internal & Restricted
Formatting Numbers and Dates
Use to_char function with format models
TO_CHAR(field_name, 'format_model')
SELECT inv_id, TO_CHAR(inv_price, '$99,999.99')
FROM inventory WHERE item_id = 1;
96 2010 Wipro Ltd Internal & Restricted
Lesson C Objectives
Learn how to create SQL queries that join multiple
tables
Learn how to create nested SQL queries
Understand how to combine query results using set
operators
Create and use database views
97 2010 Wipro Ltd Internal & Restricted
Joining Multiple Tables
Join: combine data from multiple database tables using foreign
key references
SELECT field1, field2, ... FROM table1, table2 WHERE
table1.joinfield = table2.joinfield AND search_condition(s);
If tables share field names, must prefix field in select with table
name (table1.field1, table2.field1)
Join condition: part of where clause indicating how tables are
related (table1.foreign_key = table2.primary key)
Search conditions can be added to join condition using AND
operator
98 2010 Wipro Ltd Internal & Restricted
Inner Join
Join two tables based on values in one table being equal
to values in another table
Also known as equality join, equijoin or natural join
Returns results only if records exist in both tables
99 2010 Wipro Ltd Internal & Restricted
Joining Via Linking Table
100 2010 Wipro Ltd Internal & Restricted
Using a Query Design Diagram
Helpful for creating complicated queries
Can use a formula to derive actual query from diagram
101 2010 Wipro Ltd Internal & Restricted
Outer Join
Returns all rows in one table and matching rows in joined table

Inner table: all rows are returned

Outer table: matching rows are returned

Outer table marked with a + in join condition

inner_table.join_field = outer_table.join_field(+)

Null values are inserted for fields in outer table that are not
found
102 2010 Wipro Ltd Internal & Restricted
Self-Join
A query that joins a table to itself

Used when a table has a foreign key relationship to itself
(usually parent-child relationship)

Must create a table alias and structure the query as if you are
joining the table to a copy of itself

FROM table1 alias1, ...

Use alias, not table name for select and where clauses
103 2010 Wipro Ltd Internal & Restricted
Self-Join Example
104 2010 Wipro Ltd Internal & Restricted
Creating Nested Queries
Used to select results based on the result of a query
Consists of a main query and one or more subqueries.
Main query: first query that appears in the SELECT command
Subquery retrieves values that the main querys search condition
must match
105 2010 Wipro Ltd Internal & Restricted
Creating Nested Queries
Nested queries can return single or multiple values
To match single values use = operator
To match multiple values use IN operator

Subqueries can be nested to more than one level (nested
subqueries)

Nested subqueries are slower than joins and should be used
sparingly
106 2010 Wipro Ltd Internal & Restricted
Nested Subquery Example
107 2010 Wipro Ltd Internal & Restricted
Using Set Operators
To Combine Query Results
Use to select data from multiple tables not connected with
foreign key relationships
108 2010 Wipro Ltd Internal & Restricted
Set Operators
query1 OPERATOR query2; (where operator is UNION, UNION ALL,
INTERSECT, or MINUS)

Both queries must have same number of select fields and same data
types in same order

UNION suppresses duplicate values

UNION ALL includes duplicate values

INTERSECT takes only matching fields

MINUS takes only fields in query1 not query2
109 2010 Wipro Ltd Internal & Restricted
Creating and Using Database Views
Similar to storing the result of a query in the database

Based on a source query that:
can specify a subset of a single tables fields or records
can join multiple tables

Can be used to enforce security (user has access to view but
not underlying table)
110 2010 Wipro Ltd Internal & Restricted
Creating and Using Database Views
Views can be updateable if:
SELECT clause contains only fieldnames, no functions or
calculations
cannot contain the ORDER BY, DISTINCT, or GROUP BY clauses,
group functions, or set operators
search condition cannot contain a nested query

Views are used like tables for selecting, inserting, updating and
deleting data (only updatable views can be modified)
111 2010 Wipro Ltd Internal & Restricted
Creating and Deleting Views
CREATE OR REPLACE VIEW view_name AS source_query;
DROP VIEW viewname;
112 2010 Wipro Ltd Internal & Restricted
Summary
A database stores all organizational data in a central location
Database management system (DBMS) provides a central set
of common functions for managing a database, including
Inserting
Updating
Retrieving
Deleting data values
Most modern databases are relational databases
Store data in a tabular format
Columns represent different data fields
Rows contain individual data records
113 2010 Wipro Ltd Internal & Restricted
Summary
In a relational database
Data about different entities is stored in separate tables
You create relationships that link related data using key
fields
A database system consists of
DBMS: manages the physical data storage
Database applications: provide the user interface to the
database
Many database systems use a client/server architecture
DBMS runs as a server process
Database applications run as client processes


114 2010 Wipro Ltd Internal & Restricted
Summary
SQL commands include:
Data description language (DDL) commands: create, modify,
Deleted database objects
Data manipulation language (DML) commands: insert,
update, delete, view database data
To create a table:
specify the table name, the name of each data field, and the
data type and size of each data field
Data types ensure correct data values
Constraints restrict values of database fields
SQL*Plus commands are not case sensitive
115 2010 Wipro Ltd Internal & Restricted
Summary
Errors include line number, position, error
code
Use DESCRIBE command to display a tables
fieldnames and data types
Tables can be modified or deleted but some
changes are restricted
116 2010 Wipro Ltd Internal & Restricted
Summary
Use INSERT commands to add data
NUMBER, DATE and INTERVAL data types can be converted
to and from character strings using format models
Database changes are made within a transaction that can be
committed or rolled back
Use search conditions to specify records to update, delete or
select
Arithmetic, logical, grouping, and built-in Oracle functions can be
used to specify search conditions and manipulate data
Query output can be formatted by modifying SELECT clause
117 2010 Wipro Ltd Internal & Restricted
Summary
Results from more than one table related through foreign key
relationships can be combined in a join
Results from more than one unrelated table can be combined
using set operators
Queries can be saved by creating a view
Views can be used like tables to select, insert, update and
delete data
118 2010 Wipro Ltd Internal & Restricted
References
119 2010 Wipro Ltd Internal & Restricted 119 2010 Wipro Ltd Internal & Restricted
References
1.http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/toc.htm
2.Oracle Database 10g SQL - Oracle Press Book

2010 Wipro Ltd Internal & Restricted
Thank You

You might also like