Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Volume Two S Participant Guide

Edition 1.1 M03990 T1001E11

Authors Neena Kochhar Debby Kramer

Copyright E Oracle Corporation, 1992, 1996. All rights reserved. This documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and disclo sure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the fol lowing legend is applicable: Restricted Rights Legend Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights soft ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS 252.227 7013, Rights in Technical Data and Computer Software (October 1988). This material or any portion of it may not be copied in any form or by any means without the express prior written permission of the Worldwide Education Services group of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the De partment of Defense, then it is delivered with Restricted Rights," as defined in FAR 52.227 14, Rights in Data General, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Worldwide Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, Red wood Shores, CA 94065. Oracle Corporation does not warrant that this document is error free. SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle Server, Discoverer/2000, and Designer/2000 are trademarks or registered trade marks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Technical Contributors and Reviewers Christian Bauwens Debra Bowman Lenny Brunson Jackie Collins Ralf Durben Brian Fry Anthony Holbrook Karlene Jensen Sarah Jones Glenn Maslen Sundar Nagarathnam Sandra Schrick Ulrike Schwinn Rosemarie Truman Jenny Tsai Laura Van Deusen

Publishers Stephanie Jones Kimberly Lee Jennifer Robertson Mark Turangan

7
Specifying Variables at Runtime

72

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
You can create a command file containing a WHERE clause to restrict the rows displayed. To change the condition each time the command file is run, you use substitution variables. Substitution variables can replace values in the WHERE clause, a text string, and even a column or a table name. At the end of this lesson, you should be able to
D D D

Create a SELECT statement that prompts the user to enter a value at runtime. Use the SQL*Plus ACCEPT command to define a variable. Define a variable that can be automatically picked up by the SELECT statement at runtime.

Specifying Variables at Runtime

73

74

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
The reports produced so far have not been interactive in any way. In a finished application, the user would trigger the report, and the report would run without further prompting. The range of data reported would be predetermined by the fixed WHERE clause in the SQL*Plus script file. However, SQL*Plus enables you to create reports that prompt the user to supply their own values to restrict the range of data returned. Interactive Reports To create interactive reports, you can embed substitution variables in a command file or in single SQL commands. A variable can be thought of as a container in which values are temporarily stored.

Specifying Variables at Runtime

75

76

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Substitution Variables
In SQL*Plus, you can use single ampersand substitution variable to temporarily store values. You can predefine variables in SQL*Plus by using the ACCEPT or DEFINE commands. ACCEPT reads a line of user input and stores it in a variable. DEFINE creates and assigns a value to a variable. Examples of Restricted Ranges of Data
D D D

Report figures for the current quarter or specified date range only. Report on data relevant to the user requesting the report only. Display personnel within a given department only.

Other Interactive Effects Interactive effects are not restricted to direct user interaction with the WHERE clause. The same principles can be used to achieve other goals, for example:
D D D

Dynamically altering headers and footers. Obtaining input parameters from a file rather than from a person. Passing values from one SQL statement to another.

SQL*Plus does not support validation checks on user input. Make sure that the prompts you write for the user are simple and unambiguous.

Specifying Variables at Runtime

77

78

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Single Ampersand Substitution Variables
When running a report, users often want to restrict the data returned dynamically. SQL*Plus provides this flexibility by means of user variables. Use an ampersand (&) to identify each variable in your SQL statement. You do not need to define the value of each variable. Notation &user_variable Description Indicates a variable in a SQL statement; if the variable does not exist, SQL*Plus prompts the user for a value. SQL*Plus discards a new variable once it is used.

Example Create a statement to prompt the user for a department number at runtime. The report should contain each employee’s number, last name, and salary. SQL> SELECT 2 FROM 3 WHERE id, last_name, salary s_emp dept_id = &department_number;

Enter value for department_number: 31 ID ---------3 11 LAST_NAME SALARY ------------------------- ---------Nagayama 1400 Magee 1400

With the single ampersand, the user is prompted every time the command is executed. SET VERIFY Command To confirm the changes in the SQL statement, use the SQL*Plus SET VERIFY command. Setting SET VERIFY to ON forces SQL*Plus to display the text of a command before and after it replaces substitution variables with values.

Specifying Variables at Runtime

79

7 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Single Ampersand Substitution Variables

continued

Specifying Character and Date Values with Substitution Variables Remember that in a WHERE clause, date and character values must be enclosed within single quotation marks. The same rule applies to the substitution variables. To avoid entering the quotation marks at run time, enclose the variable in single quotation marks within the SQL statement itself. Example Write a query to retrieve the employee number, last name, and salary of all employees based on the title entered at the prompt by the user. SQL> SELECT 2 FROM 3 WHERE id, last_name, salary s_emp title = ’&job_title’;

Enter value for job_title: Stock Clerk

Specifying Variables at Runtime

7 11

7 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Single Ampersand Substitution Variables
Specifying Column Names, Expressions, and Text at Runtime

continued

Not only can you use the substitution variables in the WHERE clause of a SQL statement, but these variables can be used to substitute column names, expressions, or text. Examples Display the number and any other column and any condition of orders. Try a couple of variations of column names and conditions to observe the results. SQL> SELECT 2 FROM 3 WHERE id, &column_name s_ord &condition;

Enter value for column_name: total Enter value for condition: payment_type = ’CASH’ ID TOTAL ---------- ---------103 377 110 1539.13 111 2770 98 595

SQL> SELECT 2 FROM 3 WHERE

id, &column_name s_ord &condition;

Enter value for column_name: date_ordered Enter value for condition: total > 300000 ID ---------100 109 DATE_ORDE --------31-AUG-92 08-SEP-92

If you do not enter a value for the substitution variable, you will obtain an error when you execute above command.

Specifying Variables at Runtime

7 13

7 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Defining User Variables
You can predefine user variables before executing a SELECT statement. SQL*Plus provides two commands for defining and setting user variables: DEFINE and ACCEPT. Command DEFINE variable = value DEFINE variable DEFINE ACCEPT (see syntax below) Abridged Syntax ACCEPT variable [datatype][FORMAT][PROMPT text][HIDE] where: variable datatype is the name of the variable that stores the value. If it does not exist, SQL*Plus creates it. is either NUMBER, CHAR, or DATE. CHAR has a maximum length limit of 240 bytes. DATE checks against a format model, and the datatype is CHAR. specifies the format model, for example A10 or 9.999. displays the text before the user can enter the value. suppresses what the user enters, for example a password. Description Creates a CHAR datatype user variable and assigns a value to it. Displays the variable, its value, and its datatype. Displays all user variables with value and datatype. Reads a line of user input and stores it in a variable.

FOR[MAT] PROMPT text HIDE

Note: Do not prefix the SQL*Plus substitution parameter with the ampersand (&) when referencing the substitution parameter in the ACCEPT command.

Specifying Variables at Runtime

7 15

7 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Defining User Variables
Guidelines
D

continued

Both the ACCEPT and DEFINE commands will create a variable if the variable does not exist; these commands will automatically redefine a variable if it exists. When using the DEFINE command, use single quotation marks (‘ ’) to enclose a string that contains an embedded space. Use the ACCEPT command to
D

D

D

Give a customized prompt when accepting user input. Otherwise, you will see the default “Enter value for variable.” Explicitly define a NUMBER or DATE datatype variable. Hide user input for security reasons.

D D

Example Display the region number and name for a specified department name. Create a script file called l7prompt.sql, and use the ACCEPT command to prompt the user with a customized message. SET ECHO OFF ACCEPT p_dname PROMPT ’Provide the department name: ’ SELECT d.name, r.id, r.name ”REGION NAME” FROM s_dept d, s_region r WHERE d.region_id = r.id AND UPPER(d.name) LIKE UPPER(’%&p_dname%’) / SET ECHO ON

SQL> START l7prompt Provide the department name: sales

SET ECHO Command The ECHO variable controls whether START and @ commands list each command in a command file as the command is executed. Setting the ECHO variable to ON lists the command and setting it to OFF suppresses the listing.

Specifying Variables at Runtime

7 17

7 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Defining User Variables
Variables are defined until you either
D D

continued

Issue the UNDEFINE command on a variable. Exit SQL*Plus.

When you undefine variables, you can verify your changes with the DEFINE command. When you exit SQL*Plus, variables defined during that session are lost. To define those variables for every session, modify your login.sql file so that those variables are created at startup. Example Create a variable to hold the department position. Display all department names that match the position in the variable. SQL> DEFINE dname = sales SQL> DEFINE dname DEFINE dname SQL> SELECT 2 FROM 3 WHERE = ”sales” (CHAR) name s_dept lower(name) = ’&dname’;

NAME -------------------Sales Sales Sales Sales Sales SQL> UNDEFINE dname SQL> DEFINE dname symbol dname is UNDEFINED

Specifying Variables at Runtime

7 19

7 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Passing Values into a Script File
A parameter is a value that you can pass to a report by means of the command line. To create and run a parameterized report, follow these steps:
1. 2. 3.

Create a script file to include the SELECT statement. In the SELECT statement, use the notation &number for each variable reference. In the command line, specify a value following the filename. Use a space to separate values.

Example Create a script file, l7param.sql, to produce a series of reports by job title. Instead of prompting you for the title, you enter the job title on the command line when you start the file. SET ECHO OFF SELECT FROM WHERE / SET ECHO ON

id, last_name, salary s_emp title = ’&1’

SQL> START l7param President

Guidelines
D

You can use the DEFINE command to associate meaningful names with parameters. A prefix can be used to differentiate column names (no prefix), simple variables (for example, v_test), and parameterized variables (for example, p_name). The position of each parameter value in the command line is significant. The first value corresponds to &1, the second parameter to &2, and onward. Reports can accept a maximum of nine parameters that are named from &1 to &9. SQL*Plus retains report parameters and their values until you redefine them, undefine them, or terminate your SQL*Plus session.

D

D

D D

Specifying Variables at Runtime

7 21

7 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Substitution variables are useful for running reports. They allow flexibility to replace values in a WHERE clause, column names, and expressions. You can customize reports by writing script files with
D D D D D

Single ampersand substitution variables. The ACCEPT command. The DEFINE command. The UNDEFINE command. Substitution variables in the command line.

Specifying Variables at Runtime

7 23

7 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
This practice gives you the opportunity to create files that can be run interactively by using substitution variables to create runtime selection criteria. Practice Contents
D D D

Creating a query to display values using substitution variables Starting a command file containing substitution variables Using the ACCEPT command

Specifying Variables at Runtime

7 25

Practice 7
Determine whether the following statements are true or false.
1. 2.

A single ampersand substitution variable prompts only once. True / False The ACCEPT command is a SQL command. True / False Write a script file to display the user name, first and last names concatenated together, and start dates of employees within a specified range. Prompt the user for the two ranges by using the ACCEPT command. Use the format MM/DD/YY. Save the script file as p7q3.sql. Your result should look like the output below. Enter the low date range (’MM/DD/YY’): 09/01/91 Enter the high date range (’MM/DD/YY’): 09/01/92 USERID -------acatchpo hgiljum mnguyen adumas emaduro EMPLOYEE -----------------------------Antoinette Catchpole Henry Giljum Mai Nguyen Andre Dumas Elena Maduro START_DAT --------09-FEB-92 18-JAN-92 22-JAN-92 09-OCT-91 07-FEB-92

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables.
3.

7 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 7
4.

continued

Write a script to search for customer names and numbers. The search condition should allow for case-insensitive name searches. Save the script file as p7q4.sql. Your result should look like the output below. Please enter the customer’s name: sport ID -----201 203 204 205 206 207 208 211 212 213 215 CUSTOMER NAME ---------------------------------------Unisports Delhi Sports Womansport Kam’s Sporting Goods Sportique Sweet Rock Sports Muench Sports Kuhn’s Sports Hamada Sport Big John’s Sports Emporium Sporta Russia

Specifying Variables at Runtime

7 27

Practice 7
If you have time, complete the following exercises.
5.

continued

Write a report containing the sales representative name, customer name, and each customer’s total sales order. Prompt the user for a region number. Save the script as p7q5.sql. SQL> START p7q5 Please enter a region number: 1 EMPLOYEE ––––––––––– Colin Magee Colin Magee Colin Magee Colin Magee CUSTOMER SALES –––––––––––––––––––––––––––– –––––––––– Beisbol Si! $2,722 Big John’s Sports Emporium $1,020,935 Ojibway Retail $1,539 Womansport $603,870

7 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

8
Overview of Data Modeling and Database Design

82

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
Before you build your tables, you design your database. In this lesson, you examine the data modeling process and relational database concepts, and define normalization. You also translate an entity relationship model into a relational database design. At the end of this lesson, you should be able to
D D D D D

Describe the stages of system development. List and define basic types of data relationships. Define a relational database and its components. Read an entity relationship model. Translate an entity relationship model into a relational database design.

Overview of Data Modeling and Database Design

83

84

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
When you create a database, you need to carefully consider its components. For assistance with the design, you can follow the concepts outlined in this lesson. System Development Cycle In order to logically and successfully create the database objects in the Oracle7 Server, you complete the system development cycle. Each stage of the cycle contains specific activities that you perform to achieve the best possible database design. Database Design Database design is just one of the stages of the development cycle. Through good database design, you can achieve a reliable, high-performance system. Challenges to Managing Data There are many challenges you face as you design your system. They range from controlling data redundancy to enhancing communications with users. By meeting each of these challenges through good database design, you improve the performance of your database.

Overview of Data Modeling and Database Design

85

86

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

System Development Cycle
From concept to production, develop a database by using the system development cycle. The cycle contains multiple stages of development. This top-down, systematic approach to database development transforms business information requirements into an operational database. Stages of Development Strategy and Analysis D Study and analyze the business requirements. Interview users and managers to identify the information requirements. Incorporate the enterprise and application mission statements as well as any future system specifications.
D

Build models of the system. Transfer the business narrative developed in the strategy and analysis phase into a graphical representation of business information needs and rules. Confirm and refine the model with the analysts and experts.

Design D Design the database. The entity relationship model maps entities to tables, attributes to columns, relationships to foreign keys, and business rules to constraints. Build and Document D Build the prototype system. Write and execute the commands to create the tables and supporting objects for the database.
D

Develop user documentation, help-screen text, and operations manuals to support the use and operation of the system.

Transition D Refine the prototype. Move an application into production with user acceptance testing, conversion of existing data, and parallel operations. Make any modifications required. Production D Roll out the system to the users. Operate the production system. Monitor its performance, and enhance and refine the system.

Overview of Data Modeling and Database Design

87

88

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Database Design
Designing a relational database system involves converting a model into a workable software representation. The entities (or objects) perceived by the user are transformed into tables in the database. All forms of design involve a mixture of rules, judgements, and common sense, and relational design is no different. During a design effort, your goal is to design reliable, high-performance systems using the deliverables from the analysis effort. The following key factors describe in detail why you should bother to design at all. Performance The initial design of a system has an enormous impact on its final performance. Generally the impact is much greater than any remedial tuning. Integrated Application Application systems are typically developed by teams of developers. Without some design specification from which to work, developers will each build in their own style. Not only does good design promote a cohesive look and feel, but it also helps ensure that all components of the resulting application system are integrated with each other. Integration with Other Systems Often, there are requirements that a new system integrate with existing systems, or even with systems yet to be built. Good design extends the integration benefits mentioned above into corporate or worldwide systems. Documentation and Communication A major part of a designer’s job is to communicate design decisions to others. At the very least, these decisions need to be documented. Scalability Tackle performance issues during design rather than during production. For example, developing an application in a small, controlled environment does not test real-world situations or a large set of data, factors that can reveal design flaws. Avoid Reinventing the Wheel Many of the problems you will face will have been encountered by others before you. Use existing successful design solutions wherever you can.

Overview of Data Modeling and Database Design

89

Server

8 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

ÉÉ ÉÉ ÉÉ ÉÉ

Data Model
Models are a cornerstone of design. Engineers build a model of a car before putting it into production to work out any details. In the same manner, system designers develop models to explore ideas and improve the understanding of the database design. Purpose of Models Models help communicate the concepts in people’s minds. They can be used for the following purposes:
D D D D D D D D

Communicate Categorize Describe Specify Investigate Evolve Analyze Imitate

The objective is to produce a model that fits a multitude of these uses, can be understood by an end user, but contains sufficient detail for a developer to build a database system.

Overview of Data Modeling and Database Design

8 11

8 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entity Relationship Modeling
Entity relationship models are derived from business specifications or narratives. This model is a graphical representation of business information needs and rules. Entity Relationship Models Entity relationship models separate the information required by a business from the activities performed within a business. Although businesses can change their activities, the type of information tends to remain constant. Therefore, the data structures also tend to be constant. Benefits of Entity Relationship Models
D

Documents information requirements for the organization in a clear, precise format Provides an easily understood pictorial map for the database design Develops and refines the model easily Provides a clear picture of the scope of the information requirements Offers an effective framework for integrating multiple applications, development projects, and purchased application packages

D D D D

Key Components Component Entity Attribute Relationship Description A thing of significance about which information needs to be known. Something that describes or qualifies an entity. A named association between entities showing optionality or degree.

Overview of Data Modeling and Database Design

8 13

8 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entity Relationship Model Concepts
An entity relationship model is composed of entities, attributes, and relationships. Entities An entity represents a thing of significance about the business system, or a discrete category or collection of related data. Examples are customer, orders, and employees. To represent an entity in a model, use the following conventions:
D D D D

Soft box with any dimensions Singular, unique entity name Entity name in uppercase Optional synonym names in uppercase within parentheses “()”

Attributes An attribute describes entities and holds the specific information that should be known about an entity. For example, for the customer entity, the attributes would be customer number, name, phone number, and address. If an entity does not have attributes that need to be known from the business viewpoint, then it is not within the scope of the system requirements, and should not appear in the model. Each of the attributes is either required or optional. This state is called optionality. To represent an entity in a model, use the following conventions:
D D D

Use singular names in lowercase. Tag mandatory attributes, or values that must be known, with an asterisk “*”. Tag optional attributes, or values that may be known, with an “o”.

Unique Identifiers A unique identifier (UID) is any combination of attributes or relationships, or both, that serves to distinguish occurrences of an entity. Each entity occurrence must be uniquely identifiable.
D D

Tag each attribute that is part of the UID with a number symbol (#). Tag secondary UIDs with a number sign in parentheses (#).

Overview of Data Modeling and Database Design

8 15

8 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entity Relationship Model Concepts
Relationships

continued

Each entity must have a relationship that represents the information requirements and rules of the business. The relationship is a two-directional association between two entities, or between an entity and itself. When an entity has a relationship with itself, it is recursive. Each direction of the relationship contains
D D D

A name, for example, taught by or assigned to. An optionality, either must be or may be. A degree, either one and only one or one or more.

Note: Cardinality is a synonym for the term degree. Relationship Syntax Each source entity {may be | must be} relationship name {one and only one | one or more} destination entity. Note: Convention is to read clockwise. Relationship Diagramming Conventions Symbol Dashed line Solid line Crow’s foot Single line Description Optional element indicating “may be.” Mandatory element indicating “must be.” Degree element indicating “one or more.” Degree element indicating “one and only one.”

Overview of Data Modeling and Database Design

8 17

8 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entity Relationship Model Concepts
Unique Identifier Through the Relationship

continued

An entity may be uniquely identified through a relationship. Use a UID bar to indicate that a relationship is part of the entity’s unique identifier. The relationship included in a UID must be mandatory and one and only one in the direction that participates in the UID. Example When you order items, you have an order number and an item with a unique line item number. But when another order is placed, that item number is no longer unique. Therefore, the item is uniquely identified by its attribute number and the specific order number to which the item is related. Order number 100 100 100 101 101 Recursive Relationship A relationship between an entity and itself is called a recursive relationship. It is represented by a “pig’s ear.” Relationship Types Type One-to-one Description Degree of one and only one in both directions. These types are rare, and may really be the same entity, or an attribute of the entity. Degree of one or more in one direction and a degree of one and only one in the other direction. Very common. Degree of one or more in both directions. Very common. Resolve them with an intersection entity. Item number 1 2 3 1 2 Product number 209 399 876 630 297

Many-to-one Many-to-many

Overview of Data Modeling and Database Design

8 19

8 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entity Relationship Model Concepts
Normalization

continued

Before creating the database design, you want to eliminate the problems of data redundancy by normalizing the data model. Modify the data model to support different functional requirements and alternate database designs by normalizing the storage of data before you create the database. Benefits of Normalization
D D D

Minimizes data redundancy Reduces integrity problems Identifies missing entities, relationships, and tables

Normalization Rules Rule First normal form (1NF) Second normal form (2NF) Third normal form (3NF) Description All attributes must be single-valued and not repeating. An attribute must depend upon its entity’s entire unique identifier. No non-UID attribute can be dependent upon another non-UID attribute.

Overview of Data Modeling and Database Design

8 21

8 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Integrity Constraints and Keys
Ensure that users perform only operations that leave the database in a correct and consistent state by enforcing data integrity constraints. All data integrity constraints should be enforced by the database server or the application software. Keys correspond to integrity constraints. The three types of keys are primary key, unique key, and foreign key. Integrity Constraint Type Entity Referential Column User-defined Description No part of a primary key can be NULL and the value must be unique. Foreign key values must match a primary key or be NULL. Values in the column must match the defined datatype. Values must comply with the business rules.

Examples of User Defined Data Integrity Constraints
D D D

An employee in the finance department cannot have a title of programmer. A salesperson’s commission cannot exceed 50% of the base salary. Customers can only have Excellent, Good, or Poor credit rating values.

Overview of Data Modeling and Database Design

8 23

8 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Integrity Constraints and Keys
Primary Keys

continued

Each row in the table is uniquely identified by a column or set of columns called a primary key (PK). The primary key is defined as allowing no duplicate values and cannot be NULL. A primary key consisting of multiple columns is called a composite primary key or a compound primary key. The columns of a composite primary key must be unique in combination, although the individual columns can have duplicates. No part of a primary key can contain a null value. Candidate Keys A table can have several candidate keys. A candidate key is a column or combination of columns that can serve as the primary key for the table. Select one candidate key to be the primary key for the table. The other candidates become alternate keys or unique keys. They must be UNIQUE and NOT NULL.

Overview of Data Modeling and Database Design

8 25

8 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Integrity Constraints and Keys
Foreign Keys

continued

A foreign key (FK) is a column or combination of columns in one table that refers to a primary key or unique key in the same table or in another table. Foreign keys are based on data values and are purely logical, not physical pointers. A foreign key value must match an existing primary key value or unique key, or else be NULL. If a foreign key is part of a primary key, it cannot contain a null value because no part of a PK can be NULL. Example In the S_ITEM table, the ORD_ID cannot contain a null value because it is part of the PK.
Foreign Key Primary Key

ORD_ID 100 100 101 101 102
Primary Key

ITEM_ID 1 2 1 3 1

PRODUCT_ID 10011 10013 30421 41010 20180

...

S_ITEM Table

ID 100 101 102 103

CUSTOMER_ID 204 205 206 208

DATE_ORDERED 31-AUG-92 31-AUG-92 01-SEP-92 02-SEP-92

...

S_ORD Table

Overview of Data Modeling and Database Design

8 27

8 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Designing the Database
The database design stage produces design specifications for a relational database, including definitions for relational tables, indexes, views, and storage space. Map the Entity Relationship Model to a Table Instance Chart
1. 2.

Map the simple entities to tables. Map the attributes to columns and document sample data. Clearly label the column names and their associated generic datatypes; for example, character, number, or date. Map the unique identifiers to a primary key. Be sure to include any foreign key components of the primary key. Map relationships to foreign keys.

3. 4.

Additional Requirements
D

Design the indexes, which are database objects that provide direct, quick access to rows. You may want to create indexes for alternate keys, foreign keys, and columns frequently used in the search condition. Establish view definitions, which are logical tables based on one or more tables or views. Views can restrict access, provide improved presentation of information, and can contain a pre-packaged complex query. Plan the physical storage space, which is the amount of space required to store the data of a table in the database. Redefine integrity constraints.

D

D

D

For more information, see Develop Complex Data Models and Design Databases course description.

Overview of Data Modeling and Database Design

8 29

1 2 3 4

1 Map entities to tables

2 Map attributes to columns

3 Map the unique identifiers to a primary key

4 Map relationships to foreign keys

8 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Designing the Database
Symbols Used to Document the Table Instance Chart Symbol PK FK FK1, FK2 FK1, FK1 NN U U1, U1 Guidelines
D

continued

Definition Primary key column Foreign key column Two foreign keys within the same table Two columns within the same composite foreign key Not null column Unique column Two columns that are unique in combination

The table name should be easy to trace back to the entity name. The plural of the entity name is sometimes used because the table will contain a set of rows. Column names should be easily traced to the entity relationship model. Short column names will reduce the time required for SQL command parsing. You should develop your own naming conventions and standards.

D

D

Overview of Data Modeling and Database Design

8 31

8 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Designing the Database
Map the Entities to Tables

continued

1

Create a table instance chart for the new table. The table instance chart should contain columns for the name of the table, the names of the columns, the key types, null and unique references, foreign key information, column datatype and maximum length, and sample data. Record the name of the table. Map the Attributes to Columns Map each attribute in the entity relationship model to a column name in the table. Add sample data to the chart to show the contents of the table in a visual form. Map mandatory attributes, tagged with an asterisk (*), to columns defined as NOT NULL (NN). Do not name columns with SQL reserved words, such as NUMBER. Name columns with consistent abbreviations, such as NO or NUM (but not both) to avoid programmer and user confusion. For more information, see Oracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers” section for reserved words, naming rules, and guidelines.

2

Overview of Data Modeling and Database Design

8 33

8 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Designing the Database
Map the Unique Identifiers to Primary Keys

continued

3

Map the UIDs identified in the entity relationship model by a number symbol (#) to primary key columns and label the key type as PK. Map a UID containing a single attribute to a single-column PK. Label the not null and unique references as NN and U. Map a UID that includes multiple attributes to a composite PK. Label those columns NN and U1. If you have an alternate primary key, label it as NN and U, but choose only one PK. If the entity’s UID includes the relationship (indicated by the UID bar), add a FK column for each relationship and label it as PK and FK key types. Add FK columns to the end of the table instance chart or to the right of all columns, even if the FK is part of the PK. Choose a unique name for each FK column and add sample data. ITEM
#* o o o id price quantity quantity shipped

in made up of

ORDER
#* o o o id date ordered date shipped payment type

Overview of Data Modeling and Database Design

8 35

8 36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Designing the Database
Map Relationships to Foreign Keys

continued

4

The last step is to map relationship to foreign keys. There are two types of relationships to consider: Many-to-one and one-to-one. If your relationship is part of the unique identifier, you have already mapped it. Be sure to label mandatory relationships with the NN reference. Choose a unique name for the foreign key column. Many to One Relationships Map the many-to-one relationship by taking the primary key at the one end and putting it in the table at the many end as a foreign key. This technique also applies to recursive relationships. One to One Optional Relationships You can place the foreign key in the table at either end of the relationship for an optional one-to-one relationship. Be sure to add the U reference. PET PEN
the temporary home for #* id o location o size

#* o o o *

id name date of birth weight species

assigned to

One to One Mandatory Relationships Place the unique foreign key in the table at the mandatory end and label it NN to enforce the mandatory requirement and U to enforce the one-to-one relationship. PET
#* o o o * id name date of birth weight species

assigned to the temporary home for

PEN
#* id o location o size

Overview of Data Modeling and Database Design

8 37

8 38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Logically and successfully create database objects in the Oracle7 Server by completing the system development cycle. Each stage helps you to achieve the best possible database design. Stages of Development
D D D D D D D

Study and analyze the business requirements. Build models of the system. Design the database. Build the prototype system. Write the user documentation. Refine the prototype. Roll out the system to the users.

Entity Relationship Model
D D D D D

Entities are things of significance. Attributes describe or qualify two entities. Relationships associate two entities. Establish unique identifiers. Follow normalization rules.

Database Design
D D D

Create a table instance chart. Map all entity relationship model components to the chart. Add other supporting information and objects.

Overview of Data Modeling and Database Design

8 39

8 40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

9
Creating Tables

92

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
In this lesson, you will create tables. You will also build integrity constraints, which are rules governing what can and cannot be done with the data. At the end of this lesson, you should be able to
D D D D D

Create a table containing integrity constraints. Identify table naming conventions. Describe the datatypes that can be used when specifying column definitions. Recognize the indexes that are created automatically by constraints. Create a table by populating it with rows from another table.

Creating Tables

93

94

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
An Oracle7 database can contain multiple data structures. Each structure should be outlined in the database design so that it can be created during the build stage of database development. Data Structures Structure Table View Sequence Index Description Stores data. Logically represents subsets of data from one or more tables. Generates primary key values. Improves the performance of some queries.

Summary of Oracle7 Table Structures
D D

Tables can be created at any time, even while users are using the database. You do not need to specify the size of any table. The size is ultimately defined by the amount of space allocated to the database as a whole. It is important, however, to estimate how much space a table will use over time. Table structure can be modified online.

D

Creating Tables

95

96

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating Tables
Create tables to store data by executing the SQL CREATE TABLE command. This command is one of the data definition language (DDL) commands, which you will cover in the next several lessons. DDL commands are a subset of SQL commands used to create, modify, or remove Oracle7 database structures. These commands have an immediate effect on the database, and they also record information in the data dictionary. In order to create a table, a user must have the CREATE TABLE privilege and a storage area in which to create objects. The database administrator uses data control language (DCL) commands, which are covered in a later lesson, to grant privileges to users. Abridged Syntax CREATE TABLE [schema.]table (column datatype [DEFAULT expr][column_constraint], ... [table_constraint]); where: schema table DEFAULT expr column datatype column_constraint table_constraint is the same as the owner’s name. is the name of the table. specifies a default value if a value is omitted in the INSERT statement. is the name of the column. is the column’s datatype and length. is an integrity constraint as part of the column definition. is an integrity constraint as part of the table definition.

For more information, see Oracle7 Server SQL Reference, Release 7.3, “CREATE TABLE.”

Creating Tables

97

98

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating Tables
Referencing Another User's Tables

continued

A schema is a collection of objects. Schema objects are the logical structures that directly refer to the data in a database. Schema objects include tables, views, synonyms, sequences, stored procedures, indexes, clusters, and database links. The tables referenced in a constraint must exist in the same database. If the table does not belong to the user creating the constraint, the owner’s name must be prefixed to the table referenced in the constraint. The DEFAULT Option A column can be given a default value by using the DEFAULT option. This option prevents null values from entering the columns if a row is inserted without a value for the column. The default value can be a literal, an expression, or SQL function, such as SYSDATE and USER, but the value cannot be the name of another column or a pseudocolumn, such as NEXTVAL or CURRVAL. The default expression must match the datatype of the column.

Creating Tables

99

9 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating Tables
Naming Rules

continued

Name database tables and columns according to the standard rules for naming any Oracle7 database object.
D

Table names and column names must begin with a letter and can be 1–30 characters long. Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $ and # (legal characters, but their use is discouraged). Names must not duplicate the name of another object owned by the same Oracle7 Server user. Names must not be an Oracle7 Server reserved words.

D

D

D

Naming Guidelines
D D

Use descriptive names for tables and other database objects. Name the same entity consistently in different tables. For example, the department number column is called DEPT_ID in both the S_EMP table and the S_REGION table.

Note: Names are case-insensitive. For example, EMP is treated as the same name as eMP or eMp. For more information, see Oracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers.”

Creating Tables

9 11

9 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Oracle7 Datatypes
There are many different column types. The Oracle7 Server can treat values of one datatype differently from values of other datatypes. The basic datatypes are character, number, date, and RAW. Sample Oracle7 Datatypes Datatype VARCHAR2(size) CHAR(size) NUMBER NUMBER(p,s) Description Variable length character values up to maximum length size. Minimum length is 1, maximum length is 2000. Fixed length character values of length size. Default length is 1, maximum length is 255. Floating point number with precision of 38 significant digits. Number value having a maximum precision of p ranging from 1 to 38 and a maximum scale of s; the precision is the total number of decimal digits, and the scale is the number of digits to the right of the decimal point. Date and time values between January 1, 4712 B.C. and December 31, 4712 A.D. Variable length character values up to 2 gigabytes. Only one LONG column is allowed per table. Equivalent to VARCHAR2 and LONG, respectively, but used to store byte-oriented or binary data that is not to be interpreted by the Oracle7 Server.

DATE LONG RAW and LONG RAW

Note: The column width determines the maximum number of characters for values in the column. You must specify the size for VARCHAR2 columns. You can specify the size for NUMBER and CHAR columns, but default values are available (38 for NUMBER and 1 for CHAR). For more information, see Oracle7 Server SQL Reference, Release 7.3, “Datatypes.”

Creating Tables

9 13

9 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Constraints
Constraints have been available with the Oracle7 Server since Version 6. In Oracle7, constraints are enforced at the database level. You can use constraints to
D

Enforce rules at the table level whenever a row is inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to succeed. Prevent the deletion of a table if there are dependencies from other tables. Provide rules for Oracle tools, such as Developer/2000.

D D

Data Integrity Constraints Constraint NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY Description Specifies that this column may not contain a null value. Specifies a column or combination of columns whose values must be unique for all rows in the table. Uniquely identifies each row of the table. Establishes and enforces a foreign key relationship between the column and a column of the referenced table. Specifies a condition that must be true.

CHECK

For more information, see Oracle7 Server SQL Reference, Release 7.3, “CONSTRAINT clause.”

Creating Tables

9 15

9 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Constraints
Constraint Naming Conventions

continued

All constraints are stored in the data dictionary. Constraints are easy to reference if you give them a meaningful name. Constraint names must follow the standard object naming rules. If you do not name your constraint, Oracle7 generates a name with the format SYS_Cn, where n is an integer to create a unique constraint name. Creating Constraints Constraints are usually created at the same time as the table. Constraints may be added to a table after its creation and also temporarily disabled, and will be covered in another lesson. Defining Constraints Constraints can be defined at one of two levels. Constraint Level Column Description References a single column and is defined within a specification for the owning column. Can define any type of integrity constraint. References one or more columns and is defined separately from the definitions of the columns in the table. Can define any constraints except NOT NULL. Column Constraint Level

Table

Syntax

column [CONSTRAINT constraint_name] constraint_type,

Syntax

Table Constraint Level

column, [CONSTRAINT constraint_name] constraint_type (column, ...),

Creating Tables

9 17

9 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Constraints
The NOT NULL Constraint

continued

The NOT NULL constraint ensures that null values are not allowed in the column. Columns without the NOT NULL constraint can contain null values by default. This constraint can only be specified at the column-constraint level, not at the table-constraint level. Examples This example applies the NOT NULL constraint to the PHONE column, which is a variable character column that holds 15 characters. Because this constraint is unnamed, Oracle7 will create a name for it. CREATE TABLE phone friend... VARCHAR2(15) NOT NULL, ...

This example applies the NOT NULL constraint to the LAST_NAME column, which is a variable length character column that holds up to 25 characters. In this case, the constraint name is FRIEND_LAST_NAME_NN. CREATE TABLE friend... last_name VARCHAR2(25) CONSTRAINT friend_last_name_nn NOT NULL, ...

The UNIQUE Constraint A UNIQUE constraint designates a column or combination of columns as a unique key. No two rows in the table can have the same value for this key. Null values are allowed if the unique key is based on a single column. Unique constraints can be defined at the column- or table-constraint level. A composite unique key is created by using the table-level definition. A UNIQUE index is automatically created for a unique key column. A UNIQUE constraint is not the same as or synonymous to a PRIMARY KEY constraint.

Creating Tables

9 19

9 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Constraints
The PRIMARY KEY Constraint

continued

A PRIMARY KEY constraint creates a primary key for the table. Only one primary key can be created for a each table. The PRIMARY KEY constraint is a column or set of columns that uniquely identifies each row in a table. This constraint enforces uniqueness of the column or column combination and ensures that no column that is part of the primary key can contain a null value. PRIMARY KEY constraints can be defined at the column-constraint level or table-constraint level. A composite PRIMARY KEY is created by using the table-level definition. A UNIQUE index is automatically created for a PRIMARY KEY column. The FOREIGN KEY Constraint The FOREIGN KEY, or referential integrity constraint, designates a column or combination of columns as a foreign key and establishes a relationship between a primary key or a unique key in the same table or between tables. A foreign key value must match an existing value in the parent table or be NULL. FOREIGN KEY constraints can be defined at the column- or table-constraint level. A composite foreign key is created by using the table-level definition. Foreign keys are based upon data values and are purely logical, not physical, pointers. A foreign key that is part of a primary key cannot be a null value because no part of a primary key can be NULL. Continued

Creating Tables

9 21

9 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Constraints
The FOREIGN KEY Constraint continued

continued

The foreign key is defined in the child table, and the table containing the referenced column is the parent table. The foreign key is defined using a combination of the following keywords:
D

FOREIGN KEY is used to define the column in the child table at the table-constraint level. REFERENCES identifies the table and column in the parent table. ON DELETE CASCADE indicates that when the row in the parent table is deleted, the dependent rows in the child table will also be deleted.

D D

Without the ON DELETE CASCADE option, the row in the parent table cannot be deleted if it is referenced in the child department. The CHECK Constraint The CHECK constraint defines a condition that each row must satisfy. The condition can use the same constructs as query conditions, with the following exceptions:
D

References to the CURRVAL, NEXTVAL, LEVEL, or ROWNUM pseudocolumns Calls to SYSDATE, UID, USER, or USERENV functions Queries that refer to other values in other rows

D D

CHECK constraints can be defined at the column-constraint level or table-constraint level. The constraint syntax can apply to any column in the table, not only on the column on which it is defined.

Creating Tables

9 23

9 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Table from a Table Instance Chart
Create your tables, based on the table instance chart from the database design, by using the CREATE TABLE syntax. You might find it useful to create the syntax in a script file for documentation and ease of use. Create a Table
1. 2. 3. 4.

Create a script file. Start the CREATE TABLE syntax and specify the table name. Map the column names, datatypes, and lengths from the table instance chart to the script file. Separate each column definition with a comma (,). Map the NOT NULL constraints, except for the PRIMARY KEY constraint columns, as column constraint. Map the PRIMARY KEY constraint either as a column constraint if the constraint constitutes only one column or as a table constraint if the constraint constitutes more than one column. Map the UNIQUE, CHECK, and FOREIGN KEY constraints. Save and execute the script file.

5. 6.

Creating Tables

9 25

9 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Table from a Table Instance Chart
Example Create the S_DEPT database table based on the table instance chart.

continued

SQL> CREATE TABLE s_dept 2 (id NUMBER(7) 3 CONSTRAINT s_dept_id_pk PRIMARY KEY, 4 name VARCHAR2(25) 5 CONSTRAINT s_dept_name_nn NOT NULL, 6 region_id NUMBER(7) 7 CONSTRAINT s_dept_region_id_fk REFERENCES 8 s_region (id), 9 CONSTRAINT s_dept_name_region_id_uk UNIQUE 10 (name, region_id));

Defining the Constraints
D

The S_DEPT_ID_PK column constraint identifies the ID column as the primary key of the S_DEPT table. This constraint ensures that no two departments in the same table have the same department number and that no department number is NULL. The S_DEPT_NAME_NN column constraint ensures that each department number in the table has a name. The S_DEPT_REGION_ID_FK column constraint ensures that any region number entered in the S_DEPT table has a corresponding value in the S_REGION table. Before defining this constraint, the S_REGION table, including a PRIMARY KEY or UNIQUE constraint on the ID column, must be created. The S_DEPT_NAME_REGION_ID_UK table constraint identifies the NAME column and the REGION_ID column as a composite unique key to ensure that the same combination of department name and region number does not appear in the table more than once.

D

D

D

Creating Tables

9 27

9 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Table from a Table Instance Chart
Example

continued

Create the S_EMP database table based on the table instance chart. Also, enforce the business constraint that the legal values for commission percent are 10, 12.5, 15, 17.5, and 20. Column Name Nulls/ Unique FK Table FK Column Datatype NUM Length 7 CHAR 25 CHAR 8 DATE NUM 6
START_ USERID DATE COMMISSION_ PCT

ID

LAST_NAME

DEPT_ID

Key Type PK NN, U NN NN, U

FK

S_DEPT ID NUM 7

Note: The above table displays a subset of columns found in the S_EMP table. Constraint S_EMP_ID_PK Description Establishes the ID column as the table’s primary key. This constraint ensures that a value is entered and that it is unique.

S_EMP_LAST_NAME_NN Ensures that each row in the table contains a last name value. S_EMP_USERID_NN S_EMP_USERID_UK S_EMP_DEPT_ID_FK Ensures that there is a value in the USERID column. Ensures that each value in the USERID column is unique. Ensures that the S_EMP table does not contain department number not already stored in the S_DEPT table. Restricts commission percentages.

S_EMP_COMMISSION_ PCT_CK

Creating Tables

9 29

9 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Table from Rows in Another Table
A second method to create a table is to apply the AS subquery clause to both create the table and insert rows returned from the subquery. Syntax CREATE TABLE table [column(, column...)] AS subquery; where: table column subquery Guidelines
D

is the name of the table. is the name of the column, default value, and integrity constraint. is the SELECT statement that defines the set of rows to be inserted into the new table.

The table will be created with the specified column names, and the rows retrieved by the SELECT statement will be inserted into the table. The column definition can contain only the column name, default value, and integrity constraints, not the datatype or referential integrity constraint. If column specifications are given, the number of columns must equal the number of columns in the subquery SELECT list. If no column specifications are given, the column names of the table are the same as the column names in the subquery. Only the NOT NULL constraint is inherited from the subquery table to corresponding columns in the new table.

D

D

D

D

Creating Tables

9 31

9 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Confirming Table Creation
You can verify the existence of a database table and check the column definitions by using the SQL*Plus DESCRIBE command. Example Confirm the creation of the S_EMP table. SQL> DESCRIBE s_emp Name ----------------------------ID LAST_NAME FIRST_NAME USERID START_DATE COMMENTS MANAGER_ID TITLE DEPT_ID SALARY COMMISSION_PCT Null? -------NOT NULL NOT NULL Type ------------NUMBER(7) VARCHAR2(25) VARCHAR2(25) NOT NULL VARCHAR2(8) DATE VARCHAR2(255) NUMBER(7) VARCHAR2(25) NUMBER(7) NUMBER(11,2) NUMBER(4,2)

Note: Only the NOT NULL constraint is identified in the DESCRIBE command. All constraints can be viewed in the data dictionary.

Creating Tables

9 33

9 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
The Oracle7 Server stores data in tables. Create a table by using the SQL CREATE TABLE command. You can create a table based on the definition of another table by using the AS subquery option in the CREATE TABLE command. Table Features
D D D

Table name Column names, datatypes, and lengths Integrity constraints

UNIQUE indexes are created automatically when you create PRIMARY KEY and UNIQUE constraints. Constraint Types
D D D D D

NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK

DESCRIBE Command Review the structure of a table using the SQL*Plus DESCRIBE command.

Creating Tables

9 35

9 36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
Create new tables containing constraints by using the CREATE TABLE command. Confirm that the new table was added to the database. Create the syntax in the command file, then execute the command file to create the table. Practice Contents
D D

Creating new tables containing constraints Verifying that the tables exist

Creating Tables

9 37

9 38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 9
1.

Are the following examples syntactically correct? If not, why? SQL> CREATE TABLE T_3000 2 (id NUMBER(7), 3 name VARCHAR2(25) 4 CONSTRAINT table_id_pk PRIMARY KEY(id));
a.

Correct/Incorrect

SQL> CREATE TABLE 1995_orders 2 (id NUMBER(7), 3 customer_id NUMBER(7), 4 CONSTRAINT ord_cust_id_nn NOT NULL, 5 total NUMBER(11,2), 6 filled CHAR(1) 7 CONSTRAINT ord_filled_ck CHECK 8 (filled IN (’Y’,’N’)), 9 CONSTRAINT ord_id_pk PRIMARY KEY);
b.

Correct/Incorrect

Creating Tables

9 39

Practice 9
2.

continued

Create the DEPARTMENT table based on the table instance chart given below. Enter the syntax in a script p9q2.sql, then execute the script to create the table. Confirm that the table is created. You will add data to the table in another lesson.

Table name: DEPARTMENT Column Name Key Type Nulls/ Unique FK Table FK Column Datatype Length
3.

ID PK NN, U

NAME

NUMBER 7

CHAR 25

Create the EMPLOYEE table based on the table instance chart given below. Enter the syntax in a script p9q3.sql, then execute the script to create the table. Confirm that the table is created. You will add data to the table in another lesson.

Table name: EMPLOYEE Column Name Key Type FK Table FK Column Datatype Length NUMBER CHAR 7 25 CHAR 25 ID PK NN LAST_NAME FIRST_NAME DEPT_ID FK NN DEPARTMENT ID NUMBER 7

Nulls/ Unique NN, U

9 40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

10
Oracle Data Dictionary

10 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
The Oracle data dictionary is one of the most important components of the Oracle7 Server. It consists of a set of tables and views that provide a read-only reference to the database. At the end of this lesson, you should be able to
D D

Describe the data dictionary views a user may access. Query data from the data dictionary.

Oracle Data Dictionary

10 3

10 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
The Oracle data dictionary is one of the most important components of the Oracle7 Server. It is created when a database is created. Whenever the database is in operation, the data dictionary is updated and maintained by the Oracle7 Server. All data dictionary tables are owned by the SYS user. The base tables are rarely accessed directly because the information in them is not easy to understand. Therefore, users typically access data dictionary views because the information is presented in a format that is easy for them to understand. Tables Within the Oracle7 Database Tables User tables Data dictionary Description Collection of tables created and maintained by the user, such as S_EMP, that contain user information. Collection of tables created and maintained by the Oracle7 Server, such as USER_OBJECTS, that contain information about the database.

Example Data Dictionary Contents
D D D D D

Names of Oracle7 Server users Privileges granted to users Database object names (for example, tables, views, and indexes) Table constraints Auditing information, such as who has accessed or updated specified database objects

Data Dictionary Uses The data dictionary is a reference for all database users. It is a valuable source of information for end users, application designers, and DBAs. The data dictionary is also critical for the operation of the Oracle7 Server because the database relies on the data dictionary to record and verify information about itself.

Oracle Data Dictionary

10 5

10 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Querying the Data Dictionary
You can query the data dictionary by issuing a SQL SELECT statement. Depending on your privileges, you can query various views. View Classes Data dictionary view names reflect their intended use. There are four categories of views; each category has a distinct prefix. Prefix USER_ Description Contains objects owned by the user. For example, views with this prefix allow the user to display information about tables created by the user and privileges granted by the user. Accesses objects to which the user has been granted access rights, in addition to objects owned by the user. Allows users with the DBA privilege to access any object in the database. Displays database server performance and locking. Initially available only to the DBA.

ALL_ DBA_ V$

Additional Views Several data dictionary views do not use the prefixes listed above. These include synonyms for views with long names. View Name DICTIONARY TABLE_PRIVILEGES IND Description Lists all data dictionary tables, views, and synonyms. Grants on objects for which the user is the grantor, grantee, or owner. Is a synonym for USER_INDEXES.

Oracle Data Dictionary

10 7

10 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Querying the Data Dictionary

continued

Example The DICTIONARY view lists all data dictionary views accessible to the user with a brief description of the object in a comment column. You can also reference the synonym for the view, DICT. SQL> SELECT 2 FROM * DICTIONARY;

Example You can display the structure of any data dictionary view by using the SQL*Plus DESCRIBE command. Display the structure of USER_OBJECTS. SQL> DESCRIBE user_objects Name Null? ------------------------------ -------OBJECT_NAME OBJECT_ID OBJECT_TYPE CREATED LAST_DDL_TIME TIMESTAMP STATUS Type -----------VARCHAR2(128) NUMBER VARCHAR2(13) DATE DATE VARCHAR2(75) VARCHAR2(7)

Example To view a description of each column in data dictionary tables and views, query the DICT_COLUMNS view. SQL> SELECT 2 FROM 3 WHERE column_name, comments dict_columns table_name = ’USER_OBJECTS’;

For more information, see Oracle7 Server SQL Language Quick Reference, Release 7.3.

Oracle Data Dictionary

10 9

10 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Querying the Data Dictionary
Example Display the types of objects that the user owns. SQL> SELECT 2 FROM DISTINCT object_type user_objects;

continued

Example You can search the data dictionary for a specific topic by querying the COMMENTS column in the DICTIONARY view. Find all data dictionary views pertaining to the keyword Grant. COLUMN table_name FORMAT A20 COLUMN comments FORMAT A30 SQL> SELECT 2 FROM 3 WHERE * dictionary LOWER(comments) LIKE ’%grant%’;

TABLE_NAME COMMENTS -------------------- -----------------------------ALL_COL_PRIVS Grants on columns for which th e user is the grantor, grantee , owner, or an enabled role or PUBLIC i s the grantee ALL_COL_PRIVS_MADE Grants on columns for which th e user is owner or grantor Grants on columns for which th e user, PUBLIC or enabled role is the grantee

ALL_COL_PRIVS_RECD

... 20 rows selected.

Oracle Data Dictionary

10 11

10 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Checking Constraints on a Table
After creating a table, you can confirm its existence by issuing a DESCRIBE command. The only constraint you can verify is the NOT NULL constraint. To view all constraints on your table, you can check the USER_CONSTRAINTS table. Example Confirm the constraints on the S_EMP table. SQL> SELECT 2 3 FROM 4 WHERE constraint_name, constraint_type, search_condition, r_constraint_name user_constraints table_name = ’S_EMP’;

CONSTRAINT_NAME ----------------------S_EMP_MANAGER_ID_FK S_EMP_LAST_NAME_NN S_EMP_USERID_NN S_EMP_ID_PK S_EMP_USERID_UK S_EMP_COMMISSION_PCT_CK S_EMP_DEPT_ID_FK S_EMP_TITLE_FK 8 rows selected.

C SEARCH_CONDITION R_CONSTRAINT_NA - --------------------- --------------R S_EMP_ID_PK C LAST_NAME IS NOT NULL C USERID IS NOT NULL P U C commission_pct IN (10, 12 .5, 15, 17.5, 20) R S_DEPT_ID_PK R S_TITLE_TITLE_PK

Note: The above display has been formatted to fit the page.

Oracle Data Dictionary

10 13

10 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Checking Constraints on a Table

continued

View the names of the columns involved in constraints by querying the USER_CONS_COLUMNS data dictionary view. This view is especially useful for constraints that use the system-assigned name. Example Display the column constraint information in the data dictionary for the S_EMP table. SQL> SELECT 2 FROM 3 WHERE constraint_name, column_name user_cons_columns table_name = ’S_EMP’;

CONSTRAINT_NAME ----------------------S_EMP_COMMISSION_PCT_CK S_EMP_DEPT_ID_FK S_EMP_ID_PK S_EMP_LAST_NAME_NN S_EMP_MANAGER_ID_FK S_EMP_TITLE_FK S_EMP_USERID_NN S_EMP_USERID_UK 8 rows selected.

COLUMN_NAME ----------------------COMMISSION_PCT DEPT_ID ID LAST_NAME MANAGER_ID TITLE USERID USERID

Oracle Data Dictionary

10 15

10 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
The data dictionary is a set of tables that the user can query through views. The data dictionary holds all the data about the database. Write a SELECT statement to display the contents of the data dictionary views. Frequently Accessed Data Dictionary Views
D D D D D

DICTIONARY DICT_COLUMNS USER_OBJECTS USER_CONSTRAINTS USER_CONS_COLUMNS

Oracle Data Dictionary

10 17

10 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
In this practice, you will access the data dictionary views to verify information about your tables. Practice Contents
D D

Querying the data dictionary to view table information Viewing constraint information from the data dictionary

Oracle Data Dictionary

10 19

10 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 10
1.

Select all the views from the data dictionary pertaining to Table. You can adjust the column formats by using the SQL*Plus COLUMN command.

If you want to interrupt your query, you can cancel it by pressing [CTRL]+[C] on your PC keyboard.
2.

If a query is very lengthy, what SQL*Plus command can you set before you execute the query to show only one page at a time?

Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invoke scripts p9q2.sql and p9q3.sql to create DEPARTMENT table and EMPLOYEE table respectively.
3. 4.

Query the USER_OBJECTS data dictionary to see information about the tables you created in Practice 9, DEPARTMENT and EMPLOYEE tables. Create a script to execute a generic query to confirm the constraints for the tables you have created. You can use a substitution parameter for the table name. Save the query as p10q4.sql. Execute the script to confirm the constraints for the tables you created in Practice 9, DEPARTMENT and EMPLOYEE tables.

Oracle Data Dictionary

10 21

10 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

11
Manipulating Data

11 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
Once your tables have been created, you will need to add new rows, make changes to rows in a table, or delete rows by using data manipulation commands. This lesson covers using SQL commands to make changes to data. A number of these data manipulation commands make up a transaction, which you may either save or delete using transaction controls. At the end of this lesson, you should be able to
D D D D

Insert new rows into a table. Update existing rows in a table. Delete rows from a table. Explain transaction controls and their importance.

Manipulating Data

11 3

11 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
Data manipulation language (DML) is a core part of SQL. When you want to add, update, or delete data in the database, you execute a DML statement. A collection of DML statements that have not yet been made permanent is called a transaction, or a logical unit of work.

Manipulating Data

11 5

11 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
You can add new rows to a table by issuing the INSERT command. Syntax INSERT INTO VALUES where: table column value table [(column [, column...])] (value [, value...]); is the table name. is the name of the column in the table to populate. is the corresponding value for the column.

Note: This command with the VALUES clause adds only one row at a time to a table. Inserting a Row into a Table Because you can insert a new row that contains values for each column, therefore the column list is not required in the INSERT clause. However, the values must be listed according to the default order of the columns in the table. SQL> DESCRIBE s_dept Name ------------------------ID NAME REGION_ID Null? -------NOT NULL NOT NULL Type -------------NUMBER(7) VARCHAR2(25) NUMBER(7)

SQL> INSERT INTO 2 VALUES 1 row created.

s_dept (11, ’Finance’, 2);

For clarity, use the column list in the INSERT clause. Enclose character and date values within single quotation marks; do not enclose numeric values within single quotation marks.

Manipulating Data

11 7

11 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
Inserting Null Values Method Implicit Explicit Description Omit the column from the column list. Specify the NULL keyword in the VALUES list.

continued

Specify the empty string (‘’) in the VALUES list; for character strings and dates only. Example Enter a new department omitting the region number. Because the region number is not listed in the INSERT clause, a null value is entered implicitly for the region number in this row. SQL> INSERT INTO 2 VALUES 1 row created. s_dept (id, name) (12, ’MIS’);

Example Alternatively, you can enter a null value into a row explicitly by using the NULL keyword for the value. SQL> INSERT INTO 2 VALUES 1 row created. Be sure that the targeted column allows null values by verifying the Null? status from the SQL*Plus DESCRIBE command. s_dept (13, ’Administration’, NULL);

Manipulating Data

11 9

11 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
Inserting Special Values by Using SQL Functions

continued

You can use pseudocolumns to enter special values in your table. Specify USERID to enter the current user name. SYSDATE enters the current date and time. Example Record information for the student in the S_EMP table. Supply the current user name for the USERID column and the current date and time in the START_DATE column. SQL> INSERT INTO s_emp (id, first_name, 2 last_name, userid, salary, start_date) 3 VALUES (26, ’Donna’, 4 ’Smith’, USER, NULL, SYSDATE); 1 row created.

Confirming Additions to the Table To verify that the rows were inserted into the table, you can write a SELECT statement. Example SQL> SELECT id, last_name, first_name, 2 userid, start_date, salary 3 FROM s_emp 4 WHERE id = 26;

ID LAST_NAME FIRST_NAME USERID START_DAT -- --------- ---------- -------- --------SALARY -----26 Smith Donna SFCL26 01-JAN-96

Manipulating Data

11 11

11 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
Inserting Specific Date and Time Values

continued

When inserting a date value, the format DD-MON-YY is usually used. With this format, recall that the century defaults to the current century. Because the date also contains time information, the default time is midnight (00:00:00). If a date is required to be entered in another century and a specific time is also required, use the TO_DATE function. Example Record information for the student in the S_EMP table. Supply the current user name for the USERID column. Set the START_DATE to be January 1, 1996, 8:00 A.M. SQL> INSERT INTO s_emp (id, first_name, 2 last_name, userid, salary, start_date) 3 VALUES (26, ’Donna’, 4 ’Smith’, USER, NULL, 5 TO_DATE(’01-JAN-96 08:00’, 6 ’DD-MON-YY HH:MI’)); 1 row created. If the RR format is set, the century may not be the current one.

Manipulating Data

11 13

11 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
Inserting Values by Using Substitution Variables You can produce an INSERT command that allows the user to add values interactively by using SQL*Plus substitution variables.

continued

Example Record information for a department in the S_DEPT table. Prompt the user for the department number, department name, and region number. SQL> INSERT INTO s_dept (id, name, 2 region_id) 3 VALUES (&department_id, ‘&department_name’, 4 &region_id); Enter value for department_id: 61 Enter value for department_name: Accounting Enter value for region_id: 2 1 row created. For date and character values, the ampersand and the variable name are enclosed in single quotation marks.

Manipulating Data

11 15

11 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a New Row to a Table
Creating a Script to Manipulate Data

continued

You can save your command with substitution variables to a file and execute the file. Each time you execute the command, it will prompt you for new values. Customize the prompts by using the SQL*Plus ACCEPT command. Example Record information for a department in the S_DEPT table. Prompt the user for the department number, department name, and region number. Customize the prompt messages.
ACCEPT ACCEPT ACCEPT INSERT VALUES department_id PROMPT ’Please enter the department number:’ department_name PROMPT ’Please enter the department name:’ region_id PROMPT ’Please enter the region number:’ INTO s_dept (id, name, region_id) (&department_id, ’&department_name’, &region_id);

Please enter the department number: 61 Please enter the department name: Accounting Please enter the region number: 2 1 row created. Do not prefix the SQL*Plus substitution parameter with the ampersand (&) when referencing it in the ACCEPT command. Use a dash (-) to continue a SQL*Plus command on the next line.

Manipulating Data

11 17

11 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Copying Rows from Another Table
You can use the INSERT statement to add rows to a table where the values are derived from existing tables. In place of the VALUES clause, you use a subquery. Syntax INSERT INTO subquery; where: table column subquery table [column (, column)]

is the table name. is the name of the column in the table to populate. is the subquery that returns rows into the table.

For more information, see Oracle7 Server SQL Reference, Release 7.3, “SELECT,” Subqueries section. Example Copy selected rows from the S_EMP table into the HISTORY table. SQL> 2 3 4 5 6 INSERT INTO HISTORY (id, last_name, salary, title, start_date) SELECT id, last_name, salary, title, start_date FROM s_emp WHERE start_date < ’01-JAN-94’;

10 rows created. The number of columns in the column list of the INSERT clause must match the number of values in the subquery.

Manipulating Data

11 19

11 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Updating Rows
You can modify existing rows by using the UPDATE command. Syntax UPDATE SET [WHERE where: table column value condition table column = value [, column = value...] condition]; is the table name. is the name of the column in the table to populate. is the corresponding value or subquery for the column. identifies the rows to be updated and is composed of column names, expressions, constants, subqueries, and comparison operators.

Confirm the update operation by querying the table to display the updated rows. For more information, see Oracle7 Server SQL Reference, Release 7.3, “UPDATE.”

Manipulating Data

11 21

11 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Updating Rows

continued

Example Transfer employee number 2 to department 10. Transfer employee number 1 to department 32 and change the employee’s salary to 2550. SQL> UPDATE 2 SET 3 WHERE s_emp dept_id = 10 id = 2;

1 row updated.

SQL> UPDATE 2 SET 3 WHERE

s_emp dept_id = 32, salary = 2550 id = 1;

1 row updated. Confirm both data changes. SQL> SELECT 2 FROM 3 WHERE id, last_name, salary, dept_id s_emp id IN (1,2);

ID ------2 1

LAST_NAME SALARY DEPT_ID --------- ------ ------Ngao 1450 10 Velasquez 2550 32

Manipulating Data

11 23

11 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Updating Rows

continued

If you do not include a WHERE clause in your UPDATE command, all rows in the table will be updated. Example Give a commission of 10 percent to every employee in the company. Confirm the changes. SQL> UPDATE 2 SET s_emp commission_pct = 10;

25 rows updated.

SQL> SELECT 2 FROM

id, commission_pct s_emp;

ID COMMISSION_PCT ------- -------------1 10 2 10 3 10 4 10 5 10 6 10 ... 25 rows selected.

Manipulating Data

11 25

11 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Updating Rows
Integrity Constraint Error

continued

If you attempt to update a record with a value that is tied to an integrity constraint, you will experience an error. Example If the value you specify does not exist in the parent table, then you receive the “parent key” violation ORA-02291. SQL> UPDATE 2 SET 3 WHERE s_emp dept_id = 60 dept_id = 10;

update s_emp * ERROR at line 1: ORA-02291: integrity constraint (USR.S_EMP_DEPT_ID_FK) violated - parent key not found

Manipulating Data

11 27

11 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Deleting Rows
You can remove existing rows by using the DELETE command. Syntax DELETE [FROM] table [WHERE condition]; where: table condition is the table name. identifies the rows to be deleted and is composed of column names, expressions, constants, subqueries, and comparison operators.

Confirm the delete operation by displaying the deleted rows by using the SELECT command. If the WHERE clause is omitted, all rows in the table will be deleted. Example Remove all information about employees who started after January 1, 1996. SQL> DELETE FROM s_emp 2 WHERE start_date > 3 TO_DATE(’01.01.1996’,’DD.MM.YYYY’); 1 row deleted. For more information, see Oracle7 Server SQL Reference, Release 7.3, “DELETE.”

Manipulating Data

11 29

11 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Deleting Rows

continued

If you do not include a WHERE clause in your DELETE command, all rows in the table will be deleted. Example Eliminate all data from the TEST table. SQL> DELETE FROM 25,000 rows deleted. Confirm the deletions. SQL> SELECT 2 FROM * test; test;

no rows selected

Manipulating Data

11 31

11 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Deleting Rows
Integrity Constraint Error

continued

If you attempt to delete a record with a value that is tied to an integrity constraint, you will experience an error. Example Attempt to delete all departments in region number 1. SQL> DELETE 2 WHERE s_dept region_id = 1;

delete from s_region * ERROR at line 1: ORA-02292: integrity constraint (USR.S_EMP_DEPT_ID_FK) violated - child record found If the parent record you attempt to delete has child records, then you receive the “child record found” violation ORA-02292.

Manipulating Data

11 33

11 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Transaction Processing
The Oracle7 Server ensures data consistency based on transactions. Transactions give you more flexibility and control when changing data, and assure data consistency in the event of user process failure or system failure. Transactions consist of DML commands that make up one consistent change to the data. For example, a transfer of funds between two accounts should include the debit to one account and the credit to another account in the same amount. Both actions should either fail or succeed together. The credit should not be committed without the debit. Transaction Types Type Description

Data manipulation (DML) Consist of any number of DML statements that the Oracle7 Server treats as a single entity or a logical unit of work. Data definition (DDL) Data control (DCL) Consist of only one DDL statement. Consists of only one DCL statement.

When Does a Transaction Start and End? A transaction begins when the first executable SQL command is encountered and terminates when one of the following occurs:
D D D D D

A COMMIT or ROLLBACK command is issued. A DDL command, such as CREATE, or DCL command is issued. Certain errors are detected, such as deadlocks. The user exits SQL*Plus. A machine fails or the system crashes.

After one transaction ends, the next executable SQL statement will automatically start the next transaction. A DDL command or a DCL command is automatically committed and therefore implicitly ends a transaction.

Manipulating Data

11 35

11 36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Transaction Processing
Explicit Transaction Control Statements Control the logic of transactions by using the COMMIT, SAVEPOINT, and ROLLBACK statements. Command COMMIT SAVEPOINT name ROLLBACK [TO SAVEPOINT name] Description

continued

Ends the current transaction by making all pending data changes permanent. Marks a savepoint within the current transaction. Ends the current transaction by discarding all pending data changes.

Implicit Transaction Processing Status Automatic commit Circumstance DDL command or DCL command is issued. Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK. Automatic rollback Abnormal termination of SQL*Plus, or system failure.

Manipulating Data

11 37

11 38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Committing Changes
Every data change made during the transaction is temporary until the transaction is committed. State of the Data Before COMMIT or ROLLBACK
D

Data manipulation operations primarily affect the database buffer; therefore, the previous state of the data can be recovered. The current user can review the results of the data manipulation operations by querying the tables. Other user cannot view the results of the data manipulation operations for the current user. Oracle7 institutes read consistency to ensure that each user sees data as it existed at the last commit. The affected rows are locked; other users cannot change the data within the affected rows.

D

D

D

Manipulating Data

11 39

11 40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Committing Changes

continued

Make all pending changes permanent by using the COMMIT command. Following a COMMIT
D D D D

Data changes are written to the database. The previous state of the data is permanently lost. All users can view the results of the transaction. The locks on the affected rows are released; the rows are now available for other users to perform new data changes. All savepoints are erased.

D

Example Create a new Education department with at least one employee. Make the data change permanent. SQL> INSERT INTO 2 VALUES 1 row created. s_dept (id, name, region_id) (54, ’Education’, 1);

SQL> UPDATE 2 SET 3 WHERE

s_emp dept_id = 54 id = 2;

1 row updated.

SQL> COMMIT; Commit complete.

Manipulating Data

11 41

11 42

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Rolling Back Changes
Discard all pending changes by using the ROLLBACK statement. Following a ROLLBACK
D D D

Data changes are undone. The previous state of the data is restored. The locks on the affected rows are released; the rows are now available for other users to perform new data changes.

Example While attempting to remove a record from the TEST table, accidentally empty the table. Correct the mistake, then reissue the proper command, and make the data change permanent. SQL> DELETE FROM 25,000 rows deleted. test;

SQL> ROLLBACK; Rollback complete.

SQL> DELETE FROM 2 WHERE 1 row deleted.

test id = 100;

SQL> SELECT 2 FROM 3 WHERE

* test id = 100;

no rows selected

SQL> COMMIT; Commit complete.

Manipulating Data

11 43

11 44

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Rolling Back Changes to a Savepoint
You can create a marker within the current transaction by using the SAVEPOINT command. The transaction therefore can be divided into smaller sections. You can then discard pending changes up to that marker by using the ROLLBACK TO SAVEPOINT statement. Example Update the salary for all Stock Clerks by 10 percent. Create a savepoint named UPDATE_DONE. SQL> UPDATE 2 SET 3 WHERE s_emp salary = salary * 1.1 title = ’Stock Clerk’;

10 rows updated. SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT INTO 2 VALUES 1 row inserted. SQL> SELECT 2 FROM 3 WHERE * s_region id = 8 s_region (id, name) (8, ’Central’)

ID NAME ------- -------------------8 Central SQL> ROLLBACK TO update_done; Rollback complete. SQL> SELECT 2 FROM 3 WHERE * s_region id = 8

no rows selected

If you create a second savepoint with the same name as an earlier savepoint, the earlier savepoint is deleted.

Manipulating Data

11 45

11 46

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Statement Level Rollback
Part of a transaction may be discarded by an implicit rollback if a statement execution error is detected. If a single DML statement fails during execution of a transaction, its effect is undone by a statement-level rollback, but the changes made by the previous DML statements in the transaction will not be discarded. They can be committed or rolled back explicitly by the user. Oracle issues an implicit COMMIT before and after any Data Definition Language statement. So, even if your DDL statement does not execute successfully, you cannot rollback the previous statement because the server issued a commit. Terminate your transactions explicitly by executing a COMMIT or ROLLBACK statement.

Manipulating Data

11 47

11 48

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Manipulate data in the Oracle database by using the INSERT, UPDATE, and DELETE statements. Control data changes by using the COMMIT, SAVEPOINT, and ROLLBACK commands. Data Manipulation and Transaction Control Commands Command INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK Description Adds a new row to the table. Modifies existing rows in the table. Removes existing rows from the table. Makes all pending data changes permanent. Allows a rollback to that savepoint marker. Discards all pending data changes.

Manipulating Data

11 49

11 50

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
This practice builds on a prior lesson with the DEPARTMENT and EMPLOYEE tables. In this practice, you will add rows to the tables, update, and delete data from the tables, and control your transactions. Practice Contents
D D D

Inserting rows into the tables Updating and deleting rows in the tables Controlling transactions

Manipulating Data

11 51

11 52

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11
1.

Insert data into the DEPARTMENT and EMPLOYEE tables.

Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invoke scripts p9q2.sql and p9q3.sql to create DEPARTMENT table and EMPLOYEE table respectively.
a. b.

Describe the DEPARTMENT and EMPLOYEE tables to identify the column names. View the constraints on each table to identify the primary key and any other constraints. Execute the script p10q4.sql, which is a generic query to confirm constraints. Add a row of data to the DEPARTMENT table. The department number is 10 and the department name is Finance. Do not list the columns in the INSERT clause. Add two rows of data to the EMPLOYEE table. Write a script named p11q1d.sql that prompts you for each column value. The first employee is Donna Smith in department number 10, and her employee number is 200. The second employee is Albert Jones in department number 54, and his employee number is 201. What was the result and why?

c.

d.

e.

Insert into the DEPARTMENT table department number 10 and department name of Marketing. What was the result and why?

f. g.

Confirm your additions to the tables. Write a script named p11q1g.sql to add the following rows to the DEPARTMENT table: Marketing as number 37; Sales as number 54; and Personnel as number 75. Execute the p11q1d.sql script to add the following rows to the EMPLOYEE table: Albert Jones in department number 54, and employee number 201; Harry Chin in department 75 and employee number 202; Rey Guiliani in department 37 and employee number 203. Confirm your additions to the tables. Make the data additions permanent.

h.

i. j.

Manipulating Data

11 53

Practice 11
2.

continued

Update and delete data in the DEPARTMENT and EMPLOYEE tables.
a. b. c. d.

Change the name of the Personnel department to Human Resources. Change the last name of employee 202 to Korsgaard. Verify your changes to the tables. Attempt to delete department 54. What was the result and why?

e. f.

Delete Albert Jones from the EMPLOYEE table. Attempt to delete department 54 from the DEPARTMENT table again. What was the result and why?

g. h. 3.

Verify the changes to your tables. Commit all pending changes. Execute the p11q1g.sql script to reinstate the Sales department as department number 54. Verify your addition. Mark a transaction processing savepoint. Empty the entire EMPLOYEE table. Verify that the EMPLOYEE table is empty. Discard the most recent DELETE operation without discarding the most recent INSERT operation. Verify that the new row in the DEPARTMENT table is still intact. Verify that the EMPLOYEE table has all three rows. Make the data addition permanent.

Control data transactions to the DEPARTMENT and EMPLOYEE tables.
a. b. c. d. e. f. g. h.

11 54

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

12
Altering Tables and Constraints

12 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
After you create your tables, you may need to change the table structures because you omitted a column, your column definition needs to be changed, or you want to enable or disable constraints. This lesson will demonstrate how you can amend table structures as well as add and remove constraints. At the end of this lesson, you should be able to
D D D D D D

Add and modify table columns. Add, enable, disable, or remove constraints. Drop a table. Remove all rows leaving the table definition intact. Change object names. Add comments to objects and view comments from the data dictionary.

Altering Tables and Constraints

12 3

12 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
Once you have created your tables, you can modify their structure by using the ALTER TABLE command. Add columns, modify the column length, add or drop constraints, and enable or disable constraints by using this command. If you want to remove a table, both the rows and the data structure of a table, invoke the DROP TABLE command. Other commands that affect tables that are covered in this lesson are
D D D

RENAME, to change a database object name. TRUNCATE, to remove all rows from a table. COMMENT, to add a comment about a database object to the data dictionary.

All of these commands are data definition commands (DDL). When you issue these statements, an automatic commit occurs. You cannot roll back DDL commands. Therefore, be very careful when you execute them.

Altering Tables and Constraints

12 5

12 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a Column
You can add columns to a table by using the ALTER TABLE command with the ADD clause. Syntax ALTER TABLE table ADD (column datatype [DEFAULT expr][NOT NULL] [, column datatype]...); where: table column datatype DEFAULT expr NOT NULL Guidelines
D D

is the name of the table. is the name of the new column. is the datatype and length of the new column. specifies the default value for a new column. adds a NOT NULL constraint to the new column.

You can add or modify columns, but you cannot drop them from a table. You cannot specify where the column is to appear. The new column becomes the last column.

Altering Tables and Constraints

12 7

12 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Modifying a Column
You can modify a column definition by using the ALTER TABLE command with the MODIFY clause. Column modification can include changes to a column’s datatype, size, default value, and NOT NULL column constraint. Syntax ALTER TABLE table MODIFY (column datatype [DEFAULT expr][NOT NULL] [, column datatype]...); where: table column datatype DEFAULT expr NOT NULL Guidelines
D D

is the name of the table. is the name of the column. is the datatype and length of the column. specifies the default value for a new column. adds a NOT NULL constraint to the new column.

Increase the width or precision of a numeric column. Decrease the width of a column if the column contains only null values or if the table has no rows. Change the datatype if the column contains null values. Convert a CHAR column to the VARCHAR2 datatype or convert a VARCHAR2 column to the CHAR datatype if the column contains null values or if you do not change the size. A change to the default value of a column only affects subsequent insertions to the table. Add a NOT NULL constraint only if there are no null values in the column.

D D

D

D

Altering Tables and Constraints

12 9

12 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding and Dropping a Constraint
You can add or drop constraints for existing tables by using the ALTER TABLE command with the ADD or DROP clause. Syntax ALTER TABLE table ADD [CONSTRAINT constraint] type (column); where: table constraint type column is the name of the table. is the name of the constraint. is the constraint type. is the name of the column affected by the constraint.

The constraint name syntax is optional, although recommended. If you do not name your constraints, the system will generate constraint names. Guidelines
D

You can add, drop, enable, or disable a constraint, but you cannot modify its structure. You can add a NOT NULL constraint to an existing column by using the MODIFY clause of the ALTER TABLE command.

D

Altering Tables and Constraints

12 11

12 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding and Dropping a Constraint

continued

To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views. Then, use the ALTER TABLE command with the DROP clause. The CASCADE option of the DROP clause causes any dependent constraints also to be dropped. Syntax ALTER TABLE table DROP PRIMARY KEY | UNIQUE (column) | CONSTRAINT constraint [CASCADE]; where: table column constraint is the name of the table. is the name of the column affected by the constraint. is the name of the constraint.

When you drop an integrity constraint, that constraint is no longer enforced by the Oracle7 Server and is no longer available in the data dictionary.

Altering Tables and Constraints

12 13

12 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Disabling and Enabling a Constraint
You can enable or disable constraints without dropping them or recreating them by using the ALTER TABLE command with the ENABLE or DISABLE clause. Syntax ALTER TABLE table DISABLE | ENABLE CONSTRAINT constraint [CASCADE];

Guidelines
D

If you enable a constraint, that constraint applies to all the data in the table. All the data in the table must fit the constraint. If you enable a UNIQUE or PRIMARY KEY constraint, a UNIQUE or PRIMARY KEY index is automatically created. You can use the ENABLE and DISABLE clauses in both the CREATE TABLE command and the ALTER TABLE command. The CASCADE clause disables dependent integrity constraints.

D

D

D

Altering Tables and Constraints

12 15

12 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Dropping a Table
The DROP TABLE command removes the definition of an Oracle7 table. When you drop a table, the database loses all the data in the table and all the indexes associated with it. The CASCADE CONSTRAINTS option will also remove dependent referential integrity constraints. Syntax DROP TABLE where: table Guidelines
D D

table [CASCADE CONSTRAINTS]; is the name of the table.

All data is deleted from the table. Any views, synonyms, stored procedures, functions, or packages will remain, but are invalid. Any pending transactions are committed. Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table.

D D

The DROP TABLE command, once executed, is irreversible. The Oracle7 Server does not question the action when you issue the DROP TABLE command. If you own that table or have a high level privilege, then the table is immediately removed. All DDL commands issue a commit, therefore making the transaction permanent.

Altering Tables and Constraints

12 17

12 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Renaming and Truncating a Table
Additional DDL commands include the RENAME command, which is used to rename a table, view, sequence, or synonym, and the TRUNCATE TABLE command, which is used to remove all rows from a table and to release the storage space used by that table. Syntax RENAME Command

RENAME old_name TO new_name; You must be the owner of the object you rename. Syntax TRUNCATE Command

TRUNCATE TABLE table; You must be the owner of the table or have DELETE TABLE system privileges to truncate a table. The DELETE command can also remove all rows from a table, but it does not release storage space.

Altering Tables and Constraints

12 19

12 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Adding a Comment to a Table
You can add a comment of up to 2000 bytes about a column, table, view, or snapshot by using the COMMENT command. The comment is stored in the data dictionary and can be viewed in one of the following data dictionary views in the COMMENTS column:
D D D D

ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS

Syntax COMMENT ON TABLE table | COLUMN table.column IS ’text’; where: table column text Examples Add a comment on the S_EMP table. SQL> COMMENT ON TABLE s_emp IS ’Employee Information’; Comment created. Remove a comment from a column. SQL> COMMENT ON COLUMN s_emp.last_name IS ’’; Comment created. is the name of the table. is the name of the column in a table. is the text of the comment.

Altering Tables and Constraints

12 21

12 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Data definition commands (DDL) allow you to create, modify, remove, and rename objects. When you issue a DDL command, an autocommit occurs. You cannot roll back your commands. CREATE TABLE
D D

You can create a table and the indicated constraints. Create a table based on another table by using a subquery.

ALTER TABLE
D D

Modify table structures and constraints. Change column widths, change column datatypes, add columns, add or drop constraints, and enable or disable constraints.

DROP TABLE
D D

Remove rows and a table structure. Once executed, this command cannot be rolled back.

RENAME
D

Rename a table, view, sequence, or synonym.

TRUNCATE
D D

Remove all rows from a table and release the storage space used by the table. DELETE command only removes rows.

COMMENT
D D

Add a comment to a table or a column. Query the data dictionary to view the comment.

Altering Tables and Constraints

12 23

12 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
In this practice, you will create, modify, and drop tables related to the EMPLOYEE and DEPARTMENT tables using the commands covered in this lesson. Practice Contents
D D D D D D

Creating a new table by using the CREATE TABLE AS syntax Adding constraints Modifying column definitions Dropping tables Adding a comment to a table Displaying information in data dictionary views

Altering Tables and Constraints

12 25

12 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 12
1. 2.

Create a WORKER table, which copies the data from the EMPLOYEE table. Describe the table to confirm its structure. View the constraints for this new table. Save this command to a script named p12q2.sql. Note the types and names of the constraints.

3.

Compare these constraints to those in the EMPLOYEE table. Note the types and names of the constraints.

4. 5.

Add a table level PRIMARY KEY constraint to the WORKER table using the ID column. The constraint should be immediately enabled. Add a foreign key reference from the DEPARTMENT table to the DEPT_ID column in the WORKER table. Confirm that the constraints were added by re-executing p12q2.sql. Display the object names and types from the USER_OBJECTS data dictionary view. You may want to format the columns for readability. Notice that the new table and a new index were created. Drop the EMPLOYEE table, while leaving the WORKER table in the database. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype, length 30. Add a comment to the WORKER and DEPARTMENT table definitions describing the tables. Confirm your additions in the data dictionary. TABLE_NAME --------------DEPARTMENT WORKER COMMENTS -----------------------------Departmental Listing Employee Information

6.

7.

If you have time, complete the following exercises.
8. 9.

Altering Tables and Constraints

12 27

12 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

13
Creating Sequences

13 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
Many applications require the use of unique numbers as primary key values. You can either build code into the application to handle this requirement or use a sequence to generate unique numbers. This lesson covers creating and using sequences that create unique numbers. At the end of this lesson, you should be able to
D D D D D

Explain the use of sequences. Create a sequence. Use a sequence. Modify a sequence definition. Remove a sequence.

Creating Sequences

13 3

13 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
A sequence generator can be used to automatically generate sequence numbers for rows in tables. A sequence is a database object created by a user and can be shared by multiple users. A typical usage for sequences is to create a primary key value, which must be unique for each row. The sequence is generated and incremented (or decremented) by an internal Oracle7 routine. This can be a time saving object because it can reduce the amount of application code needed to write a sequence generating routine. Sequence numbers are stored and generated independently of tables. Therefore, the same sequence can be used for multiple tables.

Creating Sequences

13 5

13 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Sequence
Define a sequence to generate sequential numbers automatically by using the CREATE SEQUENCE command. Abridged Syntax CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}] where: sequence INCREMENT BY n is the name of the sequence generator. specifies the interval between sequence numbers where n is an integer. If this clause is omitted, the sequence will increment by 1. specifies the first sequence number to be generated. If this clause is omitted, the sequence will start with 1. specifies the maximum value the sequence can generate. specifies a maximum value of 1027. This is the default option. specifies the minimum sequence value. specifies a minimum value of 1. specifies that the sequence continues to generate values after reaching either its maximum or minimum value or does not generate additional values. NOCYCLE is the default option. specifies how many values the Oracle7 Server will preallocate and keep in memory. By default, the Server will cache 20 values.

START WITH n

MAXVALUE n NOMAXVALUE MINVALUE n NOMINVALUE CYCLE | NOCYCLE

CACHE n | NOCACHE

For more information, see Oracle7 Server SQL Reference, Release 7.3, “CREATE SEQUENCE.”

Creating Sequences

13 7

13 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Sequence

continued

Example Create a sequence named S_DEPT_ID to be used for the DEPT_ID column of the S_DEPT table. Start the sequence at 51. Do not allow caching and do not allow the sequence to cycle. SQL> CREATE SEQUENCE 2 INCREMENT BY 3 START WITH 4 MAXVALUE 5 NOCACHE 6 NOCYCLE; Sequence created. Do not use the CYCLE option if the sequence is used to generate primary key values. s_dept_id 1 51 9999999

Creating Sequences

13 9

13 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Sequence
Confirming Sequences

continued

Once you have created your sequence, it is documented in the data dictionary. Since a sequence is a database object, you can identify it in the USER_OBJECTS data dictionary table. You can also confirm the settings of the sequence by selecting from the data dictionary’s USER_SEQUENCES table. Example Display information about all the sequences that you own. SQL> SELECT 2 3 FROM sequence_name, min_value, max_value, increment_by, last_number user_sequences;

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER --------------- --------- --------- ------------ ----------S_CUSTOMER_ID 1 9999999 1 216 S_DEPT_ID 1 9999999 1 51 S_EMP_ID 1 9999999 1 26 S_IMAGE_ID 1 9999999 1 1981 S_LONGTEXT_ID 1 9999999 1 1369 S_ORD_ID 1 9999999 1 113 S_PRODUCT_ID 1 9999999 1 50537 S_REGION_ID 1 9999999 1 6 S_WAREHOUSE_ID 1 9999999 1 10502 9 rows selected.

Creating Sequences

13 11

13 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Using a Sequence
Once you create your sequence, you can use the sequence to generate sequential numbers for use in your tables. Reference the sequence values by using the NEXTVAL and CURRVAL pseudocolumns. NEXTVAL and CURRVAL Pseudocolumns The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a specified sequence. You must qualify NEXTVAL with the sequence name. When you reference sequence.NEXTVAL, a new sequence number is generated and the current sequence number is placed in CURRVAL. The CURRVAL pseudocolumn is used to refer to a sequence number that the current user has just generated. NEXTVAL must be used to generate a sequence number in the current user’s session before CURRVAL can be referenced. You must qualify CURRVAL with the sequence name. When sequence.CURRVAL is referenced, the last value returned to that user’s process is displayed. Rules for Using NEXTVAL and CURRVAL You can use NEXTVAL and CURRVAL in
D D D D

The SELECT list of a SELECT statement that is not part of a subquery. The SELECT list of a subquery in an INSERT statement. The VALUES clause of an INSERT statement. The SET clause of an UPDATE statement. A SELECT list of a view. A SELECT statement with the DISTINCT keyword. A SELECT statement with the GROUP BY, HAVING, or ORDER BY clauses. A subquery in a SELECT, DELETE, or UPDATE statement. A DEFAULT expression in a CREATE TABLE or ALTER TABLE command.

You cannot use NEXTVAL and CURRVAL in
D D D D D

For more information, see Oracle7 Server SQL Reference, Release 7.3, “Pseudocolumns” section and “CREATE SEQUENCE.”

Creating Sequences

13 13

13 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Using a Sequence
Caching Sequence Values

continued

Cache sequences in the memory to allow faster access to those sequence values. The cache is populated at the first reference to the sequence. Each request for the next sequence value is retrieved from the cached sequence. After the last sequence is used, the next request for the sequence pulls another cache of sequences into memory. Beware of Gaps in Your Sequence Although sequence generators issue sequential numbers without gaps, this action occurs independent of a commit or rollback. Therefore, if you roll back a command containing a sequence, the number is lost. Another event that can cause gaps in the sequence is a system crash. If the sequence caches values in the memory, then those values are lost if the system crashes. Because sequences are not tied directly to tables, the same sequence can be used for multiple tables. If this occurs, each table can contain gaps in the sequential numbers. Viewing the Next Available Sequence Value Without Incrementing It It is possible to view the next available sequence value without incrementing it, only if the sequence was created with NOCACHE, by querying the USER_SEQUENCES table.

Creating Sequences

13 15

13 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Altering a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from the sequence will be allocated and you will receive an error indicating the sequence exceeds the MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER SEQUENCE command. Syntax ALTER SEQUENCE sequence [INCREMENT BY n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]

Guidelines
D

You must own or you have the ALTER privilege for the sequence in order to modify it. Only future sequence numbers are affected by the ALTER SEQUENCE command. Some validation is performed. For example, a new MAXVALUE cannot be imposed that is less than the current sequence number. The START WITH option cannot be changed using ALTER SEQUENCE. The sequence must be dropped and re-created in order to restart the sequence at a different number.

D

D

D

For more information, see Oracle7 Server SQL Reference, Release 7.3, “ALTER SEQUENCE.”

Creating Sequences

13 17

13 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Removing a Sequence
To remove a sequence from the data dictionary, use the DROP SEQUENCE command. You must be the owner of the sequence or have the DROP ANY SEQUENCE privilege to remove it. Syntax DROP SEQUENCE sequence; where: sequence is the name of the sequence generator.

For more information, see Oracle7 Server SQL Reference, Release 7.3, “DROP SEQUENCE.”

Creating Sequences

13 19

13 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
The sequence generator can be used to automatically generate sequence numbers for rows in tables. This can be time saving, and can reduce the amount of application code needed. A sequence is a database object that can be shared with other users. Information about the sequence can be found in the USER_SEQUENCES table of the data dictionary. To use a sequence, reference it with either the NEXTVAL or the CURRVAL pseudocolumns.
D D

Retrieve the next number in the sequence by referencing sequence.NEXTVAL. Return the current available number by referencing sequence.CURRVAL.

Creating Sequences

13 21

13 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
In this practice, you will create a sequence to be used when populating your DEPARTMENT and WORKER tables. Practice Contents
D D D

Creating a sequence Modifying a sequence Using a sequence

Creating Sequences

13 23

13 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 13
1.

Create a sequence to be used with the DEPARTMENT table’s primary key column. The sequence should start at 76 and have a maximum value of 80. Be sure that it increments by one number. Name the sequence DEPT_ID_SEQ. Create another sequence. This sequence will be used with the WORKER table’s primary key column. Start this sequence at 204, and set the maximum value to be 9999999. Be sure that it increments by one number. Allow the sequence to cache 5 numbers. Name the sequence WORKER_ID_SEQ. Write a script to display the following information about your sequences: sequence name, cache size, maximum value, increment size, and last number generated. Name the script p13q3.sql. Write an interactive script to insert a row into the DEPARTMENT table. Name your script p13q4.sql. Be sure to use the sequence you created for the ID column. Create a customized prompt to enter the department name. Execute your script. Add two departments named Education and Administration. Confirm your additions. Display information about your sequences by executing the p13q3.sql script. Notice that the WORKER_ID_SEQ last number does not match the highest primary key value in Exercise 6. Why? Write a script to insert two rows into the WORKER table. Name your script p13q5.sql. Use the sequence you create for the ID column. Execute your script. Add Tomas Lira as the President in the last department you just added to the table. The other employee is Anna Seigher who is the Vice President in the Finance department. Confirm your additions to the DEPARTMENT table and WORKER table. Note the highest primary key values for each table.

2.

3.

4.

5.

If you completed Practice 12, Exercise 8, you can do the following two exercises.
6.

7.

Creating Sequences

13 25

Practice 13
If you have time, complete the following exercises:
8.

continued

Execute p13q4.sql to insert four additional departments named Accounting, Warehouse, Operations, and Research. What happened and why?

9. 10. 11.

Modify your department sequence to allow no maximum value. Verify the change to the sequence by executing the p13q3.sql script. Add the Research department by using your script named p13q4.sql. Make this addition permanent. Display the contents of the DEPARTMENT table and WORKER table.

13 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

14
Creating Views

14 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
In this lesson, you will see how views can be used to present data to users in a variety of ways. In addition, you will see how integrity constraints can be enforced, if using a view to insert, update, or delete data. At the end of this lesson, you should be able to
D D D D D D

Explain the concept of a view. Use data dictionary views. Create simple and complex views. Create a view with an option to enforce constraints. Modify a view. Remove a view.

Creating Views

14 3

14 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
Present logical subsets or combinations of data by creating views of tables. What Is a View? A view is a logical table based on a table or another view. A view contains no data of its own, but is rather like a “window” through which data from tables can be viewed or changed. The tables upon which a view is based are called base tables. The view is stored as a SELECT statement in the data dictionary. Advantages of Views
D

Restrict access to the database because the view can display a selective portion of the database. Allow users to make simple queries to retrieve the results from complicated queries. For example, views allow users to query information from multiple tables without knowing how to write a join statement. Provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables. Provide groups of users access to data according to their particular criteria.

D

D

D

For more information, see Oracle7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Creating Views

14 5

14 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a View
Create a view by embedding a subquery within the CREATE VIEW statement. Abridged Syntax CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY] where: OR REPLACE FORCE recreates the view if it already exists. creates the view regardless of whether the base tables exist or not. NOFORCE creates the view only if the base tables exist. This is the default. view is the name of the view. alias specifies names for the expressions selected by the view’s query. The number of aliases must match the number of expressions selected by the view. subquery is a complete SELECT statement. You can use aliases for the columns in the SELECT list. WITH CHECK OPTION specifies that only rows accessible to the view may be inserted or updated. constraint is the name assigned to the CHECK OPTION constraint. WITH READ ONLY ensures that no DML operations can be performed on this view.

Guidelines
D D D D

The query that defines a view can contain complex SELECT syntax, including joins, groups, and subqueries. The query that defines the view cannot contain an ORDER BY clause. If you do not specify a constraint name, the system will assign a default name in the format SYS_Cn. You can use the OR REPLACE option to change the definition of the view without dropping and re-creating it, or regranting object privileges previously granted on it.

Creating Views

14 7

14 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a View

continued

There are two classifications for views: simple and complex. The basic difference is related to the DML operations. Simple Views Compared to Complex Views Characteristic Number of tables Contain functions Contain groups of data (DISTINCT or group functions) DML through the view Example Create a view containing the employee number, last name, and job title for employees in department 45. Display the contents. SQL> 2 3 4 CREATE VIEW AS SELECT FROM WHERE empvu45 id, last_name, title s_emp dept_id = 45; Simple Views Only one No No Yes Complex Views One or more Yes Yes No

View created.

SQL> SELECT 2 FROM

* empvu45;

ID -----10 24 25

LAST_NAME -----------Havel Dancs Schwartz

TITLE --------------------Warehouse Manager Stock Clerk Stock Clerk

Creating Views

14 9

14 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a View
Control the column names by including column aliases within the subquery.

continued

Example Create a view containing the employee number, first name with the alias FIRST, last name with the alias LAST, and salary with the alias MONTHLY_SALARY for department 41. SQL> 2 3 4 5 CREATE VIEW salvu41 AS SELECT id, first_name FIRST, last_name LAST, salary MONTHLY_SALARY FROM s_emp WHERE dept_id = 41;

View created. Alternatively, control the column names by including column aliases in the CREATE VIEW clause. To change the view definition, use the CREATE OR REPLACE clause. Example Modify EMPVU45 view. Change the employee number to have a heading ID_NUMBER, last name to a heading EMPLOYEE, and title to a heading JOB. SQL> 2 3 4 5 CREATE OR REPLACE VIEW empvu45 (id_number, employee, job) AS SELECT id, last_name, title FROM s_emp WHERE dept_id = 45;

View created. Note: When assigning column aliases in the CREATE VIEW clause, remember that the aliases are listed in the same order as the columns in the subquery.

Creating Views

14 11

14 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a View

continued

Create a complex view that contains group functions to display values from two tables. Example Create a view of the department names, minimum salary, maximum salary, and average salary by department. Display the structure of the view and its contents. SQL> 2 3 4 5 6 7 CREATE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) AS SELECT d.name, min(e.salary), max(e.salary), avg(e.salary) FROM s_emp e, s_dept d WHERE e.dept_id = d.id GROUP BY d.name;

View created.

SQL> DESCRIBE dept_sum_vu Name Null? ------------------------------- -------NAME NOT NULL MINSAL MAXSAL AVGSAL Type ---VARCHAR2(25) NUMBER NUMBER NUMBER

SQL> SELECT 2 FROM

* dept_sum_vu;

NAME MINSAL MAXSAL AVGSAL -------------------- ---------- ---------- ---------Administration 1550 2500 2025 Finance 1450 1450 1450 Operations 750 1450 1086.8 Sales 795 1525 1367.85714

Creating Views

14 13

14 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Performing DML Operations on a View
You can perform DML operations on data through a view provided those operations follow the rules outlined below:
D

You can remove a row from a view unless it contains any of the following:
D D D

Group functions A GROUP BY clause The DISTINCT command

D

You can modify data in a view unless it contains any of the above and any of the following:
D D

Columns defined by expressions, for example, SALARY * 12. The ROWNUM pseudocolumn.

D

You can add data through a view unless it contains any of the above and there are NOT NULL columns in the base table that are not selected by the view. All required values must be present in the view. Remember that you are adding values directly into the underlying table through the view.

For more information, see Oracle 7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Creating Views

14 15

14 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Performing DML Operations on a View

continued

You can ensure that when you add or update data in a simple view, the added or updated data can be queried through the view. Example Create a view that contains all columns from the S_EMP table for department 45. Add the WITH CHECK OPTION clause. SQL> 2 3 4 5 CREATE OR REPLACE VIEW empvu41 AS SELECT * FROM s_emp WHERE dept_id = 41 WITH CHECK OPTION CONSTRAINT empvu41_ck;

View created. Attempt to change the department number for employee 16 to department 42 through the view. SQL> UPDATE 2 SET 3 WHERE empvu41 dept_id = 42 id = 16;

ERROR at line 3: ORA-01402: view WITH CHECK OPTION where-clause violation Note: No rows are updated because if the department number were to change to 42, the view would no longer be able to see that employee. Therefore, with the WITH CHECK OPTION clause, the view can only see department 41 employees, and does not allow the department number for those employees to be changed through the view.

Creating Views

14 17

14 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Performing DML Operations on a View

continued

You can ensure that no DML operations occur on your view by creating it with the WITH READ ONLY option. Example Modify the EMPVU45 view. Do not allow DML operations to occur on this view. Attempt to remove a row from the view. SQL> 2 3 4 5 6 CREATE OR REPLACE VIEW empvu45 (id_number, employee, job) AS SELECT id, last_name, title FROM s_emp WHERE dept_id = 45 WITH READ ONLY;

View created.

SQL> DELETE FROM 2 WHERE

empvu45 id_number = 10;

ERROR at line 1: ORA-01732: data manipulation operation not legal on this view

Creating Views

14 19

14 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Confirming View Names and Structures
You can confirm the names and defining SELECT statements of views by querying the USER_VIEWS data dictionary table. Example Describe the structure of the USER_VIEWS data dictionary table. Display the names and contents of all views currently owned by the user. SQL> DESCRIBE user_views Name Null? ------------------------------- -------VIEW_NAME NOT NULL TEXT_LENGTH TEXT Type ---VARCHAR2(30) NUMBER LONG

SQL> SELECT 2 FROM

* user_views;

VIEW_NAME TEXT_LENGTH TEXT --------------- ----------- ----------------------------------DEPT_SUM_VU 121 SELECT d.name, MIN(e.salary), MAX(e .salary), AVG(e.salary) FROM s_emp e, s_dept EMPVU41 179 SELECT ”ID”,”LAST_NAME”,”FIRST_NAM E”,”USERID”,”START_DATE”,”COMMENTS” ,”MANAGER_ 56 SELECT id, last_name, title FROM s_emp WHERE dept_id=45 97 SELECT id, first_name first, last_n ame last, salary monthly_salary FROM s_emp WH

EMPVU45

SALVU41

Creating Views

14 21

14 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Removing a View
Use the DROP VIEW command to remove a view. The command removes the view definition from the database. Dropping views has no affect on the tables on which the view was based. Views or other applications based on deleted views become invalid. Only the creator or a user with the DROP ANY VIEW privilege can remove a view. Syntax DROP VIEW where: view view; is the name of the view.

Creating Views

14 23

14 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
A view is based on a table or another view and acts as a window through which data on tables can be viewed or changed. A view does not contain data. The definition of the view is stored in the data dictionary. You can see the definition of the view in the USER_VIEWS data dictionary table. Advantages of Views
D D D D D

Restrict database access Simplify queries Provide data independence Allow multiple views of the same data Remove views without affecting the underlying data

View Options
D D

Can be a simple view based on one table Can be a complex view based on more than one table, or contain groups or functions Can be replaced if one of the same name exists Contain a check constraint Can be read-only

D D D

Creating Views

14 25

14 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
In this practice, you will create simple and complex views, and attempt to perform DML statements to the views. Practice Contents
D D D D D D

Creating a simple view Creating a complex view Creating a view with a check constraint Attempting to modify data in the view Displaying view definitions Removing views

Creating Views

14 27

14 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 14
1.

Create a view called EMP_VU based on the employee number, last name, and department number from the WORKER table. Change the heading for the last name to EMPLOYEE.
a. b.

Display the content of the EMP_VU view. Write a script to display the definition of a view. Pass the name of the view to the script. Save the script as p14q1.sql. Execute the script to view the definition of the EMP_VU view. Change the department number for Smith to 37 in the EMP_VU view. Confirm that Smith is now assigned to department 37.

c. d. 2.

Create a view called MNS_VU that contains the employee number, full name, and department name for all employees in the Marketing and Sales departments in the WORKER and DEPARTMENT tables.
a. b. c.

Display the structure and contents of the MNS_VU view. Display the definition of the MNS_VU view by executing the p14q1.sql script. Display the department name and number of employees in each department.

3.

Modify EMP_VU view contain only those employees in department 37. Add a check constraint so that the department number cannot be modified.
a. b.

Display the contents of the EMP_VU view. Change the department number for Smith back to 54 through the EMP_VU view. Was your operation successful? Why or why not?

If you have time, complete the following exercises:
4.

Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and 4:00 P.M. You can edit the script named p14q1.sql. Execute the script. Display the contents of the view. Remove all views from the data dictionary. Confirm that no views exist in the data dictionary.

5.

Creating Views

14 29

14 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

15
Creating Indexes

15 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
If you want to improve the performance of some queries, you should consider creating an index. You can also use indexes to enforce uniqueness on a column or a collection of columns. At the end of this lesson, you should be able to
D

Distinguish between the indexes that are created automatically and those that are created manually. Identify the uses for indexes. Explain the index structure and why it improves query speed. Create a non-unique index. Remove an index from the data dictionary. Evaluate guidelines for creating and using indexes.

D D D D D

Creating Indexes

15 3

15 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
An Oracle7 Server index is a database object that can speed up the retrieval of rows by using a pointer. Indexes can be created explicitly or automatically. They are transparent to the user. If you do not have an index on the column, then a full table scan will occur. What Is an Index? An index is a database object that provides direct and fast access to rows in a table. Its purpose is to reduce the necessity of disk I/O by using a B*Tree indexed path to locate data quickly. The index is automatically used and maintained by the Oracle7 Server. Once an index is created, no direct activity is required by the user. Indexes are logically and physically independent of the table they index. This means that they can be created or dropped at any time and have no effect on the base tables or other indexes. How Are Indexes Created? Two types of indexes can be created. One type is a unique index. The Oracle7 Server automatically creates this index when you define a column in a table to have a PRIMARY KEY or a UNIQUE constraint. The name of the index is the name given to the constraint. The other type of index a user can create is a non-unique index. For example, you can create a FOREIGN KEY column index for a join in a query to improve retrieval speed. For more information, see Oracle7 Server Concepts Manual, Release 7.3, “Schema Objects” section, “Indexes” topic.

Creating Indexes

15 5

15 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

When Is the Index Used?
Once the index has been created, the Oracle7 Server will use it whenever possible to speed up access to the data. Note that this use is automatic and usually requires no action by the user. A brief guideline is provided below on how the Server determines to use the index. Optimization Techniques When an index is used depends partly on the Oracle Optimizer being used at the time. The Oracle7 Server uses both rule-based and cost-based optimization. Rule-based optimization is when the Oracle7 Server decides when it is appropriate to use an index based on its internal rules. The Server identifies the columns that are indexed and the index types. The cost-based optimization method uses statistics about tables along with information about available indexes to select an execution plan for the SQL statements. For more information, see Tune Oracle7 Applications course description.

Creating Indexes

15 7

15 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Index Structure
An index is an optional structure that is independent of the table structure. Each index is composed of column values that the index is on and pointers (or ROWIDs) to the row containing that value. The pointer directly points to the appropriate row in the table, therefore avoiding a full table scan. B*Tree The Oracle7 Server uses a balanced B*tree index structure. This is a binary, self-balancing search structure to equalize access times to any row. It is an efficient method of ensuring that access to any specified value will take approximately the same time whether the row is at the beginning, middle, or end of the table. Each index that the Oracle7 Server builds consists of a number of pages (or branches) of storage arranged in a tree. Each page (or branch) holds a series of key values and pointers to pages (or branches) lower in the structure until eventually the key values indicate the location of the data itself. The location identifier at the database level is called a ROWID.

Creating Indexes

15 9

15 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Index Structure
Index Types Type Unique Non-unique Single column Concatenated or composite Description

continued

Ensures that values in specified columns are unique. Ensures fastest possible results when querying data. Only one column exists in the index. Can contain up to 16 columns in the index for either performance or uniqueness check purposes. The columns need not be adjacent.

Index types are not mutually exclusive. For example, you can create a unique, concatenated index.

Creating Indexes

15 11

15 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating an Index
Create an index on one or more columns by issuing the CREATE INDEX command. Abridged Syntax CREATE INDEX index ON table (column[, column]...); where: index table column is the name of the index. is the name of the table. is the name of the column in the table to be indexed.

Example Create an index to improve the speed of query access on the LAST_NAME column in the S_EMP table. SQL> CREATE INDEX 2 ON Index created. For more information, see Oracle7 Server SQL Reference, Release 7.3, “CREATE INDEX.” s_emp_last_name_idx s_emp(last_name);

Creating Indexes

15 13

15 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating an Index
More Is Not Always Better

continued

More indexes on a table does not mean it will speed up queries. Each DML operation that is committed on a table with indexes means that the indexes must be updated. The more indexes you have associated with a table, the more effort the Server must make to update all the indexes after a DML. When to Create an Index
D D D D

The column is used frequently in the WHERE clause or in a join condition. The column contains a wide range of values. The column contains a large number of null values. Two or more columns are frequently used together in a WHERE clause or join condition. The table is large and most queries are expected to retrieve less than 2–4% of the rows.

D

Remember that if you want to enforce uniqueness, you should define a unique constraint in the table definition. Then, a unique index is automatically created. When to Not Create an Index
D D D D

The table is small. The columns are not often used as a condition in the query. Most queries are expected to retrieve more than 2–4% of the rows. The table is updated frequently.

Creating Indexes

15 15

15 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Confirming Indexes
Confirm the existence of indexes from the USER_INDEXES data dictionary view. You can also check the columns involved in an index by querying the USER_IND_COLUMNS view. Example Display all previously created indexes, affected column names, and uniqueness on the S_EMP table. SQL> 2 3 4 5 SELECT FROM WHERE AND ic.index_name, ic.column_name, ic.column_position col_pos, ix.uniqueness user_indexes ix, user_ind_columns ic ic.index_name = ix.index_name ic.table_name = ’S_EMP’;

INDEX_NAME –––––––––––––––––––– S_EMP_ID_PK S_EMP_LAST_NAME_IDX S_EMP_USERID_UK

COLUMN_NAME ––––––––––– ID LAST_NAME USERID

COL_POS –––––––– 1 1 1

UNIQUENESS –––––––––– UNIQUE NONUNIQUE UNIQUE

Creating Indexes

15 17

15 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Removing an Index
You cannot modify indexes. To change an index, you must drop it and then re-create it. Remove an index definition from the data dictionary by issuing the DROP INDEX command. In order to drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege. Syntax DROP INDEX where: index index; is the name of the index.

Creating Indexes

15 19

15 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Indexes are used to improve the query retrieval speed. They are database objects and therefore take up disk space. Indexes use the B*tree search method to retrieve the pointer to the rows in the tables. Unique indexes for the PRIMARY KEY and UNIQUE KEY constraints in a table definition are created automatically. Users can create non-unique indexes to speed up searches by using the CREATE INDEX command. Indexes are maintained automatically by the Oracle7 Server. Users can view the definitions of the indexes in the USER_INDEXES data dictionary view. An index can be dropped by the creator or a user with the DROP ANY INDEX privilege by using the DROP INDEX command.

Creating Indexes

15 21

15 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
In this practice you will create an index on the WORKER table. Practice Contents
D D D

Creating non-unique indexes Displaying data dictionary information about the index Dropping indexes

Creating Indexes

15 23

15 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 15
1.

Would any indexes specified be used with the following queries and why?
a.

Non-unique index on LAST_NAME. Yes/No

SQL> SELECT 2 FROM 3 WHERE
b.

* s_emp last_name = ’Biri’;

Unique index on ID and non-unique index on CUSTOMER_ID. Yes/No

SQL> SELECT 2 FROM 3 WHERE
c.

id, customer_id, total s_ord date_ordered = ’31-AUG-92’;

Unique index on S_DEPT.ID and non-unique index on S_EMP.DEPT_ID. Yes/No

SQL> SELECT 2 FROM 3 WHERE

e.last_name, d.name s_emp e, s_dept d e.dept_id = d.id;

Creating Indexes

15 25

Practice 15
2. 3. 4.

continued

Create a non-unique index on the foreign key column in the WORKER table. Since users will frequently query on the employee last name, create a non-unique index on that column in the WORKER table. Display the indexes and uniqueness that exist in the data dictionary for the WORKER and DEPARTMENT tables. Save the command into a script named p15q4.sql. Remove the primary key constraint on the WORKER table. Re-display the indexes and uniqueness that exist in the data dictionary for the WORKER and DEPARTMENT tables by executing the p15q4.sql script. What changes do you observe and why?

5. 6.

If you have time, complete the following exercises:
7.

Re-create the primary key constraint on the WORKER table. Confirm the constraint in the data dictionary by executing pl2q2.sql. Confirm the unique index in the data dictionary by executing pl5q4. Remove the index on the employee last name from the WORKER table.

8.

15 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

16
Controlling User Access

16 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
This lesson describes the Oracle7 Server decentralized security system. Using the commands covered in this lesson, you can control database access to specific objects and add new users with different levels of access privileges. You can provide alternative names for objects by using the CREATE SYNONYM command. At the end of this lesson, you should be able to
D D D D D D D

Explain the concept of the database security model. Describe system privileges. Set up and maintain database access by using roles. Identify object privileges. Change a password. Grant and revoke object privileges. Create synonyms for ease of table access.

Controlling User Access

16 3

Server

16 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

ÉÉ É

Overview
In a multiple-user environment, you want to maintain security of the database access and use. Oracle7 Server database security allows you to
D D D D

Control database access. Give access to specific objects in the database. Confirm given and received privileges with the Oracle data dictionary. Create synonyms for database objects.

Database security can be classified into two categories: system security and data security. System security covers access and use of the database at the system level, such as username and password, disk space allocated to users, and system operations allowed by the user. Database security covers access and use of the database objects and the actions that those users can have on the objects. Privileges Privileges are the right to execute particular SQL statements. The database administrator is a high level user with the ability to grant users access to the database and its objects. The users require system privileges to gain access to the database and object privileges to manipulate the content of the objects in the database. Users can also be given the privilege to grant additional privileges to other users or to roles, which are named groups of related privileges. Schema A schema is a collection of objects, such as tables, views, and sequences. The schema is owned by a database user and has the same name as that user. For more information, see Oracle7 Server Application Developer’s Guide, Release 7.3, “Establishing a Security Policy” section and Oracle7 Server Concepts Manual, “Database Security” topic.

Controlling User Access

16 5

16 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

System Privileges
There are more than eighty system privileges available for users and roles. System privileges are typically provided by the database administrator. Typical DBA Privileges System Privilege CREATE USER DROP USER DROP ANY TABLE BACKUP ANY TABLE Operations Authorized Allows grantee to create other Oracle users (a privilege required for a DBA role). Drops another user. Drops a table in any schema. Backs up any table in any schema with the export utility.

Creating a User The DBA creates a new Oracle7 Server user by allocating a number of system privileges to that user. These privileges in turn determine what the user can do at the database level. The DBA creates the user by executing the CREATE USER command. The user does not have any system privileges. Abridged Syntax CREATE USER user IDENTIFIED BY password; where: user password is the name of the user to be created. specifies that the user must log in with this password.

For more information, see Oracle7 Server SQL Reference, Release 7.3, “GRANT” (System Privileges and Roles) and “CREATE USER.”

Controlling User Access

16 7

16 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

System Privileges

continued

Now that the DBA has created a user, the DBA can assign privileges to that user. Typical User Privileges System Privilege CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE Operations Authorized Connect to the database. Create tables in the user’s schema. Create a sequence in the user’s schema. Create a view in the user’s schema. Create a stored procedure, function, or package in the user’s schema.

Granting System Privileges The DBA uses the GRANT command to allocate system privileges to the user. Once the user has been granted the privileges, the user can immediately use those privileges. Syntax GRANT privilege [, privilege...] TO user [, user...]; where: privilege user Note: The above syntax is abridged. is the system privilege to be granted. is the name of the user.

Controlling User Access

16 9

16 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

What Is a Role?
A role is a named group of related privileges that can be granted to the user. This method makes granting and revoking privileges easier to perform and maintain. A user can have access to several roles, and several users can be assigned the same role. Roles typically are created for a database application. Creating and Assigning a Role First, the DBA must create the role. Then, the DBA can assign privileges to the role and users to the role. Syntax CREATE ROLE role; where: role is the name of the role to be created.

Now that the role is created, the DBA can use the GRANT command to assign users to the role as well as assign privileges to the role. Example Allow the managers to create tables and views. Give these privileges to Velasquez and to Ropeburn. SQL> CREATE ROLE manager; Role created. SQL> GRANT create table, create view TO manager; Grant succeeded. SQL> GRANT manager TO cvelasqu, aropebur; Grant succeeded.

Controlling User Access

16 11

16 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Changing Your Password
Every user has a password that is initialized by the DBA when the user is created. You can change your password by using the ALTER USER command. Syntax ALTER USER user IDENTIFIED BY password; where: user password is the name of the user. specifies the new password.

Note: Although this command can be used to change your password, there are many other options. You must have the ALTER USER privilege to change any other option. For more information, see Oracle7 Server SQL Reference, Release 7.3, “ALTER USER.”

Controlling User Access

16 13

16 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Granting Object Privileges
The DBA can allow users to perform a particular action on a specific table, view, sequence, or stored procedure by granting them object privileges. The object privileges vary from object to object. The table on the facing page outlines the privileges. An object owner has all privileges on the object. To give another user access to your database objects, execute the GRANT command. Syntax GRANT {object_priv(, object_priv...)|ALL}[(columns)] ON object TO {user[, user...]|role|PUBLIC} [WITH GRANT OPTION]; where: object_priv ALL columns ON object TO PUBLIC is an object privilege to be granted. all object privileges. specifies the column from a table or view on which privileges are granted. is the object on which the privileges are granted. identifies to whom the privilege is granted. grants object privileges to all users.

WITH GRANT OPTION allows the grantee to grant the object privileges to other users and roles. Note: A procedure refers to standalone procedures and functions, and public package constructs. The INDEX and REFERENCES privileges cannot be granted to a role. For more information, see Oracle7 Server SQL Reference, Release 7.3, “GRANT.”

Controlling User Access

16 15

16 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Granting Object Privileges
Guidelines
D

continued

To grant privileges on an object, the object must be in your own schema or you must have been granted the object privileges WITH GRANT OPTION. An object owner can grant any object privilege on the object to any other user or role of the database. The owner of an object automatically acquires all object privileges on that object.

D

D

Examples Grant users Sue and Rich the privilege to query your S_EMP table. SQL> GRANT 2 ON 3 TO select s_emp sue, rich;

Grant succeeded. Grant UPDATE privileges on specific columns in the S_DEPT table to Scott and to the manager role. SQL> GRANT 2 ON 3 TO update (name, region_id) s_dept scott, manager;

Grant succeeded.

Controlling User Access

16 17

16 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Granting Object Privileges
The WITH GRANT OPTION Keyword

continued

A privilege that is granted WITH GRANT OPTION can be passed on to other users and roles by the grantee. Object privileges granted WITH GRANT OPTION are revoked when the grantor’s privilege is revoked. Example As user Alice, allow user Scott to access your S_DEPT table with the privileges to query the table and add rows to the table. Allow Scott to give others these privileges. SQL> 2 3 4 GRANT select, insert ON s_dept TO scott WITH GRANT OPTION;

Grant succeeded.

The PUBLIC Keyword An owner of a table can grant access to all users by using the PUBLIC keyword. Example As user Scott, allow all users on the system to query data from Alice’s S_DEPT table. SQL> GRANT 2 ON 3 TO select alice.s_dept PUBLIC;

Grant succeeded.

Controlling User Access

16 19

16 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Confirming Privileges Granted
If you attempt to perform an unauthorized operation, for example, deleting a row from a table for which you do not have the DELETE privilege, the Oracle7 Server will not permit the operation to take place. If you receive the Oracle7 Server error message “table or view does not exist,” you have done either of the following:
D D

Named a table or view that does not exist Attempted to perform an operation on a table or view for which you do not have the appropriate privilege

What Privileges Do You Have? You can access the data dictionary to view the privileges you have. Data Dictionary Table ROLE_SYS_PRIVS ROLE_TAB_PRIVS USER_ROLE_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_COL_PRIVS_MADE USER_COL_PRIVS_RECD Description System privileges granted to roles. Table privileges granted to roles. Roles accessible by the user. Object privileges granted on the user’s objects. Object privileges granted to the user. Object privileges granted on the columns of the user’s objects. Object privileges granted to the user on specific columns.

Controlling User Access

16 21

16 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Revoking Object Privileges
Remove privileges granted to other users by using the REVOKE command. When you use the REVOKE command, the privileges you specify are revoked from the users you name, and from any other users to whom those privileges may have been granted. Syntax REVOKE {privilege [, privilege...] | ALL} ON object FROM {user[, user...]|role|PUBLIC} [CASCADE CONSTRAINTS] where: CASCADE CONSTRAINTS are required to remove any referential integrity constraints made to the object by means of the REFERENCES privilege.

SQL> REVOKE 2 ON 3 FROM

select, insert s_dept scott;

Revoke succeeded. For more information, see Oracle7 Server SQL Reference, Release 7.3, “REVOKE.”

Controlling User Access

16 23

16 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Synonym for an Object
To refer to a table owned by another user, you need to prefix the table name with the name of the user who created it followed by a period. Creating a synonym eliminates the need to qualify the object name with the schema, and provides you with an alternative name for a table, view, sequence, procedure, or other objects. This method can be especially useful with lengthy object names, such as views. Syntax CREATE [PUBLIC] SYNONYM synonym FOR object; where: PUBLIC synonym object Guidelines
D D

creates a synonym accessible to all users. is the name of the synonym to be created. identifies the object for which the synonym is created.

The object cannot be contained in a package. A private synonym name must be distinct from all other objects owned by the same user.

Example As user Scott, create a private synonym named S_DEPT for Alice’s S_DEPT table. SQL> CREATE SYNONYM 2 FOR Synonym created. For more information, see Oracle7 Server SQL Reference, Release 7.3, “CREATE SYNONYM.” s_dept alice.s_dept;

Controlling User Access

16 25

16 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Synonym for an Object
Examples Create a synonym for the DEPT_SUM_VU for quicker reference. SQL> CREATE SYNONYM 2 FOR Synonym created. The DBA can create a public synonym accessible to all users. SQL> CREATE PUBLIC SYNONYM 2 FOR Synonym created. s_dept alice.s_dept; d_sum dept_sum_vu;

continued

Remove a Synonym To drop a synonym, use the DROP SYNONYM command. Only the DBA can drop a public synonym. Example SQL> DROP SYNONYM Synonym dropped. For more information, see Oracle7 Server SQL Reference, Release 7.3, “DROP SYNONYM.” s_dept;

Controlling User Access

16 27

16 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
DBAs establish initial database security for users by assigning privileges to the users.
D

The DBA creates users who must have a password. The DBA is also responsible for establishing the initial system privileges for a user. Once the user has created an object, the user can pass along any of the available object privileges to other users or to all users by using the GRANT command. A DBA can create roles by using the CREATE ROLE command to pass along a collection of system or object privileges to multiple users. Roles make granting and revoking privileges easier to maintain. Users can change their password by using the ALTER USER command. You can remove privileges from users by using the REVOKE command. DBAs can create public synonyms, and users can create private synonyms for convenience by using the CREATE SYNONYM command. They permit short names or alternative names for objects. Remove synonyms by using the DROP SYNONYM command. Data dictionary views allow users to view the privileges granted to them and that are granted on their objects.

D

D

D D D

D

Controlling User Access

16 29

16 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
Team up with other students for this exercise of controlling database object access. Practice Contents
D D D D

Granting other users privileges to your table Modifying another user’s table through the privileges granted to you Creating a synonym Querying the data dictionary views related to privileges

Controlling User Access

16 31

16 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 16
1.

What privilege should a user be given to log in to the Oracle7 Server? Is this privilege a system or object privilege?

2.

What privilege should a user be given to create tables?

3.

If you create a table, who can pass along privileges to other users on your table?

4.

You are the DBA. You are creating many users who require the same system privileges. What would you use to make your job easier?

5.

What command do you use to change your password?

6. 7. 8.

Grant other users query access to your S_REGION table. Have them grant you query access to their S_REGION table. Query all the rows in your S_REGION table. Add a new row to your S_REGION table. Team 1 should add Central America as region number 6. Team 2 should add Micronesia as region number 7. Make the changes permanent. Query the other team’s S_REGION table. Create a synonym for the other team’s S_REGION table. Display the other team’s S_REGION table contents by using your synonym. Confirm the privileges for your team’s tables. Revoke the SELECT privilege from the other team. Attempt to SELECT from the other team’s S_REGION table. Drop the synonym you created.

9. 10. 11. 12. 13. 14. 15.

Controlling User Access

16 33

16 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

17
Summary of SQL and SQL*Plus

Foreign Key Table

Row Column

Primary Key

17 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary of SQL and SQL*Plus
The SQL and SQL*Plus module of the Introduction to Oracle course covered relational database concepts, the SQL command language, and SQL*Plus commands to execute and format SQL commands. Database Terminology Concept Table Row Description A table is the basic storage structure of an RDBMS, consisting of one or more columns and zero or more rows. A row is a combination of column values in a table; for example, the information about one department in the table S_DEPT. A row is sometimes called a “record.” A column represents one kind of data in a table; for example, the department name in the example table S_DEPT. It is described with a column name and holds data of a specific type and size. At the intersection of a row and a column, you find a field. The field can contain data. If there is no data in the field, it is said to contain a null value. A primary key is the column or set of columns that uniquely identifies each row in a table; for example a department number. It must contain a value. A foreign key is a column or set of columns that refers to a primary key in the same table or in another table. You create them to enforce relational database design rules.

Column

Field

Primary key

Foreign key

Summary of SQL and SQL*Plus

17 3

17 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary of SQL and SQL*Plus

continued

Structured Query Language, SQL*Plus, and PL/SQL commands are used to access and manipulate data stored in an Oracle database. SQL*Plus, SQL, and PL/SQL Language or Tool SQL Description A command language for communication with the Oracle7 Server from any tool or application. Oracle SQL contains many extensions. An Oracle tool that recognizes and executes SQL and PL/SQL statements and contains its own command language. An Oracle procedural language for writing application logic and manipulating data outside the database.

SQL*Plus

PL/SQL SQL Commands

There are many commands available in SQL. The table below describes the commands covered in this course. Command SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Description Retrieves data from the database. Most commonly used command. Enters new rows, changes existing rows, and removes unwanted rows from tables in the database, respectively. Collectively known as Data Manipulation Language (DML) commands. Sets up, changes, and removes data structures from tables. Collectively known as Data Definition Language (DDL) commands.

Manage the changes made by DML statements. Changes to the data can be grouped together into logical transactions. Gives or removes access rights to both the Oracle database and the structures within it. Collectively known as Data Control Language (DCL) commands.

Summary of SQL and SQL*Plus

17 5

17 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary of SQL and SQL*Plus
Oracle Data Dictionary

continued

The data dictionary is a set of tables that the user can access through views. The data dictionary holds all the data about the database. Whenever the database is in operation, the data dictionary is updated and maintained by the Oracle7 Server. Write a SELECT statement to view the contents of the data dictionary views. The following are some frequently accessed data dictionary tables:
D D D D D

DICTIONARY USER_OBJECTS OBJ (alias for USER_OBJECTS) USER_CONSTRAINTS USER_SEQUENCES

SQL*Plus Commands SQL*Plus commands may be divided into the following main categories: Category Environment Format File manipulation Execution Edit Interaction Purpose Affects the general behavior of SQL statements for the session. Formats query results. Saves, loads, and runs script files. Sends SQL or PL/SQL commands from SQL buffer to Oracle7 Server. Modifies SQL commands in the buffer. Allows users to create and pass variables to SQL statements, print variable values, and print messages to the screen. Various commands to connect to the database, manipulate the SQL*Plus environment, and display column definitions.

Miscellaneous

Summary of SQL and SQL*Plus

17 7

17 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
This practice has you build a set of database tables for a video application. Once you create the tables, you will insert, update, and delete records in a video store database, and generate a report. The database contains only the essential tables. Practice Contents
D D D D D D

Creating tables and sequences based on a database design Modifying data in the tables Modifying a table definition Creating a view Writing scripts containing SQL and SQL*Plus commands Generating a simple report

Note: If you want to build the tables, you can execute the buildtab.sql script in SQL*Plus. If you want to drop the tables, you can execute the dropvid.sql script in SQL*Plus. Then, you can execute the buildvid.sql script in SQL*Plus to create and populate the tables.

Summary of SQL and SQL*Plus

17 9

17 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17
1.

Create the tables based on the entity relationship diagram on the previous page and the table instance charts below. Choose the appropriate datatypes and be sure to add the integrity constraints.
a.

Table name: MEMBER
MEMBER_ ID PK NN, U NN NN System date number 10 char 25 char 25 char 100 char 30 char 15 date LAST_ FIRST_ NAME NAME

Column Name Key Type Null/ Unique Default Value Datatype Length b.

ADDRESS CITY

PHONE

JOIN_DATE

Table name: TITLE

Note: Do not create the PRICE column while creating the TITLE table. You would be modifying the TITLE table, in Exercise 7, to add the PRICE column.
Column Name Key Type Null/ Unique Check TITLE_ ID PK NN, U NN NN G, PG, R, NC17, NR DRAMA, COMEDY, ACTION, CHILD, SCIFI, DOCUMENTA RY DRAMA number 10 char 60 char 400 char 4 char 20 date DESCRIP– TION RELEASE_ DATE

TITLE

RATING

CATEGORY

Default Value Datatype Length

Summary of SQL and SQL*Plus

17 11

Practice 17
1.—continued c.

continued

Table name: TITLE_COPY

Column Name Key Type Null/ Unique Check FK Ref Table FK Ref Col Datatype Length d.

COPY_ID PK NN, U

TITLE_ID PK, FK NN, U

STATUS

NN AVAILABLE, DESTROYED, RENTED, RESERVED

title title_id number 10 number 10 char 15

Table name: RENTAL
BOOK_ DATE PK NN,U System date member member_id date number 10 title_copy copy_id number 10 date date MEMBER_ ID FK NN ACT_RET_ DATE EXP_RET_ DATE

Column Name Key Type Null/ Unique Default Value FK Ref Table FK Ref Col Datatype Length

COPY_ID PK, FK NN,U

TITLE_ID PK, FK NN,U

2 days after book date title_copy title_id number 10

17 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17
1.—continued e.

continued

Table name: RESERVATION
Column Name Key Type Null/Unique FK Ref Table FK Ref Col Datatype Length date RES_DATE PK NN,U MEMBER_ID PK, FK NN,U member member_id number 10 TITLE_ID PK, FK NN,U title title_id number 10

2. 3.

Verify that the tables and constraints were created properly by checking the data dictionary. Create sequences to uniquely identify each row in the MEMBER table and the TITLE table.
a. b. c.

Member number for the MEMBER table, start with 101, do not allow caching of the values. Title number for the TITLE table, start with 92, no caching. Verify the existence of the sequences in the data dictionary.

Summary of SQL and SQL*Plus

17 13

Practice 17
4.

continued

Add data to the tables. Create a script for each set of data to add.
a.

Add movie titles to the TITLE table. Write a script to enter the movie information. Save the script as p17q4a.sql. Use the sequence to uniquely identify each title. Remember that single quotation marks in a character field must be specially handled. Verify your additions. Description Rating Category CHILD Release date 05-OCT-95

Title Willie and Christmas Too Alien Again

All of Willie’s friends made a G Christmas list for Santa, but Willie has yet to add his own wish list. Yet another installment of science fiction history. Can the heroine save the planet from the alien life form? A meteor crashes near a small American town and unleashes carnivorous goo in this classic. With a little luck and a lot of ingenuity, a teenager skips school for a day in New York. A six-year-old has doubts about Santa Claus. But she discovers that miracles really do exist. After discovering a cache of drugs, a young couple find themselves pitted against a vicious gang. R

SCIFI

19-MAY-95

The Glob

NR

SCIFI

12-AUG-95

My Day Off

PG

COMEDY

12-JUL-95

Miracles on Ice

PG

DRAMA

12-SEP-95

Soda Gang

NR

ACTION

01-JUN-95

17 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17
4.—continued b.

continued

Add data to the MEMBER table. Write a script named p17q4b.sql to prompt users for the information. Execute the script. Be sure to use the sequence to add the member numbers.

First name Carmen LaDoris Midori Mark Audry Molly

Last name Velasquez Ngao Nagayama

Address 283 King Street 5 Modrany 68 Via Centrale

City Seattle Bratislava Sao Paolo

Phone 206-899-6666 586-355-8882 254-852-5764 63-559-7777 41-559-87 418-542-9988

Join date 08-MAR-90 08-MAR-90 17-JUN-91 07-APR-90 18-JAN-91 18-JAN-91

Quick-To-See 6921 King Lagos Way Ropeburn Urguhart 86 Chu Street 3035 Laurier Blvd Hong Kong Quebec

Summary of SQL and SQL*Plus

17 15

Practice 17
4.—continued c.

continued

Add the following movie copies in the TITLE_COPY table: Copy number 1 1 2 1 1 2 3 Status Available Available Rented Available Available Available Rented Available Available

Title Willie and Christmas Too Alien Again The Glob My Day Off

Miracles on Ice Soda Gang
d.

1 1

Add the following rentals to the RENTAL table: Copy number 1 2 3 1 Date return Date returned Date rented expected 3 days ago 1 day ago 2 days ago 4 days ago 1 day ago 1 day from now Today 2 days ago 2 days ago 2 days ago

Title 92 93 95 97
5.

Customer 101 101 102 106

Create a view named TITLE_AVAIL to show the movie titles and the availability of each copy and its expected return date if rented. Query all rows from the view.

17 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17
6.

continued

Make changes to data in the tables.
a.

Add a new title. The movie is “Interstellar Wars”, which is rated PG, and classified as a SCIFI movie. The release date is 07-JUL-77. The description is “Futuristic interstellar action movie. Can the rebels save the humans from the evil Empire?” Be sure to add a title copy record for two copies. Enter two reservations. One reservation is for Carmen Velasquez who wants to rent “Interstellar Wars.” The other is for Mark Quick-To-See who wants to rent “Soda Gang”. Customer Carmen Velasquez rents the movie “Interstellar Wars”, copy 1. Remove her reservation for the movie. Record the information about the rental. Allow the default value for the expected return date to be used. Verify the rental was recorded by using the view you created. Add a PRICE column to the TITLE table to record the purchase price of the video. The column should have a total length of eight digits and two decimal places. Verify your modification. Create a script named p17q7b.sql to update each video with a price according to the following list: Price 25 35 35 35 98 35 29

b.

c.

7.

Make a modification to one of the tables.
a.

b.

Title Willie and Christmas Too Alien Again The Glob My Day Off Miracle on Ice Soda Gang Interstellar Wars
c. 8.

Ensure that in the future all titles will contain a price value. Verify the constraint.

Create a report titled Customer History Report. This report will contain each customer’s history of renting videos. Be sure to include the customer name, movie rented, dates of the rentals, and duration of rentals. Count up the total number of rentals for all customers for the reporting period. Save the script in a file named p17q8.sql.

Summary of SQL and SQL*Plus

17 17

17 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Sign up to vote on this title
UsefulNot useful