Full SQL Updated

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 273

Chapter 1

Overview of Database Concepts

Chapter 1 Oracle9i: SQL 1


Chapter Objectives
• Identify the purpose of a database
management system (DBMS)
• Distinguish a field from a record and a
column from a row
• Define the three types of relationships that
can exist between entities

Chapter 1 Oracle9i: SQL 2


Chapter Objectives
• Identify the problem associated with many-
to-many relationships and the appropriate
solutions
• Explain the purpose of normalization
• Describe the role of a primary key
• Identify partial dependency and transitive
dependency in the normalization process
Chapter 1 Oracle9i: SQL 3
Chapter Objectives
• Explain the purpose of a foreign key
• Determine how to link data in different
tables through the use of a common field
• Explain the purpose of a structured query
language (SQL)

Chapter 1 Oracle9i: SQL 4


Database Terminology
• Database – logical structure to store
data
• Database Management System
(DBMS) – software used to create
and interact with the database

Chapter 1 Oracle9i: SQL 5


Database Components
• Character
• Field
• Record
• File

Chapter 1 Oracle9i: SQL 6


Database Components -
Character
• Basic unit of data
• Can be a letter, number, or special symbol

Chapter 1 Oracle9i: SQL 7


Database Components - Field
• A group of related characters
• Represents an attribute or characteristic of
an entity
• Corresponds to a column in the physical
database

Chapter 1 Oracle9i: SQL 8


Database Components - Record
• A collection of fields for one specific entity
• Corresponds to a row in the physical
database

Chapter 1 Oracle9i: SQL 9


Database Components - File
• A group of records about the same type of
entity

Chapter 1 Oracle9i: SQL 10


Components Example

Chapter 1 Oracle9i: SQL 11


Review of Database Design
• Systems Development Life Cycle (SDLC)
• Normalization

Chapter 1 Oracle9i: SQL 12


Systems Development Life Cycle
(SDLC)
• Systems investigation – understanding the
problem
• Systems analysis – understanding the
solution
• Systems design – creating the logical and
physical components

Chapter 1 Oracle9i: SQL 13


Systems Development Life Cycle
(SDLC)
• Systems implementation – placing
completed system into operation
• Systems maintenance and review –
evaluating the implemented system

Chapter 1 Oracle9i: SQL 14


Relationships
• The following relationships can be
included in an E-R Model:
– One-to-one
– One-to-many
– Many-to-many

Chapter 1 Oracle9i: SQL 15


One-to-one Relationship
• Each occurrence of data in one entity is
represented by only one occurrence of data
in the other entity
• Example: Each individual has just one
Employee id and each Employee id is
assigned to just one person

Chapter 1 Oracle9i: SQL 16


One-to-many Relationship
• Each occurrence of data in one entity can be
represented by many occurrences of the
data in the other entity
• Example: Shashank ---- Employees

Chapter 1 Oracle9i: SQL 17


Many-to-many Relationship
• Data can have multiple occurrences in both
entities
• Example: A student can take many classes
and each class is composed of many
students
• Can not be included in the physical
database

Chapter 1 Oracle9i: SQL 18


Normalization
• Determines required tables and columns for
each table
• Multi-step process
• Used to reduce or control data redundancy

Chapter 1 Oracle9i: SQL 19


Unnormalized Data
Contains repeating Hotels in the Oct_hotel
table

Chapter 1 Oracle9i: SQL 20


First-Normal Form (1NF)
• Primary key is identified
• Repeating groups are eliminated

Chapter 1 Oracle9i: SQL 21


First-Normal Form (1NF)
Oct_hotel_id is the primary key for Oct_hotel (Not null and Unique).

Chapter 1 Oracle9i: SQL 22


Composite Primary Key
• More than one column is required to
uniquely identify a row
• Can lead to partial dependency - a column
is only dependent on a portion of the
primary key

Chapter 1 Oracle9i: SQL 23


Second-Normal Form (2NF)
• Partial dependency must be eliminated
– Break the composite primary key into
two parts, each part representing a
separate table

Chapter 1 Oracle9i: SQL 24


Second-Normal Form (2NF)
Oct_hotel table in 2NF

Chapter 1 Oracle9i: SQL 25


Third-Normal Form (3NF)
Partial and transitive dependency removed.

Chapter 1 Oracle9i: SQL 26


Summary of Normalization Steps
• 1NF: eliminate repeating groups, identify
primary key
• 2NF: table is in 1NF and partial
dependencies eliminated
• 3NF: table is in 2NF and transitive
dependencies eliminated

Chapter 1 Oracle9i: SQL 27


Linking Tables
• Once tables are normalized, make certain
tables are linked
• Tables are linked through a common field
• A common field is usually a primary key in
one table and a foreign key in the other
table

Chapter 1 Oracle9i: SQL 28


Chapter 1 Oracle9i: SQL 29
Structured Query Language
(SQL)
• Data sublanguage
• Used to:
– Create or modify tables
– Add data to tables
– Edit data in tables
– Retrieve data from tables

Chapter 1 Oracle9i: SQL 30


Chapter 2
Basic SQL SELECT Statements
» Select * from oct_hotel;
» Select * from dst_destination;
» Select * from Top_destination;

Chapter 1 Oracle9i: SQL 31


Chapter Objectives
• Distinguish between an RDBMS and an
ORDBMS
• Identify keywords, mandatory clauses, and
optional clauses in a SELECT statement
• Select and view all columns of a table
• Select and view one column of a table

Chapter 1 Oracle9i: SQL 32


Chapter Objectives
• Display multiple columns of a table
• Use a column alias to clarify the contents of
a particular column
• Perform basic arithmetic operations in the
SELECT clause

Chapter 1 Oracle9i: SQL 33


Chapter Objectives
• Remove duplicate lists, using either the
DISTINCT or UNIQUE keyword
• Combine fields, literals, and other data
• Format output

Chapter 1 Oracle9i: SQL 34


Relational Database Management
System (RDBMS)
An RDBMS is the software program used
to create the database and it allows you to
enter, manipulate, and retrieve data

Chapter 1 Oracle9i: SQL 35


Object Relational Database
Management System (ORDBMS)
Same as an RDBMS except it can be used
to reference objects such as maps and object
fields

Chapter 1 Oracle9i: SQL 36


SELECT Statement Syntax
• SELECT statements are used to retrieve
data from the database
• Syntax gives the basic structure, or rules,
for a command

Chapter 1 Oracle9i: SQL 37


SELECT Statement Syntax
Optional clauses and keywords are shown in
brackets

Chapter 1 Oracle9i: SQL 38


SELECT Statement Syntax
• SELECT and FROM clauses are required
• SELECT clause identifies column(s)
• FROM clause identifies table(s)
• Each clause begins with a keyword

Chapter 1 Oracle9i: SQL 39


Selecting All Data in a Table
Substitute an asterisk for the column names in a
SELECT clause
» Select * from oct_hotel;

Chapter 1 Oracle9i: SQL 40


Selecting Column from a Table
Enter column name in SELECT clause

Chapter 1 Oracle9i: SQL 41


Operations Within the SELECT
Statement
• Column alias can be used for column
headings
• Perform arithmetic operations
• Suppress duplicates
• Concatenate data

Chapter 1 Oracle9i: SQL 42


Column Alias
• List after column heading
• AS keyword is optional
• Enclose in double quotation marks:
– If it contains blank space(s)
– If it contains special symbol(s)
– To retain case

Chapter 1 Oracle9i: SQL 43


Column Alias Example

Chapter 1 Oracle9i: SQL 44


Arithmetic Operations
• Executed left to right
• Multiplication and division are solved first
• Addition and subtraction are solved last
• Override order with parentheses

Chapter 1 Oracle9i: SQL 45


Suppressing Duplicates
Enter DISTINCT or UNIQUE after
SELECT keyword
» Select distinct hotel_nme from
oct_hotel;

Chapter 1 Oracle9i: SQL 46


Concatenation
• Can combine data with string literal
• Use concatenation operator, ||
• Allows use of column alias

Chapter 1 Oracle9i: SQL 47


Concatenation Example

Chapter 1 Oracle9i: SQL 48


Chapter 3
Restricting Rows and Sorting
Data

Chapter 1 Oracle9i: SQL 49


Chapter Objectives
• Use a WHERE clause to restrict the rows
returned by a query
• Create a search condition using
mathematical comparison operators
• Use the BETWEEN…AND comparison
operator to identify records within a range
of values

Chapter 1 Oracle9i: SQL 50


Chapter Objectives
• Specify a list of values for a search
condition using the IN comparison operator
• Search for patterns using the LIKE
comparison operator
• Identify the purpose of the % and _
wildcard characters

Chapter 1 Oracle9i: SQL 51


Chapter Objectives
• Join multiple search conditions using the
appropriate logical operator
• Perform searches for null values
• Specify the order for the presentation of
query results, using ORDER BY, DESC,
ASC, and the SELECT clause

Chapter 1 Oracle9i: SQL 52


WHERE Clause
• Used to retrieve rows based on a stated
condition
• Requires:
– Column name
– Comparison operator
– Value or column for comparison
• Case sensitive

Chapter 1 Oracle9i: SQL 53


WHERE Clause Example
• List WHERE clause after FROM clause
• Enclose non-numeric data in single quotes

Chapter 1 Oracle9i: SQL 54


Comparison Operators
Indicates how the data should relate to the
given search value

Chapter 1 Oracle9i: SQL 55


Arithmetic Comparison
Operators

Chapter 1 Oracle9i: SQL 56


Other Comparison Operators

Chapter 1 Oracle9i: SQL 57


IN Operator
• Match a value in a specified list
• List must be in parentheses
• Values separated by commas

Chapter 1 Oracle9i: SQL 58


IN Operator Example

Chapter 1 Oracle9i: SQL 59


LIKE Operator
• Performs pattern searches
• Used with wildcard characters
– Underscore (_) for exactly one character in the
indicated position
– Percent sign (%) to represent any number of
characters

Chapter 1 Oracle9i: SQL 60


LIKE Operator Example

Chapter 1 Oracle9i: SQL 61


Logical Operators
• Used to combine conditions
• Evaluated in order of NOT, AND, OR
– NOT – reverses meaning
– AND – both conditions must be TRUE
– OR – at least one condition must be TRUE

Chapter 1 Oracle9i: SQL 62


AND Logical Operator Example

Chapter 1 Oracle9i: SQL 63


Resolving Multiple Types of
Operators
1. Arithmetic operators
2. Comparison operators
3. Logical operators

Chapter 1 Oracle9i: SQL 64


Treatment of NULL Values
• Absence of data
• Requires use of IS NULL operator

Chapter 1 Oracle9i: SQL 65


ORDER BY Clause
• Presents data in sorted order
• Ascending order is default
• Use DESC keyword to override column
default
• 255 columns maximum

Chapter 1 Oracle9i: SQL 66


Sort Sequence
• In ascending order, values will be listed in
the following sequence:
– Numeric values
– Character values
– NULL values
• In descending order, sequence is reversed

Chapter 1 Oracle9i: SQL 67


ORDER BY Example

Chapter 1 Oracle9i: SQL 68


Chapter 4
Joining Multiple Tables

Chapter 1 Oracle9i: SQL 69


Chapter Objectives
• Create a Cartesian join
• Create an equality join using the WHERE clause
• Create an equality join using the JOIN keyword
• Create a non-equality join using the WHERE
clause
• Create a non-equality join using the JOIN…ON
approach

Chapter 1 Oracle9i: SQL 70


Chapter Objectives
• Create a self-join
• Distinguish an inner join from an outer join
• Create an outer join using the WHERE clause
• Create an outer join using the OUTER keyword
• Use set operators to combine the results of
multiple queries
• Join three or more tables

Chapter 1 Oracle9i: SQL 71


Purpose of Joins
• Joins are used to link tables and reconstruct
data in a relational database
• Joins can be created through:
– Conditions in a WHERE clause
– Use of JOIN keywords in FROM clause

Chapter 1 Oracle9i: SQL 72


Cartesian Join
• Created by omitting joining condition in the
WHERE clause or through CROSS JOIN
keywords in the FROM clause
• Results in every possible row combination
(m * n)

Chapter 1 Oracle9i: SQL 73


Cartesian Join Example:
Omitted Condition
• select * from oct_hotel, dst_destination;
• select * from oct_hotel cross join
dst_destination;

Chapter 1 Oracle9i: SQL 74


Equality Join
• Links rows through equivalent data that
exists in both tables
• Created by:
– Creating equivalency condition in the WHERE
clause
– Using NATURAL JOIN, JOIN…USING, or
JOIN…ON keywords in the FROM clause

Chapter 1 Oracle9i: SQL 75


Equality Join: WHERE Clause
Example

Chapter 1 Oracle9i: SQL 76


Equality Join: NATURAL JOIN
Syntax: tablename NATURAL JOIN tablename

Chapter 1 Oracle9i: SQL 77


Equality Join: JOIN…USING
Syntax: tablename JOIN tablename USING (columnname)

Chapter 1 Oracle9i: SQL 78


Equality Join: JOIN…ON
Syntax: tablename JOIN tablename ON condition

Chapter 1 Oracle9i: SQL 79


JOIN Keyword Overview
• Use NATURAL JOIN when tables have one
column in common
• Use JOIN…USING when tables have more than
one column in common
• Use JOIN…ON when a condition is needed to
specify a relationship other than equivalency
• Using JOIN keyword frees the WHERE clause for
exclusive use in restricting rows

Chapter 1 Oracle9i: SQL 80


Non-Equality Joins
• In WHERE clause, use any comparison
operator other than equal sign
• In FROM clause, use JOIN…ON keywords
with non-equivalent condition

Chapter 1 Oracle9i: SQL 81


Self-Joins
• Used to link a table to itself
• Requires use of column qualifier

Chapter 1 Oracle9i: SQL 82


Self-Join: WHERE Clause
Example

Chapter 1 Oracle9i: SQL 83


Outer Joins
• Use to include rows that do not have a
match in the other table
• In WHERE clause, include outer join
operator (+) next to table with missing rows
to add NULL rows
• In FROM clause, use FULL, LEFT, or
RIGHT with OUTER JOIN keywords

Chapter 1 Oracle9i: SQL 84


Outer Join: WHERE Clause
Example

Chapter 1 Oracle9i: SQL 85


Outer Join: OUTER JOIN
Keyword Example
»select distinct(a.geoname_id),b.name from oct_hotel a
left outer join dst_destination b on
a.geoname_id=b.geoname_id;
»select distinct(a.geoname_id),b.name from oct_hotel a
right outer join dst_destination b on
a.geoname_id=b.geoname_id;
»select distinct(a.geoname_id),b.name from oct_hotel a
full outer join dst_destination b on
a.geoname_id=b.geoname_id;

Chapter 1 Oracle9i: SQL 86


Set Operators
Used to combine the results of two or more
SELECT statements

Chapter 1 Oracle9i: SQL 87


Set Operator Example

»select geoname_id from (select geoname_id from


dst_destination where rownum <11 order by geoname_id desc)
minus
select geoname_id from(selectOracle9i:
Chapter 1
geoname_id
SQL
from dst_destination 88
where rownum <10 order by geoname_id desc);
Joining Three or More Tables
• Same procedure as joining two tables
• Will always results in one less join than the
number of tables being joined

Chapter 1 Oracle9i: SQL 89


Joining Three or More Tables:
Example

Chapter 1 Oracle9i: SQL 90


Chapter 5
Selected Single-Row Functions

Chapter 1 Oracle9i: SQL 91


Chapter Objectives
• Use the UPPER, LOWER, and INITCAP
functions to change the case of field values
and character strings
• Extract a substring using the SUBSTR
function
• Determine the length of a character string
using the LENGTH function

Chapter 1 Oracle9i: SQL 92


Chapter Objectives
• Use the LPAD and RPAD functions to pad a
string to a desired width
• Use the LTRIM and RTRIM functions to remove
specific characters strings
• Round and truncate numeric data using the
ROUND and TRUNC functions
• Calculate the number of months between two
dates using the MONTHS_BETWEEN function

Chapter 1 Oracle9i: SQL 93


Chapter Objectives
• Identify and correct problems associated with
calculations involving null values using the NVL
function
• Display dates and numbers in a specific format
with the TO_CHAR function
• Determine the current date setting using the
SYSDATE keyword
• Nest functions inside other functions

Chapter 1 Oracle9i: SQL 94


Terminology
• Function – predefined block of code that
accepts arguments
• Single-row Function – returns one row of
results for each record processed
• Multiple-row Function – returns one result
per group of data processed

Chapter 1 Oracle9i: SQL 95


Types of Functions

Chapter 1 Oracle9i: SQL 96


Case Conversion Functions
Alter the case of data stored in a column or
character string

Chapter 1 Oracle9i: SQL 97


LOWER Function
Used to convert characters to lower-case
letters

Chapter 1 Oracle9i: SQL 98


UPPER Function
Used to convert characters to upper-case
letters

Chapter 1 Oracle9i: SQL 99


INITCAP Function
Used to convert characters to mixed-case

Chapter 1 Oracle9i: SQL 100


Character Manipulation
Functions
Manipulates data by extracting substrings,
counting number of characters, replacing
strings, etc.

Chapter 1 Oracle9i: SQL 101


SUBSTR Function
Used to return a substring, or portion of a string

Chapter 1 Oracle9i: SQL 102


LENGTH Function
Used to determine the number of characters in a
string

Chapter 1 Oracle9i: SQL 103


LPAD and RPAD Functions
Used to pad, or fill in, a character string to a fixed
width

Chapter 1 Oracle9i: SQL 104


LTRIM and RTRIM Functions
Used to remove a specific string of characters

Chapter 1 Oracle9i: SQL 105


REPLACE Function
Substitutes a string with another specified string

Chapter 1 Oracle9i: SQL 106


CONCAT Function
Used to concatenate two character strings

Chapter 1 Oracle9i: SQL 107


Number Functions
Allows for manipulation of numeric data

Chapter 1 Oracle9i: SQL 108


ROUND Function
Used to round numeric columns to a stated precision

Chapter 1 Oracle9i: SQL 109


TRUNC Function
Used to truncate a numeric value to a specific position

Chapter 1 Oracle9i: SQL 110


Date Functions
Used to perform date calculations or format
date values

Chapter 1 Oracle9i: SQL 111


MONTHS_BETWEEN Function
Determines the number of months between
two dates

Chapter 1 Oracle9i: SQL 112


ADD_MONTHS Function
Adds a specified number of months to a date

Chapter 1 Oracle9i: SQL 113


NEXT_DAY Function
Determines the next occurrence of a
specified day of the week after a given date

Chapter 1 Oracle9i: SQL 114


TO_DATE Function
Converts various date formats to the
internal format (DD-MON-YYYY) used by
Oracle9i

Chapter 1 Oracle9i: SQL 115


Format Model Elements - Dates

Chapter 1 Oracle9i: SQL 116


NVL Function

Substitutes a value for a NULL value


store_name Sales
Store A 300
Store B NULL
Store C 150

»SELECT SUM(NVL(Sales,100)) FROM Sales_Data;

Chapter 1 Oracle9i: SQL 117


NVL2 Function
Allows different actions based on whether a value
is NULL

Chapter 1 Oracle9i: SQL 118


TO_CHAR Function

Converts dates and numbers to a formatted


character string

Chapter 1 Oracle9i: SQL 119


Format Model Elements –
Time and Number

Chapter 1 Oracle9i: SQL 120


Other Functions
• NVL
• NVL2
• TO_CHAR
• DECODE
• SOUNDEX

Chapter 1 Oracle9i: SQL 121


DECODE Function
Determines action based upon values in a list

Chapter 1 Oracle9i: SQL 122


Nesting Functions
• One function is used as an argument inside
another function
• Must include all arguments for each function
• Inner function is resolved first, then outer function

Chapter 1 Oracle9i: SQL 123


Chapter 6
Group Functions

Chapter 1 Oracle9i: SQL 124


Chapter Objectives
• Differentiate between single-row and multiple-row
functions
• Use the SUM and AVG functions for numeric
calculations
• Use the COUNT function to return the number of
records containing non-NULL values
• Use COUNT(*) to include records containing
NULL values

Chapter 1 Oracle9i: SQL 125


Chapter Objectives
• Use the MIN and MAX functions with non-
numeric fields
• Determine when to use the GROUP BY
clause to group data
• Identify when the HAVING clause should be
used
• List the order of precedence for evaluating
WHERE, GROUP BY, and HAVING clauses

Chapter 1 Oracle9i: SQL 126


Chapter Objectives
• State the maximum depth for nesting group
functions
• Nest a group function inside a single-row
function
• Calculate the standard deviation and
variance of a set of data, using the
STDDEV and VARIANCE functions

Chapter 1 Oracle9i: SQL 127


Group Functions
• Return one result per group of rows
processed
• Also called multiple-row and aggregate
functions
• All group functions ignore NULL values
except COUNT(*)
• Use DISTINCT to suppress duplicate values

Chapter 1 Oracle9i: SQL 128


Group by Function
Calculates total amount stored in a numeric
column for a group of rows

Chapter 1 Oracle9i: SQL 129


GROUP BY Clause
• Used to group data
• Must be used for individual column in the
SELECT clause with a group function
• Cannot reference column alias

Chapter 1 Oracle9i: SQL 130


HAVING Clause
Having

Chapter 1 Oracle9i: SQL 131


Order of Clause Evaluation
When included in the same SELECT
statement, evaluated in order of:
– WHERE
– GROUP BY
– HAVING

Chapter 1 Oracle9i: SQL 132


Nesting Functions
• Inner function resolved first
• Maximum nesting depth: 2

Chapter 1 Oracle9i: SQL 133


Chapter 7
Subqueries

Chapter 1 Oracle9i: SQL 134


Chapter Objectives
• Determine when it is appropriate to use a subquery
• Identify which clauses can contain subqueries
• Distinguish between an outer query and a
subquery
• Use a single-row subquery in a WHERE clause
• Use a single-row subquery in a HAVING clause
• Use a single-row subquery in a SELECT clause

Chapter 1 Oracle9i: SQL 135


Chapter Objectives
• Distinguish between single-row and multiple-
row comparison operators
• Use a multiple-row subquery in a WHERE
clause
• Use a multiple-row subquery in a HAVING
clause
• Use a multiple-column subquery in a WHERE
clause

Chapter 1 Oracle9i: SQL 136


Chapter Objectives
• Create an inline view using a multiple-
column subquery in a FROM clause
• Compensate for NULL values in subqueries
• Distinguish between correlated and
uncorrelated subqueries
• Nest a subquery inside another subquery

Chapter 1 Oracle9i: SQL 137


Subquery
• Used when query is based on unknown
value
• A query nested inside another query
• Requires SELECT and FROM clauses
• Must be enclosed in parentheses
• Place on right side of comparison operator

Chapter 1 Oracle9i: SQL 138


Types of Subqueries

Chapter 1 Oracle9i: SQL 139


Single-Row Subquery Operators
• Can only return one result to outer query
• Operators include =, >, <, >=, <=, < >

Chapter 1 Oracle9i: SQL 140


Single-Row Subquery –
In WHERE Clause
Used for comparison against individual data

Chapter 1 Oracle9i: SQL 141


Single-Row Subquery –
In HAVING Clause
Required when returned value is compared
to grouped data

Chapter 1 Oracle9i: SQL 142


Single-Row Subquery –
In SELECT Clause
Replicates subquery value for each row displayed

Chapter 1 Oracle9i: SQL 143


Multiple-Row Subqueries
• Return more than one row of results
• Require use of IN, ANY, ALL, or EXISTS
operators

Chapter 1 Oracle9i: SQL 144


ANY and ALL Operators
Combine with arithmetic operators

Chapter 1 Oracle9i: SQL 145


EXISTS Operator
Determines whether condition exists in subquery

Chapter 1 Oracle9i: SQL 146


Multiple-Row Subquery –
In WHERE Clause

Chapter 1 Oracle9i: SQL 147


Multiple-Row Subquery –
In HAVING Clause

Chapter 1 Oracle9i: SQL 148


Multiple-Column Subquery
• Returns more than one column in results
• Can return more than one row
• Column list on left side of operator must be
in parentheses
• Uses IN operator for WHERE and
HAVING clauses

Chapter 1 Oracle9i: SQL 149


Multiple-Column Subquery –
In FROM Clause
Creates temporary table

Chapter 1 Oracle9i: SQL 150


Multiple-Column Subquery –
In WHERE Clause
Returns multiple columns for evaluation

Chapter 1 Oracle9i: SQL 151


NULL Values
When subquery might return NULL values, use NVL function

Chapter 1 Oracle9i: SQL 152


Uncorrelated Subqueries
• Processing sequence:
– Inner query executed first
– Result passed to outer query
– Outer query executed

Chapter 1 Oracle9i: SQL 153


Correlated Subqueries
• Inner query executed once for each row
processed by outer query
• Inner query references row contained in
outer query

Chapter 1 Oracle9i: SQL 154


Nested Subqueries
• Maximum 255 subqueries if nested in
WHERE clause
• No limit if nested in FROM clause
• Innermost subquery resolved first, then next
level, etc.

Chapter 1 Oracle9i: SQL 155


Nested Subquery Example
Innermost resolved first (3), then second level (2),
then outer query (1)

Chapter 1 Oracle9i: SQL 156


Chapter 8
Table Creation and Management

Chapter 1 Oracle9i: SQL 157


Chapter Objectives
• Create a new table using the CREATE
TABLE command
• Name a new column or table
• Use a subquery to create a new table
• Add a column to an existing table
• Modify the size of a column in an existing
table
Chapter 1 Oracle9i: SQL 158
Chapter Objectives
• Drop a column from an existing table
• Mark a column as unused, then delete it at a
later time
• Rename a table
• Truncate a table
• Drop a table

Chapter 1 Oracle9i: SQL 159


Database Table
• A database object
• Stores data for the database
• Consists of columns and rows
• Created and modified through Data
Definition Language (DDL) commands

Chapter 1 Oracle9i: SQL 160


Table and Column Names
• Maximum 30 characters - no blank spaces
• Must begin with a letter
• Can contain numbers, underscore (_), and
number sign (#)
• Must be unique
• No reserved words allowed

Chapter 1 Oracle9i: SQL 161


Common Datatypes

Chapter 1 Oracle9i: SQL 162


CREATE TABLE Command

Chapter 1 Oracle9i: SQL 163


CREATE TABLE Command
• Column definition list must be enclosed in
parentheses
• Datatype must be specified for each column
• Maximum of 1,000 columns

Chapter 1 Oracle9i: SQL 164


CREATE TABLE Command
Example

Chapter 1 Oracle9i: SQL 165


DESCRIBE Command
Displays structure of specified table

Chapter 1 Oracle9i: SQL 166


Table Creation Through
Subqueries
• Can use subquery to retrieve data from
existing table
• Requires use of AS keyword
• New column names can be assigned

Chapter 1 Oracle9i: SQL 167


CREATE TABLE…AS
Command

Chapter 1 Oracle9i: SQL 168


CREATE TABLE…AS
Command Example

Chapter 1 Oracle9i: SQL 169


Modifying Existing Tables
• Accomplished through ALTER TABLE
command
• Use ADD clause to add a column
• Use MODIFY clause to change a column
• Use DROP COLUMN to drop a column

Chapter 1 Oracle9i: SQL 170


ALTER TABLE Command
Syntax

Chapter 1 Oracle9i: SQL 171


ALTER TABLE…ADD
Command Example

Chapter 1 Oracle9i: SQL 172


ALTER TABLE…MODIFY
Command Example

Chapter 1 Oracle9i: SQL 173


Modification Guidelines
• Column must be as wide as the data it
already contains
• If a NUMBER column already contains
data, size cannot be decreased
• Adding or changing default data does not
affect existing data

Chapter 1 Oracle9i: SQL 174


ALTER TABLE…DROP
COLUMN Command
• Can only reference one column per
execution
• Deletion is permanent
• Cannot delete last remaining column in a
table

Chapter 1 Oracle9i: SQL 175


ALTER TABLE…SET
UNUSED Command
• Once marked for deletion, column cannot
be restored
• Storage space freed at later time

Chapter 1 Oracle9i: SQL 176


ALTER TABLE…DROP
UNUSED Command
Frees up storage space from columns
previously marked as unused

Chapter 1 Oracle9i: SQL 177


RENAME Command
Used to rename a table – old name no longer valid

Chapter 1 Oracle9i: SQL 178


Truncating a Table –
TRUNCATE Command
Rows are deleted - structure of table remains

Chapter 1 Oracle9i: SQL 179


DROP TABLE Command
Table structure and contents are deleted

Chapter 1 Oracle9i: SQL 180


Chapter 9
Constraints

Chapter 1 Oracle9i: SQL 181


Chapter Objectives
• Explain the purpose of constraints in a table
• Distinguish among PRIMARY KEY,
FOREIGN KEY, UNIQUE, CHECK, and
NOT NULL constraints and the appropriate
use for each constraint
• Distinguish between creating constraints at
the column level and table level

Chapter 1 Oracle9i: SQL 182


Chapter Objectives
• Create PRIMARY KEY constraints for a
single column and a composite primary key
• Create a FOREIGN KEY constraint
• Create a UNIQUE constraint
• Create a CHECK constraint

Chapter 1 Oracle9i: SQL 183


Chapter Objectives
• Create a NOT NULL constraint, using the
ALTER TABLE…MODIFY command
• Include constraints during table creation
• Use DISABLE and ENABLE commands
• Use the DROP command

Chapter 1 Oracle9i: SQL 184


Constraints
• Rules used to enforce business rules,
practices, and policies
• Rules used to ensure accuracy and integrity
of data

Chapter 1 Oracle9i: SQL 185


Constraint Types

Chapter 1 Oracle9i: SQL 186


Naming Constraints
• Use optional CONSTRAINT keyword
during creation to assign a name
• Let server name constraint using default
format SYS_Cn

Chapter 1 Oracle9i: SQL 187


Creating Constraints
• When:
– During table creation
– Modify existing table
• How:
– Column level approach
– Table level approach

Chapter 1 Oracle9i: SQL 188


General Syntax – Column Level
If a constraint is being created at the
column level, the constraint applies to the
column specified

Chapter 1 Oracle9i: SQL 189


General Syntax – Table Level
• Approach can be used to create any
constraint type except NOT NULL
• Required if constraint is based on multiple
columns

Chapter 1 Oracle9i: SQL 190


Enforcement
• All constraints are enforced at the table
level
• If a data value violates a constraint, the
entire row is rejected

Chapter 1 Oracle9i: SQL 191


Adding Constraints to Existing
Tables
• Added to existing table with ALTER
TABLE command
• Add NOT NULL constraint using MODIFY
clause
• All other constraints added using ADD
clause

Chapter 1 Oracle9i: SQL 192


PRIMARY KEY Constraint
• Ensures that columns do not contain
duplicate or NULL values
• Only one per table allowed

Chapter 1 Oracle9i: SQL 193


PRIMARY KEY Constraint for
Composite Key
List column names within parentheses
separated by commas

Chapter 1 Oracle9i: SQL 194


FOREIGN KEY Constraint
• Requires a value to exist in referenced
column of other table
• NULL values are allowed
• Enforces referential integrity
• Maps to the PRIMARY KEY in parent
table

Chapter 1 Oracle9i: SQL 195


FOREIGN KEY Constraint -
Example

Chapter 1 Oracle9i: SQL 196


Deletion of Foreign Key Values
• Cannot delete a value in parent table
referenced by a row in child table
• Use ON DELETE CASCADE keywords
when creating FOREIGN KEY constraint –
automatically deletes parent row when row
in child table is deleted

Chapter 1 Oracle9i: SQL 197


UNIQUE Constraint
• No duplicates allowed in referenced column
• NULL values are permitted

Chapter 1 Oracle9i: SQL 198


CHECK Constraint
Updates and additions must meet specified
condition

Chapter 1 Oracle9i: SQL 199


NOT NULL Constraint
• Special CHECK constraint with IS NOT
NULL condition
• Can only be created at column level
• Included in output of DESCRIBE command
• Can only be added to existing table using
ALTER TABLE…MODIFY command

Chapter 1 Oracle9i: SQL 200


NOT NULL Constraint Example

Chapter 1 Oracle9i: SQL 201


Adding Constraints During Table
Creation – Column Level
Include in column definition

Chapter 1 Oracle9i: SQL 202


Adding Constraints During Table
Creation – Table Level
Include at end of column list

Chapter 1 Oracle9i: SQL 203


Viewing Constraints –
USER_CONSTRAINTS
Can display name, type, and condition of
CHECK constraints

Chapter 1 Oracle9i: SQL 204


Disabling/Enabling Constraints
Use DISABLE or ENABLE clause of
ALTER TABLE command

Chapter 1 Oracle9i: SQL 205


Dropping a Constraint
• Constraints cannot be modified, must be
dropped and recreated
• Actual syntax depends on type of constraint
– PRIMARY KEY - just list type of constraint
– UNIQUE - include column name
– All others - reference constraint name

Chapter 1 Oracle9i: SQL 206


ALTER TABLE…DROP Syntax

Chapter 1 Oracle9i: SQL 207


Chapter 10
Data Manipulation

Chapter 1 Oracle9i: SQL 208


Chapter Objectives
• Add a record to an existing table
• Add a record containing a NULL value to
an existing table
• Use a subquery to copy records from an
existing table
• Modify the existing rows within a table

Chapter 1 Oracle9i: SQL 209


Chapter Objectives
• Use substitution variables with an UPDATE
command
• Issue the transaction control statements
COMMIT and ROLLBACK
• Differentiate between DDL, DML, and
transaction control commands

Chapter 1 Oracle9i: SQL 210


Chapter Objectives
• Delete records
• Differentiate between a shared lock and an
exclusive lock
• Use the SELECT…FOR UPDATE
command to create a shared lock

Chapter 1 Oracle9i: SQL 211


INSERT Command
• Used to add rows to existing tables
• Identify table in the INSERT INTO clause
• Specify data in the VALUES clause
• Can only add one row at a time to a table

Chapter 1 Oracle9i: SQL 212


INSERT Command Syntax
• Enclose non-numeric data in single quotes
• If column list not provided, a value must be
assigned to each column in the table

Chapter 1 Oracle9i: SQL 213


INSERT Command Example

Chapter 1 Oracle9i: SQL 214


Inserting NULL Value
• Omit column name from INSERT INTO
clause column list
• Substitute two single quotation marks
• Use NULL keyword

Chapter 1 Oracle9i: SQL 215


Inserting Data from an Existing
Table
Substitute subquery for VALUES clause

Chapter 1 Oracle9i: SQL 216


Modifying Existing Rows
• Modify rows using UPDATE command
• Use UPDATE command to:
– Add values to an existing row
– Change existing values

Chapter 1 Oracle9i: SQL 217


UPDATE Command
• UPDATE clause identifies table
• SET clause identifies column being
changed and new value
• Optional WHERE clause specifies row(s) to
be changed – if omitted, will update all
rows

Chapter 1 Oracle9i: SQL 218


UPDATE Command Syntax

Chapter 1 Oracle9i: SQL 219


UPDATE Command Example

Chapter 1 Oracle9i: SQL 220


Substitution Variables
• Prompts user for value
• Identified by ampersand (&) preceding
variable name
• Can be used to create interactive scripts

Chapter 1 Oracle9i: SQL 221


Substitution Variable Example

Chapter 1 Oracle9i: SQL 222


Transaction Control
• Results of Data Manipulation Language
(DML) are not permanently updated to
table until explicit or implicit COMMIT
occurs
• Transaction control statements can:
– Commit data through COMMIT command
– Undo data changes through ROLLBACK
command
Chapter 1 Oracle9i: SQL 223
COMMIT
• Explicit COMMIT occurs by executing
COMMIT;
• Implicit COMMIT occurs when DDL
command is executed or user properly exits
system
• Permanently updates table(s) and allows
other users to view changes

Chapter 1 Oracle9i: SQL 224


ROLLBACK
• Used to “undo” changes that have not been
committed
• Occurs when:
– ROLLBACK; is executed
– System restarts after crash

Chapter 1 Oracle9i: SQL 225


Deleting Rows
DELETE command removes a row from a table

Chapter 1 Oracle9i: SQL 226


DELETE Command – Omitting
WHERE Clause
Omitting WHERE clause removes all rows

Chapter 1 Oracle9i: SQL 227


Table Locks
• Prevents users from changing same data or
objects
• Two types:
– Shared – prevents DML operations on portion
of table
– Exclusive – locks table preventing other
exclusive or shared locks

Chapter 1 Oracle9i: SQL 228


Shared Lock
• Locks portion of table affected by DML
operation
• Implicitly occurs during UPDATE or
DELETE operations
• Explicitly occurs through LOCK TABLE
command with SHARE MODE option
• Released when COMMIT (implicit or
explicit) or ROLLBACK occurs
Chapter 1 Oracle9i: SQL 229
Exclusive Lock
• Implicitly locks table for DDL operations -
CREATE or ALTER TABLE
• Explicitly locked through LOCK TABLE
command with EXCLUSIVE MODE option
• Released after execution of DDL operation
or after user exits system

Chapter 1 Oracle9i: SQL 230


SELECT…FOR UPDATE
Command
• Creates shared lock on retrieved portion of
table
• Prevents one user from changing a row
while another user is selecting rows to be
changed
• Released through implicit or explicit
commit

Chapter 1 Oracle9i: SQL 231


SELECT…FOR UPDATE
Command – Example

Chapter 1 Oracle9i: SQL 232


Chapter 11
Views

Chapter 1 Oracle9i: SQL 233


Chapter Objectives
• Create a view, using CREATE VIEW
command or the CREATE OR REPLACE
VIEW command
• Employ the FORCE and NO FORCE
options
• State the purpose of the WITH CHECK
OPTION constraint

Chapter 1 Oracle9i: SQL 234


Chapter Objectives
• Explain the effect of the WITH READ
ONLY option
• Update a record in a simple view
• Re-create a view
• Explain the implication of an expression in
a view for DML operations
• Update a record in a complex view
Chapter 1 Oracle9i: SQL 235
Chapter Objectives
• Identify problems associated with adding
records to a complex view
• Identify the key-preserved table underlying
a complex view
• Drop a view
• Explain inline views and the use of
ROWNUM to perform a “TOP-N” analysis
Chapter 1 Oracle9i: SQL 236
Views
• Permanent objects that store no data
• Display data contained in other tables
• Two purposes:
– Reduce complex query requirements for novice
users
– Restrict users’ access to sensitive data

Chapter 1 Oracle9i: SQL 237


Types of Views

Chapter 1 Oracle9i: SQL 238


CREATE VIEW Command
• Use OR REPLACE if view already exists
• Use FORCE if underlying table does not
exist at time of creation
• Provide new column names if necessary

Chapter 1 Oracle9i: SQL 239


CREATE VIEW Options
• WITH CHECK OPTION constraint – if
used, prevents data changes that will make
the data subsequently inaccessible to the
view
• WITH READ ONLY – prevents DML
operations

Chapter 1 Oracle9i: SQL 240


Simple View
Only references one table – no group
functions, GROUP BY clause, or
expressions

Chapter 1 Oracle9i: SQL 241


Simple View – DML Operations
• Any DML operations are allowed through
simple views unless created with WITH
READ ONLY option
• DML operations that violate constraints on
the underlying table are not allowed

Chapter 1 Oracle9i: SQL 242


Complex View
• May contain data from multiple tables or
data created with the GROUP BY clause,
functions, or expressions
• Type of DML operations allowed depends
on various factors

Chapter 1 Oracle9i: SQL 243


DML Operations - Complex
Views with Expressions
Values cannot be inserted into columns that
are based on arithmetic expressions

Chapter 1 Oracle9i: SQL 244


DML Operations – Complex
Views from Multiple Tables
DML operations can not be performed on
non key-preserved tables, but they are
permitted on key-preserved tables

Chapter 1 Oracle9i: SQL 245


DML Operations – Other
Complex Views
No DML operations are permitted on
complex views based on DISTINCT,
ROWNUM, GROUP BY, or a function

Chapter 1 Oracle9i: SQL 246


Dropping a View
Use DROP VIEW command

Chapter 1 Oracle9i: SQL 247


Inline View
• Temporary table created by using subquery
in FROM clause
• Can only be referenced while the command
is being executed
• Most common usage – “TOP-N” Analysis

Chapter 1 Oracle9i: SQL 248


“TOP-N” Analysis
• ORDER BY included to identify top values:
– descending for highest values, ascending for lowest values

• Extract data based on ROWNUM

Chapter 1 Oracle9i: SQL 249


Chapter 12
Additional Database Objects

Chapter 1 Oracle9i: SQL 250


Chapter Objectives
• Define the purpose of a sequence and state
how it can be used by an organization
• Explain why gaps may appear in the
integers generated by a sequence
• Correctly use the CREATE SEQUENCE
command to create a sequence

Chapter 1 Oracle9i: SQL 251


Chapter Objectives
• Identify which options cannot be changed
by the ALTER SEQUENCE command
• Use NEXTVAL and CURRVAL in an
INSERT command
• Explain when Oracle9i will automatically
create an index
• Create an index, using the CREATE
INDEX command
Chapter 1 Oracle9i: SQL 252
Chapter Objectives
• Delete an index, using the DELETE
INDEX command
• Create a PUBLIC synonym
• Delete a PUBLIC synonym
• Identify the contents of different versions of
views used to access the data dictionary,
based on the prefix of the view
Chapter 1 Oracle9i: SQL 253
Database Objects
• Anything that has a name and defined
structure
• Includes:
– Sequence – generate sequential integers
– Index – quickly locate specific records
– Synonym – alias for other database objects

Chapter 1 Oracle9i: SQL 254


Sequences
• Used for internal control purposes by
providing sequential integers for auditing
• Used to generate unique value for primary
key column – no correlation with actual row
contents

Chapter 1 Oracle9i: SQL 255


CREATE SEQUENCE
Command
• Various intervals allowed – Default: 1
• Can specify starting number – Default: 1

Chapter 1 Oracle9i: SQL 256


CREATE SEQUENCE
Command
• Can specify MINVALUE for decreasing
sequence, MAXVALUE for increasing
• Numbers can be reused if CYCLE specified
• ORDER clause for application cluster
environment
• Use CACHE to pre-generate integers –
Default: 20
Chapter 1 Oracle9i: SQL 257
CREATE SEQUENCE
Command Example

Chapter 1 Oracle9i: SQL 258


Verifying Sequence Values
Query USER_SEQUENCES data
dictionary view

Chapter 1 Oracle9i: SQL 259


Using Sequence Values
• NEXTVAL – generates integer
• CURRVAL – contains last integer
generated by NEXTVAL

Chapter 1 Oracle9i: SQL 260


Altering Sequence Definitions
• Use ALTER SEQUENCE command
• START WITH value cannot be altered –
drop sequence and re-create
• Changes cannot make current integers
invalid

Chapter 1 Oracle9i: SQL 261


ALTER SEQUENCE Command
Example

Chapter 1 Oracle9i: SQL 262


DROP SEQUENCE Command
Previous values generated are not affected
by removing a sequence from a database

Chapter 1 Oracle9i: SQL 263


Indexes
• Stores frequently referenced value and row
ID (ROWID)
• Can be based on one column, multiple
columns, functions, or expressions

Chapter 1 Oracle9i: SQL 264


Creating an Index
• Implicitly created by PRIMARY KEY and
UNIQUE constraints
• Explicitly created by CREATE INDEX
command

Chapter 1 Oracle9i: SQL 265


CREATE INDEX Command
Example

Chapter 1 Oracle9i: SQL 266


Verifying an Index
Indexes listed in USER_INDEXES view

Chapter 1 Oracle9i: SQL 267


Removing an Index
Use DROP INDEX command

Chapter 1 Oracle9i: SQL 268


Synonyms
• Serve as permanent aliases for database
objects
• Can be private or public
– Private synonyms are only available to user
who created them
– PUBLIC synonyms are available to all database
users

Chapter 1 Oracle9i: SQL 269


CREATE SYNONYM
Command Syntax

Chapter 1 Oracle9i: SQL 270


CREATE SYNONYM
Command Example

Chapter 1 Oracle9i: SQL 271


Deleting a SYNONYM
• A private synonym can be deleted by owner
• A PUBLIC synonym can only be deleted by
a user with DBA privileges

Chapter 1 Oracle9i: SQL 272


Data Dictionary
• Stores information about database objects
• Owned by user SYS
• Cannot be directly accessed by users
• Displays contents through data dictionary
views

Chapter 1 Oracle9i: SQL 273

You might also like