Professional Documents
Culture Documents
Edition 1.1
M03990
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.
All other products or company names are used for identification purposes only,
and may be trademarks of their respective owners.
Publishers
Stephanie Jones
Kimberly Lee
Jennifer Robertson
Mark Turangan
7
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 Create a SELECT statement that prompts the user to enter a value at runtime.
D Use the SQL*Plus ACCEPT command to define a variable.
D Define a variable that can be automatically picked up by the SELECT statement
at runtime.
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.
Notation Description
&user_variable 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.
ID LAST_NAME SALARY
---------- ------------------------- ----------
3 Nagayama 1400
11 Magee 1400
With the single ampersand, the user is prompted every time the command is executed.
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.
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.
ID TOTAL
---------- ----------
103 377
110 1539.13
111 2770
98 595
ID DATE_ORDE
---------- ---------
100 31-AUG-92
109 08-SEP-92
If you do not enter a value for the substitution variable, you will obtain an error when
you execute above command.
Command Description
DEFINE variable = value Creates a CHAR datatype user variable and assigns
a value to it.
DEFINE variable Displays the variable, its value, and its datatype.
DEFINE Displays all user variables with value and datatype.
ACCEPT (see syntax below) Reads a line of user input and stores it in a variable.
Abridged Syntax
where: variable is the name of the variable that stores the value.
If it does not exist, SQL*Plus creates it.
datatype 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.
FOR[MAT] specifies the format model, for example A10 or
9.999.
PROMPT text displays the text before the user can enter the
value.
HIDE suppresses what the user enters, for example a
password.
Note: Do not prefix the SQL*Plus substitution parameter with the ampersand (&)
when referencing the substitution parameter in the ACCEPT command.
Guidelines
D 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.
D When using the DEFINE command, use single quotation marks (‘ ’) to enclose a
string that contains an embedded space.
D Use the ACCEPT command to
D Give a customized prompt when accepting user input. Otherwise, you will see
the default “Enter value for variable.”
D Explicitly define a NUMBER or DATE datatype variable.
D Hide user input for security reasons.
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.
Example
Create a variable to hold the department position. Display all department names that
match the position in the variable.
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.
Guidelines
D You can use the DEFINE command to associate meaningful names with
parameters.
D A prefix can be used to differentiate column names (no prefix), simple variables
(for example, v_test), and parameterized variables (for example, p_name).
D 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.
D Reports can accept a maximum of nine parameters that are named from &1 to &9.
D SQL*Plus retains report parameters and their values until you redefine them,
undefine them, or terminate your SQL*Plus session.
Practice Contents
D Creating a query to display values using substitution variables
D Starting a command file containing substitution variables
D Using the ACCEPT command
4. 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.
ID CUSTOMER NAME
------ ----------------------------------------
201 Unisports
203 Delhi Sports
204 Womansport
205 Kam’s Sporting Goods
206 Sportique
207 Sweet Rock Sports
208 Muench Sports
211 Kuhn’s Sports
212 Hamada Sport
213 Big John’s Sports Emporium
215 Sporta Russia
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 Describe the stages of system development.
D List and define basic types of data relationships.
D Define a relational database and its components.
D Read an entity relationship model.
D Translate an entity relationship model into a relational 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.
Stages of Development
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.
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.
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.
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.
ÉÉ ÉÉ
ÉÉ ÉÉ
Purpose of Models
Models help communicate the concepts in people’s minds. They can be used for the
following purposes:
D Communicate
D Categorize
D Describe
D Specify
D Investigate
D Evolve
D Analyze
D 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.
Key Components
Component Description
Entity A thing of significance about which information needs to
be known.
Attribute Something that describes or qualifies an entity.
Relationship A named association between entities showing optionality
or degree.
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 Soft box with any dimensions
D Singular, unique entity name
D Entity name in uppercase
D 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 Use singular names in lowercase.
D Tag mandatory attributes, or values that must be known, with an asterisk “*”.
D 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 Tag each attribute that is part of the UID with a number symbol (#).
D Tag secondary UIDs with a number sign in parentheses (#).
Relationships
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 A name, for example, taught by or assigned to.
D An optionality, either must be or may be.
D 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.
Symbol Description
Dashed line Optional element indicating “may be.”
Solid line Mandatory element indicating “must be.”
Crow’s foot Degree element indicating “one or more.”
Single line Degree element indicating “one and only one.”
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.
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 Description
One-to-one 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.
Many-to-one Degree of one or more in one direction and a degree of one
and only one in the other direction. Very common.
Many-to-many Degree of one or more in both directions. Very common.
Resolve them with an intersection entity.
Normalization
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 Minimizes data redundancy
D Reduces integrity problems
D Identifies missing entities, relationships, and tables
Normalization Rules
Rule Description
First normal form (1NF) All attributes must be single-valued and not
repeating.
Second normal form (2NF) An attribute must depend upon its entity’s entire
unique identifier.
Third normal form (3NF) No non-UID attribute can be dependent upon
another non-UID attribute.
Primary Keys
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.
Foreign Keys
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
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.
D 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.
D Plan the physical storage space, which is the amount of space required to store the
data of a table in the database.
D Redefine integrity constraints.
For more information, see
Develop Complex Data Models and Design Databases course description.
2
3
4 Map relationships to
foreign keys
Symbol Definition
PK Primary key column
FK Foreign key column
FK1, FK2 Two foreign keys within the same table
FK1, FK1 Two columns within the same composite foreign key
NN Not null column
U Unique column
U1, U1 Two columns that are unique in combination
Guidelines
D 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.
D Column names should be easily traced to the entity relationship model. Short
column names will reduce the time required for SQL command parsing.
D You should develop your own naming conventions and standards.
ITEM ORDER
in
#* id #* id
o price o date ordered
o quantity made o date shipped
o quantity shipped up of o payment type
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.
PET PEN
#* id assigned
to #* id
o name o location
o date of birth o size
o weight the
* species temporary
home for
PET PEN
assigned
#* id to #* id
o name o location
o date of birth the o size
o weight temporary
* species home for
Stages of Development
D Study and analyze the business requirements.
D Build models of the system.
D Design the database.
D Build the prototype system.
D Write the user documentation.
D Refine the prototype.
D Roll out the system to the users.
Database Design
D Create a table instance chart.
D Map all entity relationship model components to the chart.
D Add other supporting information and objects.
Creating Tables
9Ć2 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 Create a table containing integrity constraints.
D Identify table naming conventions.
D Describe the datatypes that can be used when specifying column definitions.
D Recognize the indexes that are created automatically by constraints.
D Create a table by populating it with rows from another table.
Data Structures
Structure Description
Table Stores data.
View Logically represents subsets of data from one or more tables.
Sequence Generates primary key values.
Index Improves the performance of some queries.
Abridged Syntax
Naming Rules
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.
D Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $ and #
(legal characters, but their use is discouraged).
D Names must not duplicate the name of another object owned by the same Oracle7
Server user.
D Names must not be an Oracle7 Server reserved words.
Naming Guidelines
D Use descriptive names for tables and other database objects.
D 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.”
Datatype Description
VARCHAR2(size) Variable length character values up to maximum length
size. Minimum length is 1, maximum length is 2000.
CHAR(size) Fixed length character values of length size. Default
length is 1, maximum length is 255.
NUMBER Floating point number with precision of 38 significant
digits.
NUMBER(p,s) 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 Date and time values between January 1, 4712 B.C.
and December 31, 4712 A.D.
LONG Variable length character values up to 2 gigabytes.
Only one LONG column is allowed per table.
RAW and LONG RAW 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.
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.”
Constraint Description
NOT NULL Specifies that this column may not contain a null value.
UNIQUE Specifies a column or combination of columns whose
values must be unique for all rows in the table.
PRIMARY KEY Uniquely identifies each row of the table.
FOREIGN KEY Establishes and enforces a foreign key relationship
between the column and a column of the referenced
table.
CHECK Specifies a condition that must be true.
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.
SyntaxĊColumnĆConstraint Level
SyntaxĊTableĆConstraint Level
column,
[CONSTRAINT constraint_name] constraint_type
(column, ...),
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.
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.
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
Create a Table
1. Create a script file. Start the CREATE TABLE syntax and specify the table name.
2. Map the column names, datatypes, and lengths from the table instance chart to the
script file. Separate each column definition with a comma (,).
3. Map the NOT NULL constraints, except for the PRIMARY KEY constraint
columns, as column constraint.
4. 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.
5. Map the UNIQUE, CHECK, and FOREIGN KEY constraints.
6. Save and execute the script file.
Example
Create the S_DEPT database table based on the table instance chart.
Example
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.
Key Type PK FK
Nulls/ NN, U NN NN, U
Unique
FK Table S_DEPT
FK ID
Column
Datatype NUM CHAR CHAR DATE NUM NUM
Length 7 25 8 6 7
Note: The above table displays a subset of columns found in the S_EMP table.
Constraint Description
S_EMP_ID_PK 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 Ensures that there is a value in the USERID column.
S_EMP_USERID_UK Ensures that each value in the USERID column is
unique.
S_EMP_DEPT_ID_FK Ensures that the S_EMP table does not contain
department number not already stored in the S_DEPT
table.
S_EMP_COMMISSION_ Restricts commission percentages.
PCT_CK
Syntax
Guidelines
D The table will be created with the specified column names, and the rows retrieved
by the SELECT statement will be inserted into the table.
D The column definition can contain only the column name, default value, and
integrity constraints, not the datatype or referential integrity constraint.
D If column specifications are given, the number of columns must equal the number
of columns in the subquery SELECT list.
D If no column specifications are given, the column names of the table are the same
as the column names in the subquery.
D Only the NOT NULL constraint is inherited from the subquery table to
corresponding columns in the new table.
Example
Confirm the creation of the S_EMP table.
Note: Only the NOT NULL constraint is identified in the DESCRIBE command. All
constraints can be viewed in the data dictionary.
Table Features
D Table name
D Column names, datatypes, and lengths
D Integrity constraints
UNIQUE indexes are created automatically when you create PRIMARY KEY and
UNIQUE constraints.
Constraint Types
D NOT NULL
D UNIQUE
D PRIMARY KEY
D FOREIGN KEY
D CHECK
DESCRIBE Command
Review the structure of a table using the SQL*Plus DESCRIBE command.
Practice Contents
D Creating new tables containing constraints
D Verifying that the tables exist
a. Correct/Incorrect
b. Correct/Incorrect
2. 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.
3. 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.
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 Describe the data dictionary views a user may access.
D Query data from the data dictionary.
Tables Description
User tables Collection of tables created and maintained by the user,
such as S_EMP, that contain user information.
Data dictionary Collection of tables created and maintained by the Oracle7
Server, such as USER_OBJECTS, that contain information
about the database.
View Classes
Data dictionary view names reflect their intended use. There are four categories of
views; each category has a distinct prefix.
Prefix Description
USER_ 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.
ALL_ Accesses objects to which the user has been granted access rights, in
addition to objects owned by the user.
DBA_ Allows users with the DBA privilege to access any object in the
database.
V$ Displays database server performance and locking. Initially available
only to the DBA.
Additional Views
Several data dictionary views do not use the prefixes listed above. These include
synonyms for views with long names.
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.
Example
To view a description of each column in data dictionary tables and views, query the
DICT_COLUMNS view.
Example
Display the types of objects that the user owns.
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.
SQL> SELECT *
2 FROM dictionary
3 WHERE 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
Example
Confirm the constraints on the S_EMP table.
8 rows selected.
Note: The above display has been formatted to fit the page.
Example
Display the column constraint information in the data dictionary for the S_EMP table.
CONSTRAINT_NAME COLUMN_NAME
----------------------- -----------------------
S_EMP_COMMISSION_PCT_CK COMMISSION_PCT
S_EMP_DEPT_ID_FK DEPT_ID
S_EMP_ID_PK ID
S_EMP_LAST_NAME_NN LAST_NAME
S_EMP_MANAGER_ID_FK MANAGER_ID
S_EMP_TITLE_FK TITLE
S_EMP_USERID_NN USERID
S_EMP_USERID_UK USERID
8 rows selected.
Practice Contents
D Querying the data dictionary to view table information
D Viewing constraint information from the data dictionary
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. Query the USER_OBJECTS data dictionary to see information about the tables
you created in Practice 9, DEPARTMENT and EMPLOYEE tables.
4. 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.
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 Insert new rows into a table.
D Update existing rows in a table.
D Delete rows from a table.
D Explain transaction controls and their importance.
Syntax
Enclose character and date values within single quotation marks; do not enclose
numeric values within single quotation marks.
Method Description
Implicit Omit the column from the column list.
Explicit Specify the NULL keyword in the VALUES list.
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.
Example
Alternatively, you can enter a null value into a row explicitly by using the NULL
keyword for the value.
Be sure that the targeted column allows null values by verifying the Null? status from
the SQL*Plus DESCRIBE command.
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.
Example
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.
If the RR format is set, the century may not be the current one.
Example
Record information for a department in the S_DEPT table. Prompt the user for the
department number, department name, and region number.
1 row created.
For date and character values, the ampersand and the variable name are enclosed in
single quotation marks.
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.
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.
Syntax
Example
Copy selected rows from the S_EMP table into the HISTORY table.
The number of columns in the column list of the INSERT clause must match the
number of values in the subquery.
Syntax
UPDATE table
SET column = value [, column = value...]
[WHERE condition];
Example
Transfer employee number 2 to department 10. Transfer employee number 1 to
department 32 and change the employee’s salary to 2550.
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.
ID COMMISSION_PCT
------- --------------
1 10
2 10
3 10
4 10
5 10
6 10
...
25 rows selected.
Example
If the value you specify does not exist in the parent table, then you receive the “parent
key” violation ORA-02291.
Syntax
Example
Remove all information about employees who started after January 1, 1996.
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> SELECT *
2 FROM test;
no rows selected
Example
Attempt to delete all departments in region number 1.
If the parent record you attempt to delete has child records, then you receive the
“child record found” violation ORA-02292.
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) Consist of only one DDL statement.
Data control (DCL) Consists of only one DCL statement.
Command Description
COMMIT Ends the current transaction by making all pending
data changes permanent.
SAVEPOINT name Marks a savepoint within the current transaction.
ROLLBACK [TO Ends the current transaction by discarding all pending
SAVEPOINT name] data changes.
Status Circumstance
Automatic commit 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.
Make all pending changes permanent by using the COMMIT command. Following a
COMMIT
D Data changes are written to the database.
D The previous state of the data is permanently lost.
D All users can view the results of the transaction.
D The locks on the affected rows are released; the rows are now available for other
users to perform new data changes.
D All savepoints are erased.
Example
Create a new Education department with at least one employee. Make the data change
permanent.
SQL> COMMIT;
Commit complete.
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> ROLLBACK;
Rollback complete.
SQL> SELECT *
2 FROM test
3 WHERE id = 100;
no rows selected
SQL> COMMIT;
Commit complete.
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.
If you create a second savepoint with the same name as an earlier savepoint, the
earlier savepoint is deleted.
Command Description
INSERT Adds a new row to the table.
UPDATE Modifies existing rows in the table.
DELETE Removes existing rows from the table.
COMMIT Makes all pending data changes permanent.
SAVEPOINT Allows a rollback to that savepoint marker.
ROLLBACK Discards all pending data changes.
Practice Contents
D Inserting rows into the tables
D Updating and deleting rows in the tables
D Controlling transactions
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 Add and modify table columns.
D Add, enable, disable, or remove constraints.
D Drop a table.
D Remove all rows leaving the table definition intact.
D Change object names.
D Add comments to objects and view comments from the data dictionary.
Syntax
Guidelines
D You can add or modify columns, but you cannot drop them from a table.
D You cannot specify where the column is to appear. The new column becomes the
last column.
Syntax
Guidelines
D Increase the width or precision of a numeric column.
D Decrease the width of a column if the column contains only null values or if the
table has no rows.
D Change the datatype if the column contains null values.
D 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.
D A change to the default value of a column only affects subsequent insertions to
the table.
D Add a NOT NULL constraint only if there are no null values in the column.
Syntax
Guidelines
D You can add, drop, enable, or disable a constraint, but you cannot modify its
structure.
D You can add a NOT NULL constraint to an existing column by using the
MODIFY clause of the ALTER TABLE command.
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
Syntax
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.
D If you enable a UNIQUE or PRIMARY KEY constraint, a UNIQUE or
PRIMARY KEY index is automatically created.
D You can use the ENABLE and DISABLE clauses in both the CREATE TABLE
command and the ALTER TABLE command.
D The CASCADE clause disables dependent integrity constraints.
Syntax
Guidelines
D All data is deleted from the table.
D Any views, synonyms, stored procedures, functions, or packages will remain, but
are invalid.
D Any pending transactions are committed.
D Only the creator of the table or a user with the DROP ANY TABLE privilege can
remove a table.
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.
SyntaxĊRENAME Command
SyntaxĊTRUNCATE Command
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.
Syntax
Examples
Add a comment on the S_EMP table.
CREATE TABLE
D You can create a table and the indicated constraints.
D Create a table based on another table by using a subquery.
ALTER TABLE
D Modify table structures and constraints.
D Change column widths, change column datatypes, add columns, add or drop
constraints, and enable or disable constraints.
DROP TABLE
D Remove rows and a table structure.
D Once executed, this command cannot be rolled back.
RENAME
D Rename a table, view, sequence, or synonym.
TRUNCATE
D Remove all rows from a table and release the storage space used by the table.
D DELETE command only removes rows.
COMMENT
D Add a comment to a table or a column.
D Query the data dictionary to view the comment.
Practice Contents
D Creating a new table by using the CREATE TABLE AS syntax
D Adding constraints
D Modifying column definitions
D Dropping tables
D Adding a comment to a table
D Displaying information in data dictionary views
3. Compare these constraints to those in the EMPLOYEE table. Note the types and
names of the constraints.
4. Add a table level PRIMARY KEY constraint to the WORKER table using the ID
column. The constraint should be immediately enabled.
5. 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.
6. 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.
7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.
If you have time, complete the following exercises.
8. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype,
length 30.
9. Add a comment to the WORKER and DEPARTMENT table definitions
describing the tables. Confirm your additions in the data dictionary.
TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information
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 Explain the use of sequences.
D Create a sequence.
D Use a sequence.
D Modify a sequence definition.
D Remove a sequence.
Abridged Syntax
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.
Do not use the CYCLE option if the sequence is used to generate primary key values.
Confirming Sequences
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.
9 rows selected.
Syntax
Guidelines
D You must own or you have the ALTER privilege for the sequence in order to
modify it.
D Only future sequence numbers are affected by the ALTER SEQUENCE
command.
D Some validation is performed. For example, a new MAXVALUE cannot be
imposed that is less than the current sequence number.
D 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.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “ALTER SEQUENCE.”
Syntax
Practice Contents
D Creating a sequence
D Modifying a sequence
D Using a sequence
9. Modify your department sequence to allow no maximum value. Verify the change
to the sequence by executing the p13q3.sql script.
10. Add the Research department by using your script named p13q4.sql. Make this
addition permanent.
11. Display the contents of the DEPARTMENT table and WORKER table.
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 Explain the concept of a view.
D Use data dictionary views.
D Create simple and complex views.
D Create a view with an option to enforce constraints.
D Modify a view.
D Remove a view.
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.
D 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.
D Provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
D Provide groups of users access to data according to their particular criteria.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “CREATE VIEW.”
Abridged Syntax
Guidelines
D The query that defines a view can contain complex SELECT syntax, including
joins, groups, and subqueries.
D The query that defines the view cannot contain an ORDER BY clause.
D If you do not specify a constraint name, the system will assign a default name in
the format SYS_Cn.
D 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.
There are two classifications for views: simple and complex. The basic difference is
related to the DML operations.
Example
Create a view containing the employee number, last name, and job title for employees
in department 45. Display the contents.
SQL> SELECT *
2 FROM empvu45;
ID LAST_NAME TITLE
------ ------------ ---------------------
10 Havel Warehouse Manager
24 Dancs Stock Clerk
25 Schwartz Stock Clerk
Control the column names by including column aliases within the subquery.
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.
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.
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.
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> SELECT *
2 FROM dept_sum_vu;
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.
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.
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.
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> SELECT *
2 FROM user_views;
Syntax
Advantages of Views
D Restrict database access
D Simplify queries
D Provide data independence
D Allow multiple views of the same data
D Remove views without affecting the underlying data
View Options
D Can be a simple view based on one table
D Can be a complex view based on more than one table, or contain groups or
functions
D Can be replaced if one of the same name exists
D Contain a check constraint
D Can be read-only
Practice Contents
D Creating a simple view
D Creating a complex view
D Creating a view with a check constraint
D Attempting to modify data in the view
D Displaying view definitions
D Removing views
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.
D Identify the uses for indexes.
D Explain the index structure and why it improves query speed.
D Create a non-unique index.
D Remove an index from the data dictionary.
D Evaluate guidelines for creating and using indexes.
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.
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.
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.
Index Types
Type Description
Unique Ensures that values in specified columns are
unique.
Non-unique Ensures fastest possible results when querying
data.
Single column Only one column exists in the index.
Concatenated or composite 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.
Abridged Syntax
Example
Create an index to improve the speed of query access on the LAST_NAME column
in the S_EMP table.
Example
Display all previously created indexes, affected column names, and uniqueness on the
S_EMP table.
Syntax
Practice Contents
D Creating non-unique indexes
D Displaying data dictionary information about the index
D Dropping indexes
SQL> SELECT *
2 FROM s_emp
3 WHERE last_name = ’Biri’;
2. Create a non-unique index on the foreign key column in the WORKER table.
3. Since users will frequently query on the employee last name, create a non-unique
index on that column in the WORKER table.
4. 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.
5. Remove the primary key constraint on the WORKER table.
6. 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?
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 Explain the concept of the database security model.
D Describe system privileges.
D Set up and maintain database access by using roles.
D Identify object privileges.
D Change a password.
D Grant and revoke object privileges.
D Create synonyms for ease of table access.
É ÉÉ
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.
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
Now that the DBA has created a user, the DBA can assign privileges to that user.
Syntax
Syntax
Example
Allow the managers to create tables and views. Give these privileges to Velasquez
and to Ropeburn.
Syntax
Syntax
Guidelines
D 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.
D An object owner can grant any object privilege on the object to any other user or
role of the database.
D The owner of an object automatically acquires all object privileges on that object.
Examples
Grant users Sue and Rich the privilege to query your S_EMP table.
Grant UPDATE privileges on specific columns in the S_DEPT table to Scott and to
the manager role.
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.
Example
As user Scott, allow all users on the system to query data from Alice’s S_DEPT table.
Syntax
Syntax
Guidelines
D The object cannot be contained in a package.
D 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.
Examples
Create a synonym for the DEPT_SUM_VU for quicker reference.
Remove a Synonym
To drop a synonym, use the DROP SYNONYM command. Only the DBA can drop a
public synonym.
Example
Practice Contents
D Granting other users privileges to your table
D Modifying another user’s table through the privileges granted to you
D Creating a synonym
D Querying the data dictionary views related to privileges
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?
6. Grant other users query access to your S_REGION table. Have them grant you
query access to their S_REGION table.
7. Query all the rows in your S_REGION table.
8. 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.
9. Query the other team’s S_REGION table.
10. Create a synonym for the other team’s S_REGION table.
11. Display the other team’s S_REGION table contents by using your synonym.
12. Confirm the privileges for your team’s tables.
13. Revoke the SELECT privilege from the other team.
14. Attempt to SELECT from the other team’s S_REGION table.
15. Drop the synonym you created.
Row
Column
Primary Key
Database Terminology
Concept Description
Table A table is the basic storage structure of an RDBMS, consisting
of one or more columns and zero or more rows.
Row 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.”
Column 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.
Field 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.
Primary key 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.
Foreign key 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.
Structured Query Language, SQL*Plus, and PL/SQL commands are used to access
and manipulate data stored in an Oracle database.
SQL Commands
There are many commands available in SQL. The table below describes the
commands covered in this course.
Command Description
SELECT Retrieves data from the database. Most commonly used
command.
INSERT Enters new rows, changes existing rows, and removes unwanted
UPDATE rows from tables in the database, respectively. Collectively
DELETE known as Data Manipulation Language (DML) commands.
CREATE Sets up, changes, and removes data structures from tables.
ALTER Collectively known as Data Definition Language (DDL)
DROP commands.
RENAME
TRUNCATE
COMMIT Manage the changes made by DML statements. Changes to the
ROLLBACK data can be grouped together into logical transactions.
SAVEPOINT
GRANT Gives or removes access rights to both the Oracle database and
REVOKE the structures within it. Collectively known as Data Control
Language (DCL) commands.
SQL*Plus Commands
SQL*Plus commands may be divided into the following main categories:
Category Purpose
Environment Affects the general behavior of SQL statements for the
session.
Format Formats query results.
File manipulation Saves, loads, and runs script files.
Execution Sends SQL or PL/SQL commands from SQL buffer to
Oracle7 Server.
Edit Modifies SQL commands in the buffer.
Interaction Allows users to create and pass variables to SQL
statements, print variable values, and print messages to
the screen.
Miscellaneous Various commands to connect to the database,
manipulate the SQL*Plus environment, and display
column definitions.
Practice Contents
D Creating tables and sequences based on a database design
D Modifying data in the tables
D Modifying a table definition
D Creating a view
D Writing scripts containing SQL and SQL*Plus commands
D 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.
Null/ NN, U NN NN
Unique
Default System date
Value
Datatype number char char char char char date
Length 10 25 25 100 30 15
1.—continued
c. Table name: TITLE_COPY
Column
Name COPY_ID TITLE_ID STATUS
Key Type PK PK, FK
Null/ NN, U NN, U NN
Unique
Check AVAILABLE, DESTROYED, RENTED,
RESERVED
FK Ref Table title
FK Ref Col title_id
Datatype number number char
Length 10 10 15
1.—continued
e. Table name: RESERVATION
2. Verify that the tables and constraints were created properly by checking the data
dictionary.
3. Create sequences to uniquely identify each row in the MEMBER table and the
TITLE table.
a. Member number for the MEMBER table, start with 101, do not allow caching
of the values.
b. Title number for the TITLE table, start with 92, no caching.
c. Verify the existence of the sequences in the data dictionary.
4. 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.
4.—continued
b. 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 Last name Address City Phone Join date
Carmen Velasquez 283 King Seattle 206-899-6666 08-MAR-90
Street
LaDoris Ngao 5 Bratislava 586-355-8882 08-MAR-90
Modrany
Midori Nagayama 68 Via Sao Paolo 254-852-5764 17-JUN-91
Centrale
Mark Quick-To-See 6921 King Lagos 63-559-7777 07-APR-90
Way
Audry Ropeburn 86 Chu Hong 41-559-87 18-JAN-91
Street Kong
Molly Urguhart 3035 Quebec 418-542-9988 18-JAN-91
Laurier
Blvd
4.—continued
c. Add the following movie copies in the TITLE_COPY table:
5. 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.
Title Price
Willie and Christmas Too 25
Alien Again 35
The Glob 35
My Day Off 35
Miracle on Ice 98
Soda Gang 35
Interstellar Wars 29
c. Ensure that in the future all titles will contain a price value. Verify the
constraint.
8. 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.