Download presentation
Presentation is loading. Please wait.
1
Chapter 1 Overview of Database Concepts
Oracle 12c: SQL Chapter 1 Overview of Database Concepts
2
Objectives Define database terms
Identify the purpose of a database management system (DBMS) Explain database design using entity-relationship models and normalization Explain the purpose of a Structured Query Language (SQL) Understand how this textbook’s topics are sequenced and how the two sample databases are used
3
Database Terminology Database – logical structure to store data
Database management system (DBMS) – software used to create and interact with the database 3
4
Database Components Character Field Record File 4
5
Database Components - Character
Basic unit of data Can be a letter, number, or special symbol 5
6
Database Components - Field
A group of related characters Represents an attribute or characteristic of an entity Corresponds to a column in the physical database 6
7
Database Components - Record
A collection of fields for one specific entity Corresponds to a row in the physical database 7
8
Database Components - File
A group of records about the same type of entity 8
9
Components Example
10
Database Example 10
11
Database Management System
Data storage: manage the physical structure of the database Security: control user access and privileges Multiuser access: manage concurrent data access Backup: enable recovery options for database failures Data access language: provide a language that allows database access Data integrity: enable constraints or checks on data Data dictionary: maintain information about database structure 11
12
Database Design Systems Development Life Cycle (SDLC)
Entity-relationship model (E-R model) Normalization 12
13
Systems Development Life Cycle (SDLC)
Systems investigation – understanding the problem Systems analysis – understanding the solution Systems design – creating the logical and physical components Systems implementation – placing completed system into operation Systems maintenance and review – evaluating the implemented system 13
14
Entity-Relationship Model (E-R Model)
Used to depict the relationship that exists among entities The following relationships can be included in an E-R model: One-to-one One-to-many Many-to-many
15
E-R Model Notation Examples
15
16
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 Social Security number (SSN) and each SSN is assigned to just one person 16
17
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: A class has only one instructor, but each instructor can teach many classes 17
18
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 18
19
JustLee Example E-R Model
19
20
Database Normalization
Determines required tables and columns for each table Multistep process Used to reduce or control data redundancy 20
21
Database Normalization (continued)
Data redundancy – refers to having the same data in different places within a database Data anomalies – refers to data inconsistencies
22
Unnormalized Data Contains repeating groups in the Author column in the BOOKS table
23
First-Normal Form (1NF)
Primary key is identified Repeating groups are eliminated 23
24
First-Normal Form (1NF) (continued)
ISBN and Author columns together create a composite primary key
25
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 25
26
Second-Normal Form (2NF)
Partial dependency must be eliminated Break the composite primary key into two parts, each part representing a separate table 26
27
Second-Normal Form (2NF) (continued)
BOOKS table in 2NF
28
Third-Normal Form (3NF)
Publisher contact name has been removed
29
Summary of Normalization Steps
1NF: eliminate repeating groups, identify the primary key 2NF: table is in 1NF, and partial dependencies are eliminated 3NF: table is in 2NF, and transitive dependencies are eliminated 29
30
Relating Tables within the Database
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 30
32
Lookup Table Common reference for descriptive data tables referenced in a foreign key
33
Structured Query Language (SQL)
Data sublanguage Used to: Create or modify tables Add data to tables Edit data in tables Retrieve data from tables ANSI and ISO standards 33
34
Databases Used in this Textbook – JustLee Books Database
Assumptions No back orders or partial shipments Only U.S. addresses Completed orders are transferred to the annual SALES table at the end of each month to enable faster processing on the ORDERS table 34
35
Topic Sequence The first half of the text will focus on creating a database The second half of the text will focus on querying or retrieving data from a database 35
36
Summary A DBMS is used to create and maintain a database
A database is composed of a group of interrelated tables A file is a group of related records; a file is also called a table in the physical database A record is a group of related fields regarding one specific entity; a record is also called a row A record is considered unnormalized if it contains repeating groups 36
37
Summary (continued) A record is in first-normal form (1NF) if no repeating groups exist and it has a primary key Second-normal form (2NF) is achieved if the record is in 1NF and has no partial dependencies After a record is in 2NF and all transitive dependencies have been removed, then it is in third-normal form (3NF), which is generally sufficient for most databases A primary key is used to uniquely identify each record 37
38
Summary (continued) A common field is used to join data contained in different tables A foreign key is a common field that exists between two tables but is also a primary key in one of the tables A lookup table is a common term for a table referenced in a foreign key A Structured Query Language (SQL) is a data sublanguage that navigates the data stored within a database’s tables 38
39
Chapter 2 Basic SQL SELECT Statements
Oracle 12c: SQL Chapter 2 Basic SQL SELECT Statements
40
Objectives Create the initial database
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 Display multiple columns of a table
41
Objectives (continued)
Use a column alias to clarify the contents of a particular column Perform basic arithmetic operations in the SELECT clause Remove duplicate lists using either the DISTINCT or UNIQUE keyword Use concatenation to combine fields, literals, and other data 41
42
Create the JustLee Database
Use the provided script to create the database so you can follow the chapter examples Verify table contents using the DESCRIBE command 42
43
SELECT Statement Syntax
SELECT statements are used to retrieve data from the database A SELECT statement is referred to as a query Syntax gives the basic structure, or rules, for a command Optional clauses and keywords are shown in brackets 43
44
SELECT Statement Syntax (continued)
44
45
SELECT Statement Syntax (continued)
SELECT and FROM clauses are required SELECT clause identifies column(s) FROM clause identifies table(s) Each clause begins with a keyword 45
46
Selecting All Data in a Table
Substitute an asterisk for the column names in a SELECT clause 46
47
Selecting One Column from a Table
Enter column name in SELECT clause 47
48
Selecting Multiple Columns from a Table
Separate column names with a comma 48
49
Operations within the SELECT Statement
Column alias can be used for column headings Perform arithmetic operations Suppress duplicates Concatenate data 49
50
Using Column Aliases List the alias after the 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 50
51
Column Alias Example 51
52
Using Arithmetic Operations
Executed left to right Multiplication and division are solved first Addition and subtraction are solved last Override order with parentheses 52
53
Example Arithmetic Operation with Column Alias
53
54
NULL Values 54
55
Using DISTINCT and UNIQUE
Enter DISTINCT or UNIQUE after SELECT keyword to suppress duplicates 55
56
Using Concatenation You can combine data with a string literal
Use the concatenation operator, || It allows the use of column aliases 56
57
Concatenation Example
57
58
Summary A basic query in Oracle 12c SQL includes the SELECT and FROM clauses, the only mandatory clauses in a SELECT statement To view all columns in the table, specify an asterisk (*) or list all of the column names individually in the SELECT clause To display a specific column or set of columns, list the column names in the SELECT clause (in the order in which you want them to appear) When listing column names in the SELECT clause, a comma must separate column names 58
59
Summary (continued) A column alias can be used to clarify the contents of a particular column; if the alias contains spaces or special symbols, or if you want to display the column with any lowercase letters, you must enclose the column alias in double quotation marks (" ") Indicate the table name following the FROM keyword Basic arithmetic operations can be performed in the SELECT clause NULL values indicate an absence of a value 59
60
Summary (continued) To remove duplicate listings, include either the DISTINCT or UNIQUE keyword To specify which table contains the desired columns, you must list the name of the table after the keyword FROM Use vertical bars (||) to combine, or concatenate, fields, literals, and other data 60
61
Chapter 3 Table Creation and Management
Oracle 12c: SQL Chapter 3 Table Creation and Management
62
Objectives Identify the table name and structure
Create a new table using the CREATE TABLE command Use a subquery to create a new table Add a column to an existing table Modify the definition of a column in an existing table Delete a column from an existing table
63
Objectives (continued)
Mark a column as unused and then delete it at a later time Rename a table Truncate a table Drop a table 63
64
Database Table A database object Stores data for the database
Consists of columns and rows Created and modified through data definition language (DDL) commands 64
65
Table Design Table and column names:
Can contain a maximum 30 characters – no blank spaces Must begin with a letter Can contain numbers, underscore (_), and number sign (#) Must be unique No reserved words are allowed 65
66
Table Design (continued)
66
67
Extended Data Types Introduced in Oracle 12c:
Enables storage of additional data bytes in specific data types Database parameters must be enabled by an Oracle system administrator 67
68
Table Creation 68
69
Defining Columns Column definition list must be enclosed in parentheses Datatype must be specified for each column Maximum of 1,000 columns 69
70
CREATE TABLE Command Example
Virtual Column 70
71
Viewing List of Tables: USER_TABLES
A data dictionary is a typical component of a DBMS that maintains information about database objects You can query the data dictionary to verify all the tables that exist in your schema The USER_TABLES data dictionary object maintains information regarding all your tables 71
72
Viewing Table Structures: DESCRIBE
DESCRIBE displays the structure of a specified table 72
73
Invisible Columns Oracle 12c allows hidden columns 73
74
Table Creation through Subqueries
You can use subqueries to retrieve data from an existing table Requires use of AS keyword New column names can be assigned 74
75
CREATE TABLE…AS 75
76
CREATE TABLE…AS Command Example
77
Modifying Existing Tables
Accomplished through the ALTER TABLE command Use an ADD clause to add a column Use a MODIFY clause to change a column Use a DROP COLUMN to drop a column 77
78
ALTER TABLE Command Syntax
78
79
ALTER TABLE…ADD Command
79
80
ALTER TABLE…MODIFY Command
80
81
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 81
82
ALTER TABLE…DROP COLUMN Command
Can only reference one column per execution Deletion is permanent Cannot delete last remaining column in a table 82
83
ALTER TABLE…SET UNUSED Command
Once marked for deletion, a column cannot be restored Storage space is freed at a later time 83
84
ALTER TABLE…DROP UNUSED Command
Frees up storage space from columns previously marked as unused 84
85
Renaming a Table RENAME…TO is used to rename a table – the old name is no longer valid 85
86
Truncating a Table TRUNCATE TABLE command – rows are deleted
Structure of table remains 86
87
Deleting a Table DROP TABLE command – table structure and contents are deleted 87
88
DROP TABLE without Purge Option
Oracle 10g introduced a recycle bin Dropped tables can be recovered from the recycle bin 88
89
FLASHBACK Command The FLASHBACK command recovers a table from the recycle bin 89
90
Use PURGE to Remove a Table from the Recycle Bin
90
91
PURGE Option Available for DROP TABLE Command
Using the PURGE option will permanently remove a table from the database The table will not be copied into the recycle bin 91
92
Summary You create a table with the CREATE TABLE command
Each column to be contained in the table must be defined in terms of the column name, data type, and for certain data types, the width A table can contain up to 1000 columns Each column name within a table must be unique You can change the structure of a table with the ALTER TABLE command Columns can be added, resized, and even deleted with the ALTER TABLE command Tables can be renamed with the RENAME...TO command 92
93
Summary (continued) To delete all the rows in a table, use the TRUNCATE TABLE command To remove both the structure of a table and all its contents, use the DROP TABLE command A dropped table is moved to the recycle bin and can be recovered using the FLASHBACK TABLE command Using the PURGE option in a DROP TABLE command permanently removes the table, meaning you cannot recover it from the recycle bin 93
94
Oracle 12c: SQL Chapter 4 Constraints
95
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 Understand how constraints can be created when creating a table or modifying an existing table Distinguish between creating constraints at the column level and table level
96
Objectives (continued)
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
97
Objectives (continued)
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
98
Constraints Rules used to enforce business rules, practices, and policies Rules used to ensure accuracy and integrity of data
99
Constraint Types
100
Creating Constraints Use the optional CONSTRAINT keyword during creation to assign a name Let the server name the constraint using the default format SYS_Cn Informative names can assist in debugging
101
Creating Constraints (continued)
When During table creation After table creation, by modifying the existing table How Column level approach Table level approach
102
Creating Constraints at the Column Level
If a constraint is being created at the column level, the constraint applies to the column specified
103
Creating Constraints at the Table Level
Approach can be used to create any constraint type except NOT NULL Required if constraint is based on multiple columns
104
Enforcement of Constraints
All constraints are enforced at the table level If a data value violates a constraint, the entire row is rejected
105
Adding Constraints to Existing Tables
Constraints are added to an existing table with the ALTER TABLE command Add a NOT NULL constraint using MODIFY clause All other constraints are added using ADD clause
106
Using the PRIMARY KEY Constraint
Ensures that columns do not contain duplicate or NULL values Only one per table is allowed
107
Constraint Checked with Data Input
108
PRIMARY KEY Constraint for Composite Key
List column names within parentheses separated by commas
109
Using the FOREIGN KEY Constraint
Requires a value to exist in the referenced column of another table NULL values are allowed Enforces referential integrity Maps to the PRIMARY KEY in parent table
110
FOREIGN KEY Constraint Example
111
Deletion of Foreign Key Values
You cannot delete a value in a parent table referenced by a row in a child table Use ON DELETE CASCADE keywords when creating FOREIGN KEY constraint – it automatically deletes a parent row when the row in a child table is deleted
112
Using the UNIQUE Constraint
No duplicates are allowed in the referenced column NULL values are permitted
113
Using the CHECK Constraint
Updates and additions must meet specified condition
114
Using the NOT NULL Constraint
The NOT NULL constraint is a 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 an existing table using ALTER TABLE…MODIFY command
115
NOT NULL Constraint Example
116
Including Constraints during Table Creation – Column Level
Include in column definition
117
Including Constraints during Table Creation – Table Level
Include at end of column list
118
Multiple Constraints on a Single Column
A column may be included in multiple constraints The order# column is included in a primary key and a foreign key constraint
119
Viewing Constraints – USER_CONSTRAINTS
Display constraint listing for a specific table
120
Viewing Constraints – USER_CONS_COLUMNS
Display constraint listing by column
121
Using DISABLE/ENABLE Use DISABLE or ENABLE clause of ALTER TABLE command
122
Dropping Constraints Constraints cannot be modified; they 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
123
ALTER TABLE…DROP Syntax
124
Drop Constraint Example
125
Drop Constraint Example – Error
126
Summary A constraint is a rule that is applied to data being added to a table The constraint represents business rules, policies, and/or procedures Data violating the constraint is not added to the table A constraint can be included during table creation as part of the CREATE TABLE command or added to an existing table using the ALTER TABLE command
127
Summary (continued) A PRIMARY KEY constraint does not allow duplicate or NULL values in the designated column Only one PRIMARY KEY constraint is allowed in a table A FOREIGN KEY constraint requires that the column entry match a referenced column entry in the referenced table or be NULL A UNIQUE constraint is similar to a PRIMARY KEY constraint except it allows NULL values to be stored in the specified column A CHECK constraint ensures a value meets a specified condition
128
Summary (continued) A NOT NULL constraint ensures a value is provided for a column A constraint can be disabled or enabled using the ALTER TABLE command and the DISABLE and ENABLE keywords A constraint cannot be modified To change a constraint, the constraint must first be dropped with the DROP command and then re-created USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views provide information regarding constraints
129
Chapter 5 Data Manipulation and Transaction Control
Oracle 12c: SQL Chapter 5 Data Manipulation and Transaction Control
130
Objectives Use the INSERT command to add a record to an existing table
Manage virtual columns in data manipulations Use quotes in data values Use a subquery to copy records from an existing table Use the UPDATE command to modify the existing rows of a table Use substitution variables with an UPDATE command
131
Objectives (continued)
Delete records Manage transactions with transaction control commands COMMIT, ROLLBACK, and SAVEPOINT Differentiate between a shared lock and an exclusive lock Use the SELECT…FOR UPDATE command to create a shared lock
132
INSERT Command Used to add rows to existing tables
Identify the table in the INSERT INTO clause Specify data in the VALUES clause Can only add one row at a time to a table
133
INSERT Command Syntax Enclose nonnumeric data in single quotes
If a column list is not provided, a value must be assigned to each column in the table
134
INSERT Command Examples
No Column List Column List
135
Inserting NULL Value Omit column name from INSERT INTO clause column list Substitute two single quotation marks Use NULL keyword NULL value input
136
ON NULL Clause Introduced in Oracle 12c Option with a DEFAULT setting
137
Manage Virtual Column Input
138
Constraint Violations
When you add or modify table data, the data is checked for compliance with any applicable constraints
139
Activating the DEFAULT option
Include a column list in the INSERT statement ignoring the column to use the DEFAULT option Use the DEFAULT keyword as the value for the column
140
Inserting Data from an Existing Table
Substitute subquery for VALUES clause Subquery
141
Modifying Existing Rows
Modify rows using UPDATE command Use UPDATE command to: Add values to an existing row (replace NULL values) Change existing values
142
UPDATE Command UPDATE clause identifies table
SET clause identifies column(s) being changed and new value(s) Optional WHERE clause specifies row(s) to be changed – if omitted, all rows will be updated!
143
UPDATE Command Syntax
144
UPDATE Command Example
145
Substitution Variables
Prompts user for value Identified by ampersand (&) preceding variable name Can be used to create interactive scripts
146
Substitution Variable Example
147
Deleting Rows DELETE command removes a row from a table
WHERE clause determines which row(s) are removed
148
DELETE Command – Omitting WHERE Clause
Omitting WHERE clause removes all rows Example below removes all rows from the acctmanager2 table
149
Transaction Control Statements
Results of data manipulation language (DML) are not permanently updated to a table until explicit or implicit COMMIT occurs Transaction control statements can: Commit data through COMMIT command Undo data changes through ROLLBACK command
150
COMMIT Command 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
151
ROLLBACK Command Used to “undo” changes that have not been committed
Occurs when: ROLLBACK; is executed System restarts after a crash SAVEPOINT marks a specific spot within the transaction Can ROLLBACK to a SAVEPOINT to undo part of the transaction
152
Transaction Control Example
153
Transaction Control Example (continued)
Only undo DML actions after SAVEPOINT
154
Table Locks Prevent users from changing same data or objects Two types
Shared – prevents DML operations on a portion of table Exclusive – locks table preventing other exclusive or shared locks
155
LOCK TABLE Command 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
156
LOCK TABLE Command 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
157
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
158
SELECT…FOR UPDATE Command Syntax
159
Summary Data manipulation language (DML) includes the INSERT, UPDATE, DELETE, COMMIT, and ROLLBACK commands The INSERT INTO command is used to add new rows to an existing table The column list specified in the INSERT INTO clause must match the order of data entered in the VALUES clause A virtual column must be ignored in all DML actions because the database system generates this column value automatically You can use a NULL value in an INSERT INTO command by including the keyword NULL, omitting the column from the column list of the INSERT INTO clause, or entering two single quotes (without a space) in the position of the NULL value
160
Summary (continued) To assign a DEFAULT option value, a column must be excluded from the column list in an INSERT statement or the keyword DEFAULT must be included as the value for the column In a DML statement, two single quotes together must be used to represent a single quote in a value If rows are copied from a table and entered in an existing table by using a subquery in the INSERT INTO command, the VALUES clause must be omitted because it’s irrelevant You can change the contents of a row or group of rows with the UPDATE command You can use substitution variables to allow you to execute the same command several times with different data values
161
Summary (continued) DML operations aren’t stored permanently in a table until a COMMIT command is issued implicitly or explicitly A transaction consists of a set of DML operations committed as a block Uncommitted DML operations can be undone by issuing the ROLLBACK command A SAVEPOINT serves as a marker for a point in a transaction and allows rolling back only a portion of the transaction Use the DELETE command to remove records from a table; if the WHERE clause is omitted, all rows in the table are deleted Table locks can be used to prevent users from mistakenly overwriting changes made by other users
162
Summary (continued) Table locks can be in SHARE mode or EXCLUSIVE mode
EXCLUSIVE mode is the most restrictive table lock and prevents any other user from placing any locks on the same table A lock is released when a transaction control statement is issued, a DDL statement is executed, or the user exits the system by using the EXIT command SHARE mode allows other users to place shared locks on other portions of the table, but it prevents users from placing an exclusive lock on the table The SELECT FOR UPDATE command can be used to place a shared lock for a specific row or rows; the lock isn’t released unless a DDL command is issued or the user exits the system
163
Chapter 6 Additional Database Objects
Oracle 12c: SQL Chapter 6 Additional Database Objects
164
Objectives Define the purpose of a sequence and state how it can be used in a database Explain why gaps may appear in the integers generated by a sequence Use the CREATE SEQUENCE command to create a sequence Call and use sequence values Identify which options cannot be changed by the ALTER SEQUENCE command Delete a sequence 164
165
Objectives (continued)
Create indexes with the CREATE INDEX command Explain the main index structures: B-tree and bitmap Verify index use with the explain plan Introduce variations on conventional indexes, including a function-based index and an index organized table 165
166
Objectives (continued)
Verify index existence via the data dictionary Rename an index with the ALTER INDEX command Remove an index using the DELETE INDEX command Create and remove a public synonym 166
167
Database Objects An object is anything that has a name and defined structure Includes: Table – stores data Sequence – generates sequential integers Index – allows users to quickly locate specific records Synonym – alias for other database objects 167
168
Sequences Used for internal control purposes by providing sequential integers for auditing Used to generate unique value for primary key column Surrogate key = no correlation with actual row contents 168
169
Creating a Sequence Use the CREATE SEQUENCE command
Various intervals are allowed – Default: 1 You can specify the starting number – Default: 1
170
Creating a Sequence (continued)
Can specify MINVALUE for decreasing sequence and MAXVALUE for increasing sequence Numbers can be reused if CYCLE is specified ORDER clause is used in application cluster environment Use CACHE to pregenerate integers – Default: 20 170
171
Creating a Sequence (continued)
171
172
Creating a Sequence (continued)
To verify the settings for options of a sequence, query USER_SEQUENCES data dictionary view Next Number to issue
173
Using Sequence Values NEXTVAL – generates integer
174
Using Sequence Values (continued)
CURRVAL – contains last integer generated by NEXTVAL
175
Using Sequence Values (continued)
Set column DEFAULT value
176
Altering Sequence Definitions
Use ALTER SEQUENCE command to change the settings for a sequence START WITH value cannot be altered – drop the sequence and re-create it Changes cannot make current integers invalid 176
177
ALTER SEQUENCE Command Example
177
178
Removing a Sequence Use the DROP SEQUENCE command to delete a sequence
Previous values generated are not affected by removing a sequence from a database
179
Removing a Sequence (continued)
180
Create an Identity Column
Alternative to using sequences to populate primary key columns
181
Using an Identity Column
182
Indexes An index stores frequently referenced values and ROWIDs
Can be based on one column, multiple columns, functions, or expressions 182
183
B-Tree Index 183
184
B-Tree Index (continued)
Implicitly create an index by PRIMARY KEY and UNIQUE constraints Explicitly create an index by using the CREATE INDEX command 184
185
CREATE INDEX Command Examples
185
186
The Explain Plan 186
187
Bitmap Indexes 187
188
Function-Based Indexes
188
189
Index Organized Tables
An IOT stores table contents in a B-tree index structure Use the “ORGANIZATION INDEX” option in a CREATE TABLE statement to build an IOT
190
Verifying an Index Use the USER_INDEXES data dictionary view to determine that the index exists Use the USER_IND_COLUMNS data dictionary view to determine the column index information
191
Verifying an Index (continued)
192
USER_IND_COLUMNS 192
193
Removing an Index Use the DROP INDEX command to remove an index
194
Synonyms Synonyms serve as permanent aliases for database objects
Simplify object references Can be private or public Private synonyms are only available to the user who created them PUBLIC synonyms are available to all database users 194
195
CREATE SYNONYM Command Syntax
195
196
CREATE SYNONYM Command
196
197
Deleting a SYNONYM A private synonym can be deleted by its owner
A PUBLIC synonym can only be deleted by a user with DBA privileges
198
Summary A sequence can be created to generate a series of integers
The values generated by a sequence can be stored in any table A sequence is created with the CREATE SEQUENCE command Gaps in sequences might occur if the values are stored in various tables, if numbers are cached but not used, or if a rollback occurs A value is generated by using the NEXTVAL pseudocolumn The CURRVAL pseudocolumn is NULL until a value is generated by NEXTVAL The USER_OBJECTS data dictionary object can be used to confirm the existence of all schema objects The USER_SEQUENCES data dictionary object is used to view sequence settings A sequence may be set as a column DEFAULT value An identity column can be created to manage primary key population as an alternative to using sequences 198
199
Summary (continued) The ALTER SEQUENCE command is used to modify an existing sequence; the only settings that can’t be modified are the START WITH option and any option that would be invalid because of previously generated values The DUAL table is helpful for testing sequence value generation The DROP SEQUENCE command deletes an existing sequence An index can be created to speed up the query process DML operations are always slower when indexes exist Oracle 11g creates an index for PRIMARY KEY and UNIQUE constraints automatically An explicit index is created with the CREATE INDEX command An index can be used by Oracle 11g automatically if a query criterion or sort operation is based on a column or an expression used to create the index 199
200
Summary (continued) The two main structures for indexes are B-tree and bitmap The explain plan can verify whether an index is used in a query Function-based indexes are used to index an expression or the use of functions on a column or columns An index organized table is a table stored in a B-tree structure to combine the index and table into one database object Information about an index can be retrieved from the USER_INDEXES and USER_IND_COLUMNS views An index can be dropped with the DROP INDEX command An index can be renamed with the ALTER INDEX command 200
201
Summary (continued) Except for a name change, an index can’t be modified; it must be deleted and then re-created A synonym provides a permanent alias for a database object A public synonym is available to any database user A private synonym is available only to the user who created it A synonym is created by using the CREATE SYNONYM command A synonym is deleted by using the DROP SYNONYM command Only a user with DBA privileges can drop a public synonym
202
Chapter 7 User Creation and Management
Oracle 12c: SQL Chapter 7 User Creation and Management
203
Objectives Explain the concept of data security
Create a new user account Identify two types of privileges: system and object Grant privileges to a user Address password expiration requirements Change the password of an existing account 203
204
Objectives (continued)
Create a role Grant privileges to a role Assign a user to a role View privilege information Revoke privileges from a user and a role Remove a user and roles 204
205
Data Security User accounts provide a method of authentication
They can grant access to specific objects They identify owners of objects 205
206
Creating a User The CREATE USER command gives each user a user name and password
207
Assigning User Privileges
There are two types of privileges System privileges Allow access to the database and execution of DDL operations Object privileges Allow a user to perform DML and query operations 207
208
Assigning User Privileges (continued)
Even with a valid user name and password, a user still needs the CREATE SESSION privilege to connect to a database
209
System Privileges Affect a user’s ability to create, alter, and drop objects Use of ANY keyword with an object privilege (INSERT ANY TABLE) is considered a system privilege List of all available system privileges available through SYSTEM_PRIVILEGE_MAP 209
210
SYSTEM_PRIVILEGE_MAP
210
211
Granting System Privileges
System privileges are given through the GRANT command
212
Granting System Privileges (continued)
GRANT clause – identifies system privileges being granted TO clause – identifies receiving user or role WITH ADMIN OPTION clause – allows a user to grant privilege to other database users 212
213
Object Privileges SELECT – display data from table, view, or sequence
INSERT – insert data into table or view UPDATE – change data in a table or view DELETE – remove data from a table or view ALTER – change definition of table or view 213
214
Granting Object Privileges
Grant object privileges through the GRANT command
215
Granting Object Privileges (continued)
GRANT clause – identifies object privileges ON clause – identifies object TO clause – identifies user or role receiving privilege WITH GRANT OPTION clause – gives a user the ability to assign the same privilege to other users 215
216
GRANT Command Examples
216
217
Password Management To change a user password, use the PASSWORD command or the ALTER USER command
218
Utilizing Roles A role is a group, or collection, of privileges
219
Utilizing Roles (continued)
Roles can be assigned to users or other roles
220
Utilizing Roles (continued)
A user can be assigned several roles All roles can be enabled at one time Only one role can be designated as the default role for each user Default role can be assigned through the ALTER USER command 220
221
Utilizing Roles (continued)
Roles can be modified with the ALTER ROLE command Roles can be assigned passwords
222
Viewing Privilege Information
ROLE_SYS_PRIVS lists all system privileges assigned to a role SESSION_PRIVS lists a user’s currently enabled roles 222
223
ROLE_TAB_PRIVS Example
223
224
Removing Privileges and Roles
Revoke system privileges with the REVOKE command
225
Removing Privileges and Roles (continued)
Revoking an object privilege – if the privilege was originally granted using WITH GRANT OPTION, the effect cascades and is revoked from subsequent recipients
226
Removing Privileges and Roles (continued)
226
227
Dropping a Role Users receiving privileges via a role that is dropped will no longer have those privileges available 227
228
Dropping a User The DROP USER command is used to remove a user account
229
Summary Database account management is only one facet of data security
A new user account is created with the CREATE USER command The IDENTIFIED BY clause contains the password for the account System privileges are used to grant access to the database and to create, alter, and drop database objects The CREATE SESSION system privilege is required before a user can access his account on the Oracle server The system privileges available in Oracle 11g can be viewed through the SYSTEM_PRIVILEGE_MAP 229
230
Summary (continued) Object privileges allow users to manipulate data in database objects Privileges are given through the GRANT command The ALTER USER command, combined with the PASSWORD EXPIRE clause, can be used to force a user to change her password upon the next attempted login to the database The ALTER USER command, combined with the IDENTIFIED BY clause, can be used to change a user’s password Privileges can be assigned to roles to make the administration of privileges easier 230
231
Summary (continued) Roles are collections of privileges
The ALTER USER command, combined with the DEFAULT ROLE keywords, can be used to assign a default role(s) to a user Privileges can be revoked from users and roles using the REVOKE command Roles can be revoked from users using the REVOKE command A role can be deleted using the DROP ROLE command A user account can be deleted using the DROP USER command
232
Chapter 8 Restricting Rows and Sorting Data
Oracle 12c: SQL Chapter 8 Restricting Rows and Sorting Data
233
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 Specify a list of values for a search condition using the IN comparison operator 233
234
Objectives (continued)
Search for patterns using the LIKE comparison operator Identify the purpose of the % and _ wildcard characters Join multiple search conditions using the appropriate logical operator Perform searches for NULL values Specify the order for the presentation of query results using an ORDER BY clause 234
235
WHERE Clause Syntax A WHERE clause is used to retrieve rows based on a stated condition Requires: Column name Comparison operator Value or column for comparison Values are case sensitive 235
236
WHERE Clause Example List WHERE clause after FROM clause
Enclose nonnumeric data in single quotes 236
237
Comparison Operators Indicate how the data should relate to the given search value 237
238
Arithmetic Comparison Operators
238
239
Other Comparison Operators
239
240
BETWEEN…AND Operator Finds values in a specified range 240
241
IN Operator Returns records that match a value in a specified list
List must be in parentheses Values are separated by commas 241
242
IN Operator Example 242
243
LIKE Operator Performs pattern searches Used with wildcard characters
Underscore (_) for exactly one character in the indicated position Percent sign (%) represents any number of characters 243
244
LIKE Operator Example 244
245
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 245
246
AND Logical Operator Example
246
247
OR Logical Operator Example
247
248
Multiple Logical Operators
Resolved in order of NOT, AND, OR 248
249
Multiple Logical Operators
Use parentheses to override the order of evaluation 249
250
Resolving Multiple Types of Operators
Arithmetic operators Comparison operators Logical operators 250
251
Treatment of NULL Values
Absence of data Requires use of IS NULL operator 251
252
Treatment of NULL Values (continued)
A common error is using = NULL, which does not raise an Oracle error but also does not return any rows 252
253
ORDER BY Clause Syntax The ORDER BY clause presents data in sorted order Ascending order is default Use DESC keyword to override column default 255 columns maximum 253
254
ORDER BY Clause Syntax 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 254
255
ORDER BY Example 255
256
ORDER BY Can Reference Column Position
256
257
Summary The WHERE clause can be included in a SELECT statement to restrict the rows returned by a query to only those meeting a specified condition When searching a nonnumeric field, the search values must be enclosed in single quotation marks Comparison operators are used to indicate how the record should relate to the search value The BETWEEN...AND comparison operator is used to search for records that fall within a certain range of values 257
258
Summary (continued) The LIKE comparison operator is used with the percent and underscore symbols (% and _) to establish search patterns Logical operators such as AND and OR can be used to combine several search conditions When using the AND operator, all conditions must be TRUE for a record to be returned in the results However, with the OR operator, only one condition must be TRUE A NULL value is the absence of data, not a field with a blank space entered 258
259
Summary (continued) Use the IS NULL comparison operator to match NULL values; the IS NOT NULL comparison operator finds records that do not contain NULL values in the indicated column You can sort the results of queries by using an ORDER BY clause; when used, the ORDER BY clause should be listed last in the SELECT statement By default, records are sorted in ascending order; entering DESC directly after the column name sorts the records in descending order A column does not have to be listed in the SELECT clause to serve as a basis for sorting 259
260
Chapter 9 Joining Data from Multiple Tables
Oracle 12c: SQL Chapter 9 Joining Data from Multiple Tables
261
Objectives Identify 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 261
262
Objectives (continued)
Create a self-join using the WHERE clause Create a self-join using the JOIN keyword 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 262
263
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 263
264
Cartesian Joins 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) 264
265
Cartesian Join Example: Omitted Condition
265
266
Cartesian Join Example: CROSS JOIN Keywords
266
267
Equality Joins Link 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 267
268
Equality Joins: WHERE Clause Example
268
269
Qualifying Column Names
Columns in both tables must be qualified 269
270
WHERE Clause Supports Join and Other Conditions
270
271
Joining More Than Two Tables
Joining four tables requires three join conditions 271
272
Equality Joins: NATURAL JOIN
272
273
No Qualifiers with a NATURAL JOIN
273
274
Equality Joins: JOIN…USING
274
275
Equality Joins: JOIN…ON
Required if column names are different 275
276
JOIN Keyword Overview Use JOIN…USING when tables have one or more columns in common Use JOIN…ON when same named columns are not involved or a condition is needed to specify a relationship other than equivalency (next section) Using the JOIN keyword frees the WHERE clause for exclusive use in restricting rows 276
277
Non-Equality Joins In WHERE clause, use any comparison operator other than the equal sign In FROM clause, use JOIN…ON keywords with a non-equivalent condition 277
278
Non-Equality Joins: WHERE Clause Example
278
279
Non-Equality Joins: JOIN…ON Example
279
280
Self-Joins Used to link a table to itself
Requires the use of table aliases Requires the use of a column qualifier 280
281
Customer Table Example
281
282
Self-Joins: WHERE Clause Example
282
283
Self-Joins: JOIN…ON Example
283
284
Outer Joins Use outer joins to include rows that do not have a match in the other table In WHERE clause, include outer join operator (+) immediately after the column name of the table with missing rows to add NULL rows In FROM clause, use FULL, LEFT, or RIGHT with OUTER JOIN keywords 284
285
Outer Joins: WHERE Clause Example
285
286
Outer Joins: OUTER JOIN Keyword Example
286
287
Outer Joins (continued)
If multiple join conditions are used, the outer join condition may be required in all of the join conditions to retain nonmatching rows 287
288
Outer Joins (continued)
In previous versions of Oracle an error would be raised if the outer join operator is used on the same table in more than one join operation 288
289
Set Operators Used to combine the results of two or more SELECT statements 289
290
Set Operators: UNION Example
290
291
Set Operators: INTERSECT Example
291
292
Set Operators: MINUS Example
292
293
Summary Data stored in multiple tables regarding a single entity can be linked together through the use of joins A Cartesian join between two tables returns every possible combination of rows from the tables; the resulting number of rows is always m * n An equality join is created when the data joining the records from two different tables are an exact match A non-equality join establishes a relationship based upon anything other than an equal condition Self-joins are used when a table must be joined to itself to retrieve needed data 293
294
Summary (continued) Inner joins are categorized as being equality, non-equality, or self-joins An outer join is created when records need to be included in the results without having corresponding records in the join tables The record is matched with a NULL record so it will be included in the output Set operators such as UNION, UNION ALL, INTERSECT, and MINUS can be used to combine the results of multiple queries 294
295
Chapter 10 Selected Single-Row Functions
Oracle 12c: SQL Chapter 10 Selected Single-Row Functions
296
Objectives Use the UPPER, LOWER, and INITCAP functions to change the case of field values and character strings Manipulate character substrings with the SUBSTR and INSTR functions Nest functions inside other functions Determine the length of a character string using the LENGTH function Use the LPAD and RPAD functions to pad a string to a certain width Use the LTRIM and RTRIM functions to remove specific characters strings Substitute character string values with the REPLACE and TRANSLATE functions
297
Objectives (continued)
Round and truncate numeric data using the ROUND and TRUNC functions Return the remainder only of a division operation using the MOD function Use the ABS function to set numeric values as positive Use the POWER function to raise a number to a specified power Calculate the number of months between two dates using the MONTHS_BETWEEN function Manipulate date data using the ADD_MONTHS, NEXT_DAY, LAST_DAY, and TO_DATE functions
298
Objectives (continued)
Differentiate between CURRENT_DATE and SYSDATE values Extend pattern matching capabilities with regular expressions 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 Perform condition processing similar to an IF statement with the DECODE function Use the SOUNDEX function to identify character phonetics Convert string values to numeric with the TO_NUMBER function Use the DUAL table to test functions
299
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 (covered in the next chapter)
300
Types of Functions
301
Case Conversion Functions
Case conversion functions alter the case of data stored in a column or character string Used in a SELECT clause, they alter the appearance of the data in the results Used in a WHERE clause, they alter the value for comparison
302
LOWER Function Used to convert characters to lowercase letters
303
UPPER Function Used to convert characters to uppercase letters
It can be used in the same way as the LOWER function To affect the display of characters, it is used in a SELECT clause To modify the case of characters for a search condition, it is used in a WHERE clause The syntax for the UPPER function is UPPER(c) Where c is the character string or field to be converted into uppercase characters
304
INITCAP Function Used to convert characters to mixed case
305
Character Manipulation Functions
Character manipulation functions manipulate data by extracting substrings, counting the number of characters, replacing strings, etc.
306
SUBSTR Function Used to return a substring, or portion of a string
307
INSTR Function
308
Nesting Functions
309
LENGTH Function Used to determine the number of characters in a string
310
LPAD and RPAD Functions
Used to pad, or fill in, a character string to a fixed width
311
LTRIM and RTRIM Functions
Used to remove a specific string of characters
312
REPLACE Function Substitutes a string with another specified string
313
TRANSLATE Function
314
CONCAT Function Used to concatenate two character strings
315
Number Functions Allow for manipulation of numeric data ROUND TRUNC
MOD ABS
316
ROUND Function Used to round numeric columns to a stated precision
317
TRUNC Function Used to truncate a numeric value to a specific position
318
MOD Function
319
ABS Function
320
Date Functions Used to perform date calculations or format date values
Subtract date for number of days difference
321
MONTHS_BETWEEN Function
Determines the number of months between two dates
322
ADD_MONTHS Function Adds a specified number of months to a date
323
NEXT_DAY Function Determines the next occurrence of a specified day of the week after a given date
324
TO_DATE Function Converts various date formats to the internal format (DD-MON-YY) used by Oracle 11g
325
Format Model Elements - Dates
326
ROUND Function
327
TRUNC Function
328
Regular Expressions Regular expressions allow the description of complex patterns in textual data
329
REGEXP_LIKE
330
Other Functions NVL NVL2 TO_CHAR DECODE SOUNDEX
331
NVL Function Substitutes a value for a NULL value
332
NVL2 Function Allows different actions based on whether a value is NULL
333
NULLIF Function
334
TO_CHAR Function Converts dates and numbers to a formatted character string
335
Format Model Elements – Time and Number
336
DECODE Function Determines action based upon values in a list
337
CASE Expression
338
SOUNDEX Function References phonetic representation of words
339
TO_NUMBER Function
340
DUAL Table Dummy table Consists of one column and one row
Can be used for table reference in the FROM clause
341
Using DUAL
342
Summary Single-row functions return a result for each row or record processed Case conversion functions such as UPPER, LOWER, and INITCAP can be used to alter the case of character strings Character manipulation functions can be used to extract substrings (portions of a string), identify the position of a substring in a string, replace occurrences of a string with another string, determine the length of a character string, and trim spaces or characters from strings Nesting one function within another allows multiple operations to be performed on data
343
Summary (continued) Simple number functions such as ROUND and TRUNC can round or truncate a number on both the left and right side of a decimal The MOD function is used to return the remainder of a division operation Date functions can be used to perform calculations with dates or to change the format of dates entered by a user Regular expressions enable complex pattern matching operations The NVL, NVL2, and NULLIF functions are used to address problems encountered with NULL values
344
Summary (continued) The TO_CHAR function lets a user present numeric data and dates in a specific format The DECODE function allows an action to be taken to be determined by a specific value The searched CASE expression enables you to evaluate conditions to determine the resulting value The SOUNDEX function looks for records based on the phonetic representation of characters The DUAL table can be helpful when testing functions
345
Chapter 11 Group Functions
Oracle 12c: SQL Chapter 11 Group Functions
346
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 Use the MIN and MAX functions with nonnumeric fields
347
Objectives (continued)
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 State the maximum depth for nesting group functions Nest a group function inside of a single-row function
348
Objectives (continued)
Calculate the standard deviation and variance of a set of data, using the STDDEV and VARIANCE functions Explain the concept of multidimensional analysis Perform enhanced aggregation grouping with the GROUPING SETS, CUBE, and ROLLUP Use composite columns and concatenated groupings in grouping operations
349
Group Functions Return one result per group of rows processed
Are also called multiple-row and aggregate functions All group functions ignore NULL values except COUNT(*) Use DISTINCT to suppress duplicate values
350
Added Clauses
351
SUM Function Calculates total amount stored in a numeric column for a group of rows
352
AVG Function Calculates the average of numeric values in a specified column
353
COUNT Function Two purposes Count non-NULL values
Count total records, including those with NULL values
354
COUNT Function – Non-NULL Values
Include column name in argument to count number of occurrences
355
COUNT Function – NULL Values
Include asterisk in argument to count number of rows
356
MAX Function Returns largest value
357
MIN Function Returns the smallest value
358
Datatypes The COUNT, MIN, and MAX functions can be used on values with character, numeric, and date datatypes
359
Grouping Data GROUP BY clause Used to group data
Must be used for any individual column in the SELECT clause with a group function Cannot reference column aliases
360
GROUP BY Example
361
Common Error A common error is missing a GROUP BY clause for nonaggregated columns in the SELECT clause
362
Restricting Aggregated Output
HAVING clause serves as the WHERE clause for grouped data
363
Restricting Aggregated Output (continued)
When included in the same SELECT statement, the clauses are evaluated in the order of: WHERE GROUP BY HAVING
364
Restricting Aggregated Output (continued)
365
Nesting Functions Inner function is resolved first
Maximum nesting depth: 2
366
Statistical Group Functions
Based on normal distribution Includes: STDDEV VARIANCE
367
STDDEV Function
368
VARIANCE Function Determines data dispersion within a group
369
Enhanced Aggregation for Reporting
Oracle provides extensions to the GROUP BY clause, which allow both aggregation across multiple dimensions or the generation of increasing levels of subtotals with a single SELECT statement A dimension is a term used to describe any category used in analyzing data, such as time, geography, and product line Each dimension could contain various levels of aggregation; for example, the time dimension may include aggregation by month, quarter, and year
370
Excel Pivot Table Example
371
Excel Pivot Table Example (continued)
372
Grouping Sets
373
CUBE
374
ROLLUP
375
Pattern Matching
376
Summary The AVG, SUM, STDDEV, and VARIANCE functions are used only with numeric fields The COUNT, MAX, and MIN functions can be applied to any datatype The AVG, SUM, MAX, MIN, STDDEV, and VARIANCE functions all ignore NULL values By default, the AVG, SUM, MAX, MIN, COUNT, STDDEV, and VARIANCE functions include duplicate values
377
Summary (continued) The GROUP BY clause is used to divide table data into groups If a SELECT clause contains both an individual field name and a group function, the field name must also be included in a GROUP BY clause The HAVING clause is used to restrict groups in a group function Group functions can be nested to a depth of only two. The inner function is always performed first, using the specified grouping. The results of the inner function are used as input for the outer function.
378
Summary (continued) The STDDEV and VARIANCE functions are used to perform statistical analyses on a set of data GROUPING SETS operations can be used to perform multiple GROUP BY aggregations with a single query The CUBE extension of the GROUP BY calculates aggregations for all possible combinations or groupings of columns included The ROLLUP extension of the GROUP BY calculates increasing levels of accumulated subtotals for the column list provided Composite columns and concatenated groupings can be used in GROUPING SETS, CUBE, and ROLLUP operations The GROUP_ID function helps eliminate duplicate grouping results
379
Chapter 12 Subqueries and Merge Statements
Oracle12c: SQL Chapter 12 Subqueries and Merge Statements
380
Objectives Determine when using a subquery is appropriate
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 380
381
Objectives (continued)
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
382
Objectives (continued)
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 Use a subquery in a DML action Process multiple DML actions with a MERGE statement
383
Subqueries and Their Uses
Subquery – a query nested inside another query Used when a query is based on an unknown value Requires SELECT and FROM clauses Must be enclosed in parentheses Place on right side of comparison operator 383
384
Types of Subqueries 384
385
Single-Row Subqueries
Can only return one result to the outer query Operators include =, >, <, >=, <=, < >
386
Single-Row Subquery in a WHERE Clause
Used for comparison against individual data
387
Single-Row Subquery in a HAVING Clause
Required when returned value is compared to grouped data
388
Single-Row Subquery in a SELECT Clause
Replicates subquery value for each row displayed
389
Multiple-Row Subqueries
Return more than one row of results Require use of IN, ANY, ALL, or EXISTS operators
390
ANY and ALL Operators Combine with arithmetic operators
391
Multiple-Row Subquery in a WHERE Clause
Note: Could use IN operator or =ANY 391
392
Multiple-Row Subquery in a WHERE Clause (continued)
392
393
Multiple-Row Subquery in a HAVING Clause
393
394
Multiple-Column Subqueries
Return more than one column in results Can return more than one row Column list on the left side of operator must be in parentheses Use the IN operator for WHERE and HAVING clauses 394
395
Multiple-Column Subquery in a FROM Clause
Creates a temporary table
396
Multiple-Column Subquery in a WHERE Clause
Returns multiple columns for evaluation
397
NULL Values When a subquery might return NULL values, use NVL function
398
Uncorrelated Subqueries
Processing sequence Inner query is executed first Result is passed to outer query Outer query is executed 398
399
Correlated Subqueries
Inner query is executed once for each row processed by the outer query Inner query references the row contained in the outer query 399
400
Correlated Subqueries (continued)
400
401
Nested Subqueries Maximum of 255 subqueries if nested in the WHERE clause No limit if nested in the FROM clause Innermost subquery is resolved first, then the next level, etc. 401
402
Nested Subqueries (continued)
Innermost is resolved first (A), then the second level (B), then the outer query (C)
403
Subquery Factoring Clause
WITH dcount AS ( SELECT deptno, COUNT(*) AS dcount FROM employees GROUP BY deptno) SELECT e.lname Emp_Lastname, e.deptno e_dept, d1.dcount edept_count, m.lname manager_name, m.deptno mdept, d2.dcount mdept_count FROM employees e, dcount d1, employees m, dcount d2 WHERE e.deptno = d1.deptno AND e.mgr = m.empno AND m.deptno = d2.deptno AND e.mgr = '7839';
404
Subquery in a DML action
405
MERGE Statement With a MERGE statement, a series of DML actions can occur with a single SQL statement Conditionally updates one data source based on another 405
406
MERGE Statement (continued)
406
407
MERGE Statement (continued)
The following explains each part of the previous MERGE statement: MERGE INTO books_1 a: The BOOKS_1 table is to be changed and a table alias of “a” is assigned to this table USING books_2 b: The BOOKS_2 table will provide the data to update and/or insert into BOOKS_1 and a table alias of “b” is assigned to this table ON (a.isbn = b.isbn): The rows of the two tables will be joined or matched based on isbn WHEN MATCHED THEN: If a row match based on ISBN is discovered, execute the UPDATE action in this clause. The UPDATE action instructs the system to modify only two columns (Retail and Category) WHEN NOT MATCHED THEN: If no match is found based on the ISBN (a books exists in BOOKS_2 that is not in BOOKS_1), then perform the INSERT action in this clause 407
408
MERGE with WHERE conditions
408
409
MERGE with DELETE 409
410
Summary A subquery is a complete query nested in the SELECT, FROM, HAVING, or WHERE clause of another query The subquery must be enclosed in parentheses and have a SELECT and a FROM clause, at a minimum Subqueries are completed first; the result of the subquery is used as input for the outer query A single-row subquery can return a maximum of one value Single-row operators include =, >, <, >=, <=, and <> Multiple-row subqueries return more than one row of results 410
411
Summary (continued) Operators that can be used with multiple-row subqueries include IN, ALL, ANY, and EXISTS Multiple-column subqueries return more than one column to the outer query NULL values returned by a multiple-row or multiple-column subquery will not present a problem if the IN or =ANY operator is used Correlated subqueries reference a column contained in the outer query Subqueries can be nested to a maximum depth of 255 subqueries in the WHERE clause of the parent query 411
412
Summary (continued) With nested subqueries, the innermost subquery is executed first, then the next highest level subquery is executed, and so on, until the outermost query is reached A MERGE statement allows multiple DML actions to be conditionally performed while comparing data of two tables
413
Oracle 12c: SQL Chapter 13 Views
414
Objectives Create a view by using CREATE VIEW command or the CREATE OR REPLACE VIEW command Employ the FORCE and NOFORCE options State the purpose of the WITH CHECK OPTION constraint Explain the effect of the WITH READ ONLY option Update a record in a simple view Re-create a view 414
415
Objectives (continued)
Explain the implication of an expression in a view for DML operations Update a record in a complex view 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 Create a materialized view to replicate data 415
416
Views Permanent objects that store no data Store a query Two purposes
Reduce complex query requirements Restrict users’ access to sensitive data 416
417
Types of Views 417
418
Creating a View You use the CREATE VIEW keywords to create a view
Use OR REPLACE if the view already exists Use FORCE if the underlying table does not exist at the time of creation Provide new column names if necessary
419
Creating a View (continued)
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 419
420
Creating a Simple View Only references one table – no group functions, GROUP BY clause, or expressions
421
DML Operations on a Simple View
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 421
422
Creating a Complex View
A 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
423
DML Operations on a Complex View with an Arithmetic Expression
424
DML Operations on a Complex View Containing Data from Multiple Tables
DML operations cannot be performed on non-key-preserved tables, but they are permitted on key-preserved tables
425
DML Operations on a Complex View Containing Data from Multiple Tables (continued)
426
DML Operations on a Complex View Containing Functions or Grouped Data
DML operations are not permitted if the view includes a group function or a GROUP BY clause
427
DML Operations on a Complex View Containing Functions or Grouped Data (continued)
427
428
DML Operations on a Complex View Containing DISTINCT or ROWNUM
DML operations on a view that contains the DISTINCT keyword or ROWNUM are not permitted
429
Dropping a View Use DROP VIEW command
430
Creating an Inline View
An inline view is a temporary table created by using a subquery in the FROM clause It can only be referenced while the command is being executed Most common usage – “TOP-N” analysis 430
431
“TOP-N” Analysis ORDER BY included to identify top values:
Descending for highest values Ascending for lowest values Extract data based on ROWNUM
432
“TOP-N” Analysis (continued)
433
“TOP-N” Analysis (continued)
Oracle 12c introduces a new row limiting clause (# rows)
434
“TOP-N” Analysis (continued)
Oracle 12c introduces a new row limiting clause (percent of rows)
435
Cross & Outer Apply Joins
A column of the joining table may be used to produce the result set of the inline view
436
Materialized Views Replicate data Store data retrieved from view query
Referred to as “snapshots” 436
437
Materialized Views (continued)
437
438
Materialized Views (continued)
438
439
Summary A view is a temporary or virtual table that is used to retrieve data that exists in the underlying database tables The view query must be executed each time the view is used A view can be used to simplify queries or to restrict access to sensitive data A view is created with the CREATE VIEW command A view cannot be modified; to change a view, it must be dropped and then re-created, or the CREATE OR REPLACE VIEW command must be used 439
440
Summary (continued) Any DML operation can be performed on a simple query if it does not violate a constraint A view that contains expressions or functions, or that joins multiple tables, is considered a complex view A complex view can be used to update only one table; the table must be a key-preserved table Data cannot be added to a view column that contains an expression DML operations are not permitted on non-key-preserved tables
441
Summary (continued) DML operations are not permitted on views that include group functions, a GROUP BY clause, the ROWNUM pseudocolumn, or the DISTINCT keyword Oracle 12c assigns a row number to every row in a table to indicate its position in the table; the row number can be referenced by the keyword ROWNUM A view can be dropped with the DROPVIEW command; the data is not affected, because it exists in the original tables An inline view can be used only by the current statement and can include an ORDER BY clause “TOP-N” analysis uses the row number of sorted data to determine a range of top values Materialized views physically store view query results
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.