Download presentation
Presentation is loading. Please wait.
1
A Guide to SQL, Eighth Edition
Chapter One Introduction to Premiere Products, Henry Books, and Alexamara Marina Group A Guide to SQL, Eighth Edition
2
A Guide to SQL, Eighth Edition
Objectives Introduce Premiere Products, a company whose database is used as the basis for many of the examples throughout the text Introduce Henry Books, a company whose database is used as a case that runs throughout the text Introduce Alexamara Marina Group, a company whose database is used as an additional case that runs throughout the text A Guide to SQL, Eighth Edition
3
A Guide to SQL, Eighth Edition
What is a Database? Database: a structure containing categories of information and relationships between these categories Categories: sales reps, customers, orders, and parts Relationships between categories: sales rep- to-customer and customer-to-orders A Guide to SQL, Eighth Edition
4
The Premiere Products Database
Premiere Products is a distributor of appliances, housewares, and sporting goods Manual system no longer feasible for managing customer, order, and inventory data Database management system will allow for current, accurate data with useful reports A Guide to SQL, Eighth Edition
5
Required Data for Sales Reps
Number Last name First name Address Total commission Commission rate A Guide to SQL, Eighth Edition
6
Required Data for Customer
Customer number Name Address Current balance Credit limit Sales rep number A Guide to SQL, Eighth Edition
7
Required Data for Parts
Part number Description Number of units on hand Item class Number of the warehouse where the item is stored Unit price for each part in inventory A Guide to SQL, Eighth Edition
8
A Guide to SQL, Eighth Edition
9
Components of a Sample Order
Heading (top of the order form) Order number and date Customer number, name, address Sales rep number and name Body (center of the order form) One or more order lines or line items Footer (bottom of the order form) Order total A Guide to SQL, Eighth Edition
10
Components of a Line Item
Part number Part description Number of units for the part ordered Quoted price for the part Total, or extension, the result of multiplying the number ordered by the quoted price A Guide to SQL, Eighth Edition
11
Items Stored for Each Order
Order number Date of the order Customer number Customer name, address, and sales rep information are stored with the customer information Sales rep name is stored with sales rep information A Guide to SQL, Eighth Edition
12
Items Stored for Each Order (continued)
Order number, part number, number of units ordered Quoted price Part description is stored with information on parts Order total is not stored but is calculated each time order is displayed or printed A Guide to SQL, Eighth Edition
13
A Guide to SQL, Eighth Edition
Sample Rep Table A Guide to SQL, Eighth Edition
14
A Guide to SQL, Eighth Edition
Rep Table Example Three sales reps in the table identified by number Sales rep number: 20 Name: Valerie Kaiser Address: 624 Randall, Grove, FL, 33321 Total commission: $20,542.50 Commission rate: 5% (0.05) A Guide to SQL, Eighth Edition
15
A Guide to SQL, Eighth Edition
Sample Customer Table A Guide to SQL, Eighth Edition
16
Customer Table Example
Ten customers are identified by number Number: 148 Name: Al’s Appliance and Sport Address: 2837 Greenway, Fillmore, FL, 33336 Current balance: $6,550.00 Credit limit: $7,500.00 Sales rep: 20 (Valerie Kaiser) A Guide to SQL, Eighth Edition
17
A Guide to SQL, Eighth Edition
Sample Part Table A Guide to SQL, Eighth Edition
18
A Guide to SQL, Eighth Edition
Part Table Example Ten parts are listed by part number Part number: AT94 Description: Iron Units on hand: 50 Item class: HW (housewares) Warehouse: 3 Price: $24.95 A Guide to SQL, Eighth Edition
19
A Guide to SQL, Eighth Edition
Sample Orders Table A Guide to SQL, Eighth Edition
20
A Guide to SQL, Eighth Edition
Orders Table Example Seven orders listed by order number Order number: 21608 Order date: 10/20/2010 Customer: 148 (Al’s Appliance and Sport) A Guide to SQL, Eighth Edition
21
Sample Order_Line Table
A Guide to SQL, Eighth Edition
22
Order_Line Table Example
Nine order line items listed by order number Order number: 21608 Part number: AT94 (iron) Number ordered: 11 Quoted price: $21.95 A Guide to SQL, Eighth Edition
23
Alternative Orders Table Structure
A Guide to SQL, Eighth Edition
24
Alternative Order Table Example
Displays identical data in one table Each table row contains all of the order lines for each order Fifth row, order has two order lines Part BV06, Qty 2, Quoted price $ each Part CD52, Qty 4, Quoted price $ each A Guide to SQL, Eighth Edition
25
Issues with Alternative Order Table
Difficult to track information between columns Other issues How much room is allowed for multiple entries? What if an order has more order lines than you have allowed room for? For a given part, how do you determine which orders contain order lines for that part? A Guide to SQL, Eighth Edition
26
Benefits of Order_Line Table
Table is less complicated when separated No multiple entries Number of order lines is not limited Finding every order for a given part is simple A Guide to SQL, Eighth Edition
27
A Guide to SQL, Eighth Edition
Henry Books Database Ray Henry owns Henry Books, a bookstore chain Data is to be stored in a database Needs forms and reports to work with the data Gathers a variety of information on branches, publishers, authors, and books A Guide to SQL, Eighth Edition
28
A Guide to SQL, Eighth Edition
Data for Branch Table Number Name Location Number of employees A Guide to SQL, Eighth Edition
29
A Guide to SQL, Eighth Edition
Sample Branch Table A Guide to SQL, Eighth Edition
30
Data for Publisher Table
Publisher Code Name City A Guide to SQL, Eighth Edition
31
Sample Publisher Table
A Guide to SQL, Eighth Edition
32
A Guide to SQL, Eighth Edition
Data for Author Table Author number Last name First name A Guide to SQL, Eighth Edition
33
A Guide to SQL, Eighth Edition
Sample Author Table A Guide to SQL, Eighth Edition
34
A Guide to SQL, Eighth Edition
Data for Book Table Book code Title Publisher Type of book Price Is it a paperback? A Guide to SQL, Eighth Edition
35
A Guide to SQL, Eighth Edition
Sample Book Table A Guide to SQL, Eighth Edition
36
A Guide to SQL, Eighth Edition
Data for Wrote Table This table relates books and authors Book code Author number Sequence, for books with multiple authors A Guide to SQL, Eighth Edition
37
Data for Inventory Table
This table indicates the number of copies currently on hand at a particular branch Book code Branch number On hand quantity A Guide to SQL, Eighth Edition
38
Sample Wrote and Inventory Tables
Wrote table Inventory table A Guide to SQL, Eighth Edition
39
Alexamara Marina Database
Alexamara Marina Group offers in-water storage to boat owners Has two properties Also provides boat repair and maintenance services Uses database to store information for managing operations A Guide to SQL, Eighth Edition
40
A Guide to SQL, Eighth Edition
Data for Marina Table Marina number Name Street Address City, State, and Zip A Guide to SQL, Eighth Edition
41
A Guide to SQL, Eighth Edition
Data for Owner Table Owner number Last and First names Street Address City, State, and Zip A Guide to SQL, Eighth Edition
42
Sample Marina and Owner Tables
A Guide to SQL, Eighth Edition
43
Data for Marina_Slip Table
Slip ID, Marina Number, Slip Number Length Rental fee Boat name and Boat type Owner number A Guide to SQL, Eighth Edition
44
Sample Marina_Slip Table
A Guide to SQL, Eighth Edition
45
A Guide to SQL, Eighth Edition
Service Data Maintenance service category information is stored in the SERVICE_CATEGORY table Information on the services requested is stored in the SERVICE_REQUEST table Stores service category, slip information, description and status, estimated hours, hours spent, and next service date A Guide to SQL, Eighth Edition
46
Sample Service_Category Table
A Guide to SQL, Eighth Edition
47
Sample Service_Request Table
A Guide to SQL, Eighth Edition
48
A Guide to SQL, Eighth Edition
Summary Premiere Products Requires rep, customer, parts, orders, and order lines Henry Books Requires branch, publisher, author, book, and inventory Alexamara Marina Group Requires marina, owners, slips, service categories, and service requests A Guide to SQL, Eighth Edition
49
A Guide to SQL, Eighth Edition
Chapter Two Database Design Fundamentals 49
50
A Guide to SQL, Eighth Edition
Objectives Understand the terms entity, attribute, and relationship Understand the terms relation and relational database Understand functional dependence and be able to identify when one column is functionally dependent on another Understand the term primary key and identify primary keys in tables A Guide to SQL, Eighth Edition
51
Objectives (continued)
Design a database to satisfy a set of requirements Convert an unnormalized relation to first normal form Convert tables from first normal form to second normal form Convert tables from second normal form to third normal form A Guide to SQL, Eighth Edition
52
Objectives (continued)
Create an entity-relationship diagram to represent the design of a database A Guide to SQL, Eighth Edition
53
A Guide to SQL, Eighth Edition
Introduction Database design Process of determining the particular tables and columns that will comprise a database Must understand database concepts Process of normalization A Guide to SQL, Eighth Edition
54
A Guide to SQL, Eighth Edition
Database Concepts Entity Attribute Relationship Functional dependence Primary key A Guide to SQL, Eighth Edition
55
A Guide to SQL, Eighth Edition
Relational Database A collection of tables Tables in Premiere Products Database Rep Customer Orders Part Order_Line A Guide to SQL, Eighth Edition
56
Entities, Attributes, and Relationships
Entity (like a noun) A person, place, thing, or event Attribute (like an adjective or adverb) Property of an entity Relationship Association between entities A Guide to SQL, Eighth Edition
57
Entities, Attributes, and Relationships (continued)
One-to-many relationship One rep is related to many customers Implement by having a common column in two or more tables REP_NUM is a column in the Customer table and the Rep table Repeating groups Multiple entries in an individual location A Guide to SQL, Eighth Edition
58
Entities, Attributes, and Relationships (continued)
A Guide to SQL, Eighth Edition
59
Entities, Attributes, and Relationships (continued)
A Guide to SQL, Eighth Edition
60
Entities, Attributes, and Relationships (continued)
Relation is a two-dimensional table Entries in the table are single-valued Each column has a distinct name All values in a column are values of the same attribute The order of the columns is immaterial Each row is distinct The order of the rows is immaterial A Guide to SQL, Eighth Edition
61
Entities, Attributes, and Relationships (continued)
Use shorthand representation to show tables and columns REP (REP_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, ZIP, COMMISSION, RATE) CUSTOMER (CUSTOMER_NUM, CUSTOMER_NAME, STREET, CITY, STATE, ZIP, BALANCE, CREDIT_LIMIT, REP_NUM) ORDERS (ORDER_NUM, ORDER_DATE, CUSTOMER_NUM) ORDER_LINE (ORDER_NUM, PART_NUM, NUM_ORDERED, QUOTED_PRICE) PART (PART_NUM, DESCRIPTION, ON_HAND, CLASS, WAREHOUSE, PRICE) A Guide to SQL, Eighth Edition
62
Functional Dependence
An attribute, B, is functionally dependent on another attribute (or collection), A, if a value for A determines a single value for B at any one time B is functionally dependent on A A B A functionally determines B Cannot determine from sample data; must know the users’ policies A Guide to SQL, Eighth Edition
63
Functional Dependence (continued)
A Guide to SQL, Eighth Edition
64
A Guide to SQL, Eighth Edition
Primary Keys Unique identifier for a table Column (attribute) A (or a collection of columns) is the for a table (relation), R, if: All columns in R are functionally dependent on A No subcollection of the columns in A (assuming that A is a collection of columns and not just a single column) also has Property 1 A Guide to SQL, Eighth Edition
65
A Guide to SQL, Eighth Edition
Database Design Given a set of requirements that the database must support Requirements gathered through a process known as systems analysis A Guide to SQL, Eighth Edition
66
A Guide to SQL, Eighth Edition
Design Method Read the requirements, identify the entities (objects) involved, and name the entities Identify the unique identifiers for the entities identified in step 1 Identify the attributes for all the entities Identify the functional dependencies that exist among the attributes Use the functional dependencies to identify the tables by placing each attribute with the attribute or minimum combination of attributes on which it is functionally dependent Identify any relationships between tables. A Guide to SQL, Eighth Edition
67
Database Design Requirements
For Premiere Products Must store data about sales reps, customers, parts, orders, and order lines Must enforce certain constraints; for example: There is only customer per order On a given order, there is at most one line item for a given part The quoted price may differ from the actual price A Guide to SQL, Eighth Edition
68
Database Design Process Example
Apply requirements to six steps in design method A Guide to SQL, Eighth Edition
69
A Guide to SQL, Eighth Edition
Normalization Identify the existence of potential problems Provides a method for correcting problems Goal Convert unnormalized relations (tables that contain repeating groups) into various types of normal forms A Guide to SQL, Eighth Edition
70
Normalization (continued)
1 NF Better than unnormalized 2 NF Better than 1 NF 3 NF Better than 2 NF A Guide to SQL, Eighth Edition
71
A Guide to SQL, Eighth Edition
First Normal Form A relation is in first normal form (1NF) if it does not contain any repeating groups To convert an unnormalized relation to 1NF, expand the PK to include the PK of the repeating group This effectively eliminates the repeating group from the relation A Guide to SQL, Eighth Edition
72
First Normal Form (continued)
A Guide to SQL, Eighth Edition
73
First Normal Form (continued)
A Guide to SQL, Eighth Edition
74
A Guide to SQL, Eighth Edition
Second Normal Form Redundancy causes problems Update Anomalies Update Inconsistent data Additions Deletions A Guide to SQL, Eighth Edition
75
Second Normal Form (continued)
Table is in First Normal Form but not in Second Normal Form A Guide to SQL, Eighth Edition
76
Second Normal Form (continued)
A relation is in second normal form (2NF) if it is in 1NF and no nonkey attribute is dependent on only a portion of the primary key or … All nonkey attributes are functionally dependent on the entire primary key A Guide to SQL, Eighth Edition
77
Second Normal Form (continued)
A 1NF relation with a primary key that is a single field is in 2NF automatically A Guide to SQL, Eighth Edition
78
Second Normal Form (continued)
A Guide to SQL, Eighth Edition
79
A Guide to SQL, Eighth Edition
Third Normal Form Update anomalies still possible Determinant An attribute (or collection) that functionally determines another attribute A Guide to SQL, Eighth Edition
80
Third Normal Form (continued)
Table is in Second Normal Form but not in Third Normal Form A Guide to SQL, Eighth Edition
81
Third Normal Form (continued)
A relation is in third normal form (3NF) if it is in 2NF and the only determinants it contains are candidate keys Boyce-Codd normal form (BCNF) is the true name for this version of 3NF A Guide to SQL, Eighth Edition
82
Third Normal Form (continued)
A Guide to SQL, Eighth Edition
83
Diagrams for Database Design
Graphical illustration Entity-relationship (E-R) diagram Rectangles represent entities Arrows represent relationships A Guide to SQL, Eighth Edition
84
Diagrams for Database Design (continued)
A Guide to SQL, Eighth Edition
85
Diagrams for Database Design (continued)
A Guide to SQL, Eighth Edition
86
Diagrams for Database Design (continued)
A Guide to SQL, Eighth Edition
87
A Guide to SQL, Eighth Edition
Summary Definition of entity Definition of attribute Definition of relationship Definition of relation Definition of functional dependence Definition of primary key Database design method A Guide to SQL, Eighth Edition
88
A Guide to SQL, Eighth Edition
Summary (continued) Normalization Unnormalized (repeating groups) First normal form (INF) Second normal form (2NF) Third normal form (3NF) Entity-relationship diagram (E-R diagram) A Guide to SQL, Eighth Edition
89
A Guide to SQL, Eighth Edition
Chapter Three Creating Tables 89
90
A Guide to SQL, Eighth Edition
Objectives Create and run SQL commands Create tables Identify and use data types to define columns in tables Understand and use nulls Add rows to tables A Guide to SQL, Eighth Edition
91
Objectives (continued)
View table data Correct errors in a table Save SQL commands to a file Describe a table’s layout using SQL A Guide to SQL, Eighth Edition
92
A Guide to SQL, Eighth Edition
Introduction Structured Query Language (SQL) Most popular and widely used language for retrieving and manipulating database data Developed in mid 1970s under the name SEQUEL Renamed SQL in 1980 Used by most DBMSs A Guide to SQL, Eighth Edition
93
Creating and Running SQL Commands
Oracle Database 10g Express Software used in text to illustrate SQL Commands will work the same in other versions of Oracle Differences between Oracle and Microsoft Access and SQL Server 2005 are noted in special boxes A Guide to SQL, Eighth Edition
94
Starting the Oracle Database Express Edition
Software loads in Internet Explorer Other browsers may not fully support examples used in text Must have a username and password Click icons on Home page to access various tools A Guide to SQL, Eighth Edition
95
Starting the Oracle Database Express Edition (continued)
A Guide to SQL, Eighth Edition
96
A Guide to SQL, Eighth Edition
Entering Commands A Guide to SQL, Eighth Edition
97
Entering Commands (continued)
A Guide to SQL, Eighth Edition
98
A Guide to SQL, Eighth Edition
Creating a Table Describe the layout of each table in the database Use CREATE TABLE command TABLE is followed by the table name Follow this with the names and data types of the columns in the table Data types define type and size of data A Guide to SQL, Eighth Edition
99
Creating a Table (continued)
Table and column name restrictions Names cannot exceed 30 characters Must start with a letter Can contain letters, numbers, and underscores (_) Cannot contain spaces A Guide to SQL, Eighth Edition
100
Creating a Table (continued)
A Guide to SQL, Eighth Edition
101
Creating a Table (continued)
Commands are free-format; no rules stating specific words in specific positions Indicate the end of a command by typing a semicolon Commands are not case sensitive In Oracle, enter the command in the SQL editor pane A Guide to SQL, Eighth Edition
102
Creating a Table (continued)
A Guide to SQL, Eighth Edition
103
Creating a Table (continued)
A Guide to SQL, Eighth Edition
104
Creating a Table (continued)
A Guide to SQL, Eighth Edition
105
Correcting Errors in SQL Commands
Use the same techniques that you might use in a word processor Make changes and click Run button to execute command again Check Results pane to determine if command executed successfully A Guide to SQL, Eighth Edition
106
A Guide to SQL, Eighth Edition
Dropping a Table Can correct errors by dropping (deleting) a table and starting over Useful when table is created before errors are discovered Command is followed by the table to be dropped and a semicolon Any data in table also deleted A Guide to SQL, Eighth Edition
107
A Guide to SQL, Eighth Edition
Using Data Types For each column, the type of data must be defined Common data types CHAR(n) VARCHAR(n) DATE DECIMAL(p,q) INT SMALLINT A Guide to SQL, Eighth Edition
108
A Guide to SQL, Eighth Edition
Using Nulls A special value to represent a situation when the actual value is not known for a column Can specify whether to allow nulls in the individual columns Should not allow nulls for primary key columns A Guide to SQL, Eighth Edition
109
Using Nulls (continued)
Use NOT NULL clause in CREATE TABLE command to exclude the use of nulls in a column Default is to allow null values If a column is defined as NOT NULL, system will reject any attempt to store a null value there A Guide to SQL, Eighth Edition
110
Using Nulls (continued)
CREATE TABLE REP (REP_NUM CHAR(2) PRIMARY KEY, LAST_NAME CHAR(15) NOT NULL, FIRST_NAME CHAR(15) NOT NULL, STREET CHAR(15), CITY CHAR(15), STATE CHAR(2), ZIP CHAR(5), COMMISSION DECIMAL(7,2), RATE DECIMAL(3,2) ); A Guide to SQL, Eighth Edition
111
A Guide to SQL, Eighth Edition
Adding Rows to a Table INSERT Command INSERT INTO followed by table name VALUES command followed by specific values in parentheses Values for character columns in single quotation marks A Guide to SQL, Eighth Edition
112
A Guide to SQL, Eighth Edition
The Insert Command A Guide to SQL, Eighth Edition
113
The INSERT Command (continued)
To add new rows, modify previous insert command Use same editing techniques as those used to correct errors A Guide to SQL, Eighth Edition
114
Inserting a Row that Contains Nulls
Use a special format of INSERT command to enter a null value in a table Identify the names of the columns that accept non-null values and then list only the non-null values after the VALUES command A Guide to SQL, Eighth Edition
115
Inserting a Row that Contains Nulls (continued)
A Guide to SQL, Eighth Edition
116
A Guide to SQL, Eighth Edition
Viewing Table Data Use SELECT command Can display all the rows and columns in a table SELECT * FROM followed by the name of the table Ends with a semicolon A Guide to SQL, Eighth Edition
117
Viewing Table Data (continued)
A Guide to SQL, Eighth Edition
118
Viewing Table Data (continued)
In Access Enter SELECT statement in SQL view In SQL Server Enter SELECT statement in Query Editor window A Guide to SQL, Eighth Edition
119
Correcting Errors in a Table
UPDATE command is used to update a value in a table DELETE command allows you to delete a record INSERT command allows you to add a record A Guide to SQL, Eighth Edition
120
Correcting Errors in a Table (continued)
A Guide to SQL, Eighth Edition
121
Correcting Errors in a Table (continued)
A Guide to SQL, Eighth Edition
122
Correcting Errors in a Table (continued)
A Guide to SQL, Eighth Edition
123
A Guide to SQL, Eighth Edition
Saving SQL Commands Allows you to use commands again without retyping Save commands in a script file or script Text file with .sql extension Script repository Special location in Oracle Can download to local drive A Guide to SQL, Eighth Edition
124
Saving SQL Commands (continued)
To create a script file in Oracle: Use Script Editor page Enter a name for script Type the command or commands to save in script Save the script A Guide to SQL, Eighth Edition
125
Saving SQL Commands (continued)
Once a script file is created: Can view, edit, or run Can delete Can download from script repository to local drive Can upload from local drive to script repository A Guide to SQL, Eighth Edition
126
Saving SQL Commands (continued)
Access Does not use script files Save SQL commands as query objects SQL Server Can create scripts Can view, edit, run scripts Can delete scripts A Guide to SQL, Eighth Edition
127
Creating the Remaining Database Tables
Execute appropriate CREATE TABLE and INSERT commands Save these commands as scripts Separate multiple commands in a script file with a semicolon Figures 3-25 through 3-32 give additional table information for Premiere Products A Guide to SQL, Eighth Edition
128
A Guide to SQL, Eighth Edition
Describing a Table DESCRIBE command (Oracle) Documenter tool (Access) Exec sp_columns command (SQL Server) A Guide to SQL, Eighth Edition
129
Describing a Table (continued)
A Guide to SQL, Eighth Edition
130
A Guide to SQL, Eighth Edition
Summary Use the CREATE TABLE command to create tables Use the DROP TABLE command to delete a table CHAR, VARCHAR, DATE, DECIMAL, INT, and SMALLINT data types Access does not support DECIMAL SQL Server uses DATETIME instead of DATE A Guide to SQL, Eighth Edition
131
A Guide to SQL, Eighth Edition
Summary (continued) Null value used when actual value for a column is unknown, unavailable, or not applicable Use NOT Null clause to identify columns that cannot have a null value Use INSERT command to add rows Use SELECT command to view data in a table A Guide to SQL, Eighth Edition
132
A Guide to SQL, Eighth Edition
Summary (continued) Use UPDATE command to change the value in a column Use DELETE command to delete a row Save SQL commands in a script file Use DESCRIBE command to display a table’s structure A Guide to SQL, Eighth Edition
133
A Guide to SQL, Eighth Edition
Chapter Four Single-Table Queries 133
134
A Guide to SQL, Eighth Edition
Objectives Retrieve data from a database using SQL commands Use simple and compound conditions in queries Use the BETWEEN, LIKE, and IN operators in queries Use computed columns in queries A Guide to SQL, Eighth Edition
135
Objectives (continued)
Sort data using the ORDER BY clause Sort data using multiple keys and in ascending and descending order Use aggregate functions in a query Use subqueries Group data using the GROUP BY clause A Guide to SQL, Eighth Edition
136
Objectives (continued)
Select individual groups of data using the HAVING clause Retrieve columns with null values A Guide to SQL, Eighth Edition
137
Constructing Simple Queries
What is a query ? Question represented in a way that the DBMS can understand How do you implement in SQL? Use SELECT command Are there any special formatting rules? No A Guide to SQL, Eighth Edition
138
Constructing Simple Queries (continued)
SELECT-FROM-WHERE statement SELECT columns to include in result FROM table containing columns WHERE any conditions to apply to the data WHERE clause is optional A Guide to SQL, Eighth Edition
139
Retrieving Certain Columns and Rows
Use SELECT command to retrieve specified columns and all rows List the number, name, and balance of all customers No WHERE clause needed, because all customers are requested A Guide to SQL, Eighth Edition
140
Retrieving Certain Columns and Rows (continued)
A Guide to SQL, Eighth Edition
141
Retrieving All Columns and Rows
Use an asterisk (*) to indicate all columns in the SELECT clause Will list all columns in the order used when table was created List specific columns in SELECT clause to present columns in a different order A Guide to SQL, Eighth Edition
142
Retrieving All Columns and Rows (continued)
A Guide to SQL, Eighth Edition
143
A Guide to SQL, Eighth Edition
Using a WHERE Clause WHERE clause Used to retrieve rows that satisfy some condition What is the name of customer number 148? Simple Condition Column name, comparison operator followed by either a column name or a value A Guide to SQL, Eighth Edition
144
Using a WHERE Clause (continued)
A Guide to SQL, Eighth Edition
145
Using a WHERE Clause (continued)
A Guide to SQL, Eighth Edition
146
Using a WHERE Clause (continued)
Simple conditions can compare columns A Guide to SQL, Eighth Edition
147
Using Compound Conditions
Connect two or more simple conditions with AND, OR, and NOT operators AND operator: all simple conditions are true OR operator: any simple condition is true NOT operator: reverses the truth of the original condition A Guide to SQL, Eighth Edition
148
Using Compound Conditions (continued)
A Guide to SQL, Eighth Edition
149
Using Compound Conditions (continued)
A Guide to SQL, Eighth Edition
150
Using Compound Conditions (continued)
A Guide to SQL, Eighth Edition
151
Using the BETWEEN Operator
Use instead of AND operator Use when searching a range of values Makes SELECT commands simpler to construct Inclusive When using BETWEEN 2000 and 5000, values of 2000 or 5000 would be true A Guide to SQL, Eighth Edition
152
Using the BETWEEN Operator (continued)
A Guide to SQL, Eighth Edition
153
Using Computed Columns
Does not exist in the database but is computed using data in existing columns Arithmetic operators + for addition - for subtraction * for multiplication / for division A Guide to SQL, Eighth Edition
154
Using Computed Columns (continued)
A Guide to SQL, Eighth Edition
155
Using Computed Columns (continued)
Use AS clause to assign a name A Guide to SQL, Eighth Edition
156
Using the LIKE Operator
Used for pattern matching LIKE %Central% will retrieve data with those characters “3829 Central” or “Centralia” Underscore (_) represents any single character “T_M” for TIM or TOM or T3M A Guide to SQL, Eighth Edition
157
Using the LIKE Operator (continued)
A Guide to SQL, Eighth Edition
158
A Guide to SQL, Eighth Edition
Using the IN Operator Concise phrasing of OR conditions A Guide to SQL, Eighth Edition
159
A Guide to SQL, Eighth Edition
Sorting By default, no defined order in which results are displayed Use ORDER BY clause to list data in a specific order A Guide to SQL, Eighth Edition
160
Using the ORDER BY Clause
Sort key or key Column on which data is to be sorted Ascending is default sort order A Guide to SQL, Eighth Edition
161
Additional Sorting Options
Possible to sort data by more than one key Major sort key and minor sort key List sort keys in order of importance in the ORDER BY clause For descending order sort, use DESC A Guide to SQL, Eighth Edition
162
Additional Sorting Options (continued)
A Guide to SQL, Eighth Edition
163
A Guide to SQL, Eighth Edition
Using Functions Aggregate functions Apply to groups of rows A Guide to SQL, Eighth Edition
164
Using the COUNT Function
Counts the number of rows in a table Can use asterisk (*) to represent any column A Guide to SQL, Eighth Edition
165
A Guide to SQL, Eighth Edition
Using the SUM Function Used to calculate totals of columns Column must be specified and must be numeric Null values are ignored A Guide to SQL, Eighth Edition
166
Using the AVG, MAX, and MIN Functions
Numeric columns only Ignores nulls A Guide to SQL, Eighth Edition
167
Using the DISTINCT Operator
Eliminates duplicate values Used with COUNT function A Guide to SQL, Eighth Edition
168
Using the DISTINCT Operator (continued)
A Guide to SQL, Eighth Edition
169
Using the DISTINCT Operator (continued)
A Guide to SQL, Eighth Edition
170
A Guide to SQL, Eighth Edition
Nesting Queries Query results require two or more steps Subquery: an inner query placed inside another query Outer query uses subquery results A Guide to SQL, Eighth Edition
171
Nesting Queries (continued)
A Guide to SQL, Eighth Edition
172
Nesting Queries (continued)
A Guide to SQL, Eighth Edition
173
A Guide to SQL, Eighth Edition
Grouping Grouping: creates groups of rows that share common characteristics Calculations in the SELECT command are performed for the entire group A Guide to SQL, Eighth Edition
174
Using the GROUP BY Clause
Group data on a particular column Calculate statistics A Guide to SQL, Eighth Edition
175
Using the GROUP BY Clause (continued)
A Guide to SQL, Eighth Edition
176
A Guide to SQL, Eighth Edition
Using a HAVING Clause Used to restrict groups that will be included A Guide to SQL, Eighth Edition
177
A Guide to SQL, Eighth Edition
Having vs. Where WHERE: limit rows HAVING: limit groups Can use together if condition involves both rows and groups A Guide to SQL, Eighth Edition
178
Having vs. Where (continued)
A Guide to SQL, Eighth Edition
179
A Guide to SQL, Eighth Edition
Nulls Condition that involves a column that can be null IS NULL IS NOT NULL A Guide to SQL, Eighth Edition
180
A Guide to SQL, Eighth Edition
Summary Create queries that retrieve data from a single table using SELECT commands Comparison operators =, >,=>,<,=<, or <>, or != Compound conditions AND,OR, and NOT Use the BETWEEN operator Use the LIKE operator A Guide to SQL, Eighth Edition
181
A Guide to SQL, Eighth Edition
Summary (continued) IN operator ORDER BY clause Aggregate functions COUNT, SUM, AVG, MAX, and MIN DISTINCT operator Subqueries GROUP BY HAVING NULL A Guide to SQL, Eighth Edition
182
A Guide to SQL, Eighth Edition
Chapter Five Multiple-Table Queries 182
183
A Guide to SQL, Eighth Edition
Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery with a subquery Use an alias A Guide to SQL, Eighth Edition
184
Objectives (continued)
Join a table to itself Perform set operations (union, intersection, and difference) Use the ALL and ANY operators in a query Perform special operations (inner join, outer join, and product) A Guide to SQL, Eighth Edition
185
Querying Multiple Tables
Retrieve data from two or more tables Join tables Use the same commands as for single-table queries A Guide to SQL, Eighth Edition
186
A Guide to SQL, Eighth Edition
Joining Two Tables SELECT clause List all columns to display FROM clause List all tables involved in query WHERE clause Restrict to rows that have common values in matching columns A Guide to SQL, Eighth Edition
187
Joining Two Tables (continued)
A Guide to SQL, Eighth Edition
188
Joining Two Tables (continued)
A Guide to SQL, Eighth Edition
189
Joining Two Tables (continued)
A Guide to SQL, Eighth Edition
190
Comparing JOINS, IN, and EXISTS
Can join tables using: WHERE clause IN operator with a subquery EXISTS operator with a subquery A Guide to SQL, Eighth Edition
191
Comparing JOINS, IN, and EXISTS (continued)
WHERE clause A Guide to SQL, Eighth Edition
192
A Guide to SQL, Eighth Edition
Using the IN Operator A Guide to SQL, Eighth Edition
193
Using the EXISTS Operator
A Guide to SQL, Eighth Edition
194
Using the EXISTS Operator (continued)
Correlated subquery Subquery involves a table listed in outer query In Figure 5-7, the ORDERS table, listed in FROM clause of outer query used in subquery Must qualify ORDER_NUM column in subquery as ORDERS.ORDER_NUM A Guide to SQL, Eighth Edition
195
Using a Subquery within a Subquery
Nested subquery is a subquery within a subquery Evaluate from innermost query to outermost More than one approach to formulating queries Many DMBSs have optimizers that analyze queries for efficiency A Guide to SQL, Eighth Edition
196
Using a Subquery within a Subquery (continued)
A Guide to SQL, Eighth Edition
197
Using a Subquery within a Subquery (continued)
Order of evaluating query Innermost subquery first producing a temporary table Next (intermediate) subquery producing a second temporary table Outer query last producing final result A Guide to SQL, Eighth Edition
198
A Comprehensive Example
A Guide to SQL, Eighth Edition
199
A Guide to SQL, Eighth Edition
Using an Alias An alternate name for a table Use in FROM clause Type name of table, press Spacebar, and then type name of alias Allows for simplicity A Guide to SQL, Eighth Edition
200
Using an Alias (continued)
A Guide to SQL, Eighth Edition
201
Joining a Table to Itself
Called a self-join Use a different alias for same table Use to compare records within one table Treat one table as two separate tables by using alias A Guide to SQL, Eighth Edition
202
Joining a Table to Itself (continued)
A Guide to SQL, Eighth Edition
203
Using a Self-Join on a Primary Key
Can create a self-join that involves primary key of table List table twice in FROM clause with aliases Same as previous self-join example A Guide to SQL, Eighth Edition
204
Using a Self-Join on a Primary Key (continued)
A Guide to SQL, Eighth Edition
205
Joining Several Tables
Condition relates columns for each pair of tables A Guide to SQL, Eighth Edition
206
Joining Several Tables (continued)
In SELECT clause, list all columns to display Qualify any column names if needed In FROM clause, list all tables Include tables used in the WHERE clause, even if they are not in the SELECT clause A Guide to SQL, Eighth Edition
207
Joining Several Tables (continued)
Take one pair of related tables at a time Indicate in WHERE clause the condition that relates tables Join conditions with AND operator Include any additional conditions in WHERE clause Connect them with AND operator A Guide to SQL, Eighth Edition
208
A Guide to SQL, Eighth Edition
Set Operations Union The union of two tables is a table containing every row that is in either the first table, the second table, or both tables Use UNION operator Tables must be union compatible; that is, the same number of columns and corresponding columns have identical data types and lengths A Guide to SQL, Eighth Edition
209
Set Operations (continued)
A Guide to SQL, Eighth Edition
210
Set Operations (continued)
Intersection Intersection of two tables is a table containing all rows that are in both tables Uses the INTERSECT operator Not supported by Microsoft Access Use an alternate approach A Guide to SQL, Eighth Edition
211
Set Operations (continued)
A Guide to SQL, Eighth Edition
212
Set Operations (continued)
Difference Difference of two tables is a table containing set of all rows that are in first table but not in second table Uses the MINUS operator Not supported by SQL Server and Microsoft Access Use an alternate approach A Guide to SQL, Eighth Edition
213
Set Operations (continued)
A Guide to SQL, Eighth Edition
214
A Guide to SQL, Eighth Edition
ALL and ANY ALL operator Condition is true only if it satisfies all values ANY operator Condition is true only if it satisfies any value Precede subquery with appropriate operator A Guide to SQL, Eighth Edition
215
ALL and ANY (continued)
A Guide to SQL, Eighth Edition
216
ALL and ANY (continued)
A Guide to SQL, Eighth Edition
217
A Guide to SQL, Eighth Edition
Special Operations Self-join Inner join Outer join Product A Guide to SQL, Eighth Edition
218
A Guide to SQL, Eighth Edition
Inner Join Compares the tables in FROM clause and lists only those rows that satisfy condition in WHERE clause INNER JOIN command Update to SQL standard 1992 A Guide to SQL, Eighth Edition
219
Inner Join (continued)
A Guide to SQL, Eighth Edition
220
A Guide to SQL, Eighth Edition
Outer Joins Left outer join: all rows from the table on the left (listed first in the query) will be included; matching rows only from the table on the right will be included Right outer join: all rows from the table on the right will be included; matching rows only from the table on the left will be included Full outer join: all rows from both tables will be included regardless of matches A Guide to SQL, Eighth Edition
221
A Guide to SQL, Eighth Edition
Product The product (Cartesian product) of two tables is the combination of all rows in the first table and all rows in the second table Omit the WHERE clause to form a product A Guide to SQL, Eighth Edition
222
A Guide to SQL, Eighth Edition
Summary Join tables with WHERE clause Join tables with IN operator Join tables with EXISTS operator A subquery can contain another subquery Use an alias to simplify SQL command as well to create self-join A Guide to SQL, Eighth Edition
223
A Guide to SQL, Eighth Edition
Summary (continued) UNION, INTERSECT, MINUS ALL and ANY operators Inner join Outer joins Left, right, full Cartesian product A Guide to SQL, Eighth Edition
224
A Guide to SQL, Eighth Edition
Chapter Six Updating Data 224
225
A Guide to SQL, Eighth Edition
Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT command Delete data using the DELETE command A Guide to SQL, Eighth Edition
226
Objectives (continued)
Use nulls in UPDATE commands Change the structure of an existing table Use the COMMIT and ROLLBACK commands to make permanent data updates or to reverse updates Understand transactions and the role of COMMIT and ROLLBACK in supporting transactions Drop a table A Guide to SQL, Eighth Edition
227
Creating a New Table from an Existing Table
Can create new table using an existing table Use CREATE TABLE command Can add query results to table by placing SELECT command in an INSERT command A Guide to SQL, Eighth Edition
228
Creating a New Table from an Existing Table (continued)
A Guide to SQL, Eighth Edition
229
Creating a New Table from an Existing Table (continued)
A Guide to SQL, Eighth Edition
230
Changing Existing Data in a Table
Use UPDATE command to change rows for which a specific condition is true Simple or compound condition Command format UPDATE (name of table to be updated) SET (name of the column to be updated = new value) Can include a calculation A Guide to SQL, Eighth Edition
231
Changing Existing Data in a Table (continued)
Simple Condition A Guide to SQL, Eighth Edition
232
Changing Existing Data in a Table (continued)
Compound Condition A Guide to SQL, Eighth Edition
233
Adding New Rows to an Existing Table
Use the INSERT command to add additional data to a table Use the SELECT command to verify rows were added correctly A Guide to SQL, Eighth Edition
234
Adding New Rows to an Existing Table (continued)
A Guide to SQL, Eighth Edition
235
A Guide to SQL, Eighth Edition
COMMIT and ROLLBACK Autocommit is default transaction mode Commits each action query as soon as the user executes each query Remove check mark to turn off Autocommit in Oracle Multi-user database applications require more control over transactions A Guide to SQL, Eighth Edition
236
COMMIT and ROLLBACK (continued)
Updates to a table are only temporary Can cancel during current work session COMMIT command Saves changes immediately during current session ROLLBACK command Reverses the changes made since last COMMIT command or in current work session A Guide to SQL, Eighth Edition
237
COMMIT and ROLLBACK (continued)
ROLLBACK command only reverses changes made to data COMMIT command is permanent Running ROLLBACK after COMMIT cannot reverse the update A Guide to SQL, Eighth Edition
238
A Guide to SQL, Eighth Edition
Transactions A transaction is a logical unit of work A sequence of steps that accomplish a single task Essential that the entire sequence be completed successfully COMMIT and ROLLBACK commands support transactions A Guide to SQL, Eighth Edition
239
Transactions (continued)
Before starting updates for a transaction, COMMIT any previous updates Complete the updates for the transaction If it cannot be completed, use ROLLBACK If all updates complete, use COMMIT again A Guide to SQL, Eighth Edition
240
Changing and Deleting Existing Rows
Autocommit is turned off A Guide to SQL, Eighth Edition
241
Changing and Deleting Existing Rows (continued)
Use DELETE command to delete data from database Command format DELETE (table from which the row(s) is to be deleted) WHERE clause (with a condition to select the row(s) to delete) All rows satisfying the condition will be deleted If no condition, then all rows deleted A Guide to SQL, Eighth Edition
242
Changing and Deleting Existing Rows (continued)
Autocommit is turned off A Guide to SQL, Eighth Edition
243
A Guide to SQL, Eighth Edition
Executing a Rollback ROLLBACK command A Guide to SQL, Eighth Edition
244
Changing a Value in a Column to Null
Command for changing value to null is the same as changing any other value Affected column must be able to accept nulls Use the value NULL as the replacement value A Guide to SQL, Eighth Edition
245
Changing a Value in a Column to Null (continued)
A Guide to SQL, Eighth Edition
246
Changing a Table’s Structure
Add new tables Delete tables no longer required Add new columns to a table Change physical characteristics of existing columns A Guide to SQL, Eighth Edition
247
Changing a Table’s Structure (continued)
ALTER TABLE command allows for changing a table’s structure Use ADD clause to add a new column ADD clause is followed by the name of column to be added, followed by its characteristics A Guide to SQL, Eighth Edition
248
Changing a Table’s Structure (continued)
Assign value to new column Simplest approach is to assign NULL as the value Or use an UPDATE command Change all rows to most common value Change individual rows A Guide to SQL, Eighth Edition
249
Changing a Table’s Structure (continued)
A Guide to SQL, Eighth Edition
250
Changing a Table’s Structure (continued)
A Guide to SQL, Eighth Edition
251
Changing a Table’s Structure (continued)
A Guide to SQL, Eighth Edition
252
Changing a Table’s Structure (continued)
A Guide to SQL, Eighth Edition
253
Changing a Table’s Structure (continued)
MODIFY clause of ALTER TABLE command changes characteristics of existing columns Can use to change a column that currently rejects null values Use NULL in place of NOT NULL Can increase and decrease size of column A Guide to SQL, Eighth Edition
254
Changing a Table’s Structure (continued)
A Guide to SQL, Eighth Edition
255
Making Complex Changes
Changes to table structure may be beyond the capabilities of SQL Eliminate multiple columns Change column order Combine data from two tables to one Create a new table A Guide to SQL, Eighth Edition
256
A Guide to SQL, Eighth Edition
Dropping a Table Use DROP TABLE command to delete a table Permanently removes table and all its data from database A Guide to SQL, Eighth Edition
257
Dropping a Table (continued)
A Guide to SQL, Eighth Edition
258
A Guide to SQL, Eighth Edition
Summary Use CREATE TABLE command to make a new table from an existing table INSERT statement containing a SELECT statement to insert data from existing table Use UPDATE command to change data Use INSERT command to add new rows Use DELETE command to delete existing rows from a table A Guide to SQL, Eighth Edition
259
A Guide to SQL, Eighth Edition
Summary (continued) Use COMMIT command to make changes permanent Use ROLLBACK command to reverse updates Use SET clause in UPDATE command to change a value to null Column name = NULL Column must accept nulls A Guide to SQL, Eighth Edition
260
A Guide to SQL, Eighth Edition
Summary (continued) Use ALTER TABLE command with ADD clause to add a column to a table Use ALTER TABLE command with MODIFY clause to change column characteristics Use DROP TABLE command to delete a table and all its data A Guide to SQL, Eighth Edition
261
A Guide to SQL, Eighth Edition
Chapter Seven Database Administration 261
262
A Guide to SQL, Eighth Edition
Objectives Understand, create, and drop views Recognize the benefits of using views Use a view to update data Grant and revoke users’ database privileges Understand the purpose, advantages, and disadvantages of using an index A Guide to SQL, Eighth Edition
263
Objectives (continued)
Create, use, and drop an index Understand and obtain information from the system catalog Use integrity constraints to control data entry A Guide to SQL, Eighth Edition
264
A Guide to SQL, Eighth Edition
Introduction Database administration Process of managing a database Database administrator Person or entire group in a business organization charged with managing the database A Guide to SQL, Eighth Edition
265
Creating and Using Views
A program’s or individual user’s picture of the database Base tables Existing, permanent tables in a relational database View is a derived table because data in it is retrieved from the base table A Guide to SQL, Eighth Edition
266
Creating and Using Views (continued)
Usually includes less information than full database Simplifies data processing for the user Provides a measure of security by omitting sensitive information Unavailable to user A Guide to SQL, Eighth Edition
267
Creating and Using Views (continued)
Created by a defining query Indicates rows and columns to include Use CREATE VIEW command CREATE VIEW, followed by name of view, AS, and then defining query A Guide to SQL, Eighth Edition
268
Creating and Using Views (continued)
A Guide to SQL, Eighth Edition
269
Creating and Using Views (continued)
A Guide to SQL, Eighth Edition
270
Creating and Using Views (continued)
Data shown in Figure 7-2 does not exist in this form Not a temporary table To query a view, merge query that created view with query to select specific data A Guide to SQL, Eighth Edition
271
Creating and Using Views (continued)
A Guide to SQL, Eighth Edition
272
Creating and Using Views (continued)
Actual query executed by SQL A Guide to SQL, Eighth Edition
273
Creating and Using Views (continued)
Can assign column names in view that are different than base table Include new column names in parentheses, following the name of the view Output will display new column names A Guide to SQL, Eighth Edition
274
Creating and Using Views (continued)
A Guide to SQL, Eighth Edition
275
Creating and Using Views (continued)
Defining query of view can be any valid SQL query View can join two or more tables A Guide to SQL, Eighth Edition
276
Creating and Using Views (continued)
A view can involve statistics A Guide to SQL, Eighth Edition
277
Creating and Using Views (continued)
Benefits of views Provide data independence Can often be used even after database structure changes Different users can view same data differently Customize display to meet each user’s needs A view can contain only those columns required by a given user Simplifies user’s perception of database Provides a measure of security A Guide to SQL, Eighth Edition
278
Using a View to Update Data
Benefits of views are for retrieval purposes only Updating data through a view is dependent on type of view A Guide to SQL, Eighth Edition
279
Updating Row-and-Column Subset Views
Can update (usually) if view contains primary key Cannot update when primary key is not included No primary key A Guide to SQL, Eighth Edition
280
Updating Views Involving Joins
Can update when a view is derived by joining two tables on primary key of each table Cannot update when view involves joining by matching the primary key of one table with a column that is not the primary key Encounter more severe problems if neither of the join columns is a primary key A Guide to SQL, Eighth Edition
281
Updating Views Involving Statistics
Most difficult to update Cannot add rows to a view that includes calculations A Guide to SQL, Eighth Edition
282
A Guide to SQL, Eighth Edition
Dropping a View Remove a view that is no longer needed with DROP VIEW command The DROP VIEW command removes only the view definition Base table and data remain unchanged A Guide to SQL, Eighth Edition
283
A Guide to SQL, Eighth Edition
Security Prevention of unauthorized access to a database Some users may be able to retrieve and update anything in database Other users may be able to retrieve data but not change data Other users may be able to access only a portion of data A Guide to SQL, Eighth Edition
284
A Guide to SQL, Eighth Edition
Security (continued) GRANT command Main mechanism for providing access to database Database administrator can grant different types of privileges to users and revoke them later Privileges include rights to select, insert, update, index, and delete table data A Guide to SQL, Eighth Edition
285
A Guide to SQL, Eighth Edition
Security (continued) Database administrator uses REVOKE command to remove privileges from users Format is similar to GRANT command A Guide to SQL, Eighth Edition
286
A Guide to SQL, Eighth Edition
Indexes Speeds up the searching of tables Similar to an index in a book A Guide to SQL, Eighth Edition
287
A Guide to SQL, Eighth Edition
Indexes (continued) A Guide to SQL, Eighth Edition
288
A Guide to SQL, Eighth Edition
Indexes (continued) SQL manages indexes User determines columns on which to build indexes Disadvantages Index occupies disk space DBMS must update index as data is entered A Guide to SQL, Eighth Edition
289
A Guide to SQL, Eighth Edition
Creating an Index Use CREATE INDEX command Name the index Identify the table Identify the column or columns A Guide to SQL, Eighth Edition
290
Creating an Index (continued)
Index on a single column A Guide to SQL, Eighth Edition
291
Creating an Index (continued)
Index on two columns A Guide to SQL, Eighth Edition
292
A Guide to SQL, Eighth Edition
Dropping an Index Use DROP INDEX to delete an index DROP INDEX followed by name of index to drop Permanently deletes index A Guide to SQL, Eighth Edition
293
Creating Unique Indexes
To ensure uniqueness of non-primary key data, you can create a unique index Use CREATE UNIQUE INDEX command A unique index will reject any update that would cause a duplicate value in the specified column A Guide to SQL, Eighth Edition
294
A Guide to SQL, Eighth Edition
System Catalog Contains information about tables in database; also called data dictionary Use SYSTABLES to list all tables in database Use SYSCOLUMNS to list all columns in a table Use SYSVIEWS to list information about views A Guide to SQL, Eighth Edition
295
System Catalog (continued)
In Oracle, use: DBA_TABLES to list information about tables DBA_TAB_COLUMNS to list information about columns DBA_VIEWS to list information about views A Guide to SQL, Eighth Edition
296
System Catalog (continued)
A Guide to SQL, Eighth Edition
297
System Catalog (continued)
A Guide to SQL, Eighth Edition
298
System Catalog (continued)
A Guide to SQL, Eighth Edition
299
Integrity Constraints in SQL
Rule for the data in the database Examples in Premiere Products A sales rep’s number must be unique The sales rep number for a customer must match an exiting sales rep number Item classes for parts must be AP, HW, or SG A Guide to SQL, Eighth Edition
300
Integrity Constraints in SQL (continued)
Integrity support is process of specifying integrity constraints for the database Clauses to support integrity constraints can be specified within a CREATE TABLE or ALTER TABLE command ADD PRIMARY KEY ADD FOREIGN KEY A Guide to SQL, Eighth Edition
301
Integrity Constraints in SQL (continued)
Primary keys Use ADD PRIMARY KEY clause on ALTER TABLE command to add after creating a table Foreign keys A column in one table whose value matches the primary key in another Legal values The CHECK clause ensures only legal values are allowed in a given column A Guide to SQL, Eighth Edition
302
Integrity Constraints in SQL (continued)
A Guide to SQL, Eighth Edition
303
Integrity Constraints in SQL (continued)
After creating a foreign key, DBMS rejects any update that violates the foreign key constraint Error messages refer to parent and child When specifying a foreign key, table containing foreign key is the child Table referenced by foreign key is parent A Guide to SQL, Eighth Edition
304
Integrity Constraints in SQL (continued)
A Guide to SQL, Eighth Edition
305
A Guide to SQL, Eighth Edition
Summary Views CREATE VIEW command Benefits Update issues DROP VIEW command Security features GRANT REVOKE A Guide to SQL, Eighth Edition
306
A Guide to SQL, Eighth Edition
Summary (continued) Indexes Make data retrieval more efficient CREATE INDEX DROP INDEX System catalog information SYSTABLES, SYSCOLUMNS, SYSVIEWS DBA_TABLES, DBA_TAB_COLUMNS, DBA_VIEWS A Guide to SQL, Eighth Edition
307
A Guide to SQL, Eighth Edition
Summary (continued) Integrity constraints ADD PRIMARY KEY ADD FOREIGN KEY CHECK A Guide to SQL, Eighth Edition
308
A Guide to SQL, Eighth Edition
Chapter Eight SQL Functions and Procedures 308
309
A Guide to SQL, Eighth Edition
Objectives Understand how to use functions in queries Use the UPPER and LOWER functions with character data Use the ROUND and FLOOR functions with numeric data Add a specific number of months or days to a date A Guide to SQL, Eighth Edition
310
Objectives (continued)
Calculate the number of days between two dates Use concatenation in a query Embed SQL commands in PL/SQL and T-SQL procedures Retrieve single rows using embedded SQL Update a table using embedded INSERT, UPDATE, and DELETE commands A Guide to SQL, Eighth Edition
311
Objectives (continued)
Use cursors to retrieve multiple rows in embedded SQL Manage errors in procedures containing embedded SQL commands Use SQL in a language that does not support embedded SQL commands Use triggers A Guide to SQL, Eighth Edition
312
Using SQL in a Programming Environment
SQL is a nonprocedural language Use simple commands to communicate tasks to computer PL/SQL is a procedural language Must provide step-by-step process for accomplishing tasks Can embed SQL in another language, such as PL/SQL or T-SQL (SQL Server) A Guide to SQL, Eighth Edition
313
Using SQL in a Programming Environment (continued)
Useful when needed tasks are beyond the capabilities of SQL Cannot embed SQL commands in Access programs A Guide to SQL, Eighth Edition
314
A Guide to SQL, Eighth Edition
Using Functions Aggregate functions Perform calculations based on groups of records SUM is an example Other SQL functions Affect single records Vary from one SQL implementation to another A Guide to SQL, Eighth Edition
315
A Guide to SQL, Eighth Edition
Character Functions UPPER function Displays a value in uppercase letters Function operates on an argument LOWER function Displays a value in lowercase letters Can use functions in WHERE clauses Access uses UCASE and LCASE A Guide to SQL, Eighth Edition
316
Character Functions (continued)
A Guide to SQL, Eighth Edition
317
A Guide to SQL, Eighth Edition
Number Functions ROUND Rounds values to a specified number of decimal places Requires two arguments FLOOR Truncates everything to the right of the decimal place Not supported by Access A Guide to SQL, Eighth Edition
318
Number Functions (continued)
A Guide to SQL, Eighth Edition
319
A Guide to SQL, Eighth Edition
Working with Dates ADD_MONTHS Adds a specific number of months to a date Has two arguments Access and SQL Server use DATEADD function to add months Add a specific number of days Use a simple calculation Can also subtract A Guide to SQL, Eighth Edition
320
Working with Dates (continued)
SYSDATE Obtains today’s date (Oracle) DATE() Obtains today’s date (Access) GETDATE() Obtains today’s date (SQL Server) A Guide to SQL, Eighth Edition
321
Working with Dates (continued)
A Guide to SQL, Eighth Edition
322
Working with Dates (continued)
A Guide to SQL, Eighth Edition
323
Working with Dates (continued)
A Guide to SQL, Eighth Edition
324
Concatenating Columns
Concatenate Combine two or more columns into a single expression Type two vertical lines (||) (Oracle) & symbol (Access) + symbol (SQL Server) RTRIM function Removes extra spaces to the right of a value A Guide to SQL, Eighth Edition
325
Concatenating Columns (continued)
A Guide to SQL, Eighth Edition
326
A Guide to SQL, Eighth Edition
Stored Procedures Useful in client/server systems Advantages Procedure is stored on server; DBMS compiles stored procedure; creates compiled, optimized code to run Convenience (reduces typing) Access does not support A Guide to SQL, Eighth Edition
327
Retrieving a Single Row and Column
A Guide to SQL, Eighth Edition
328
Retrieving a Single Row and Column (continued)
When executed, user will be prompted for a value for I_REP_NUM That value will be used to retrieve the last name of the sales rep whose number equals this value The results will be placed in the variable I_LAST_NAME This variable can be used in another program A Guide to SQL, Eighth Edition
329
Retrieving a Single Row and Column (continued)
Use CREATE PROCEDURE command %TYPE attribute ensures that variable has same data type as a particular column Procedural code located between BEGIN and END commands Each variable declaration and command as well as the word END are followed by semicolons The slash (/) at the end of the program appears on its own line A Guide to SQL, Eighth Edition
330
Retrieving a Single Row and Column (continued)
DBMS_OUTPUT is a package that contains multiple procedures To call procedure: Type BEGIN, the name of the procedure, argument in parentheses, END, semicolon,slash A Guide to SQL, Eighth Edition
331
Retrieving a Single Row and Column (continued)
A Guide to SQL, Eighth Edition
332
A Guide to SQL, Eighth Edition
Error Handling Use EXCEPTION clause Print an error message A Guide to SQL, Eighth Edition
333
Using Update Procedures
A procedure that updates data A Guide to SQL, Eighth Edition
334
Changing Data with a Procedure
A Guide to SQL, Eighth Edition
335
Deleting Data with a Procedure
A Guide to SQL, Eighth Edition
336
Selecting Multiple Rows with a Procedure
PL/SQL can process only one record at a time A Guide to SQL, Eighth Edition
337
A Guide to SQL, Eighth Edition
Using a Cursor A cursor is a pointer to a row in the collection of rows retrieved by a SQL command A cursor advances one row at a time to provide sequential one-record-at-a-time access to retrieved rows A Guide to SQL, Eighth Edition
338
Using a Cursor (continued)
The first step is to declare the cursor and describe the associated query in the declaration section CURSOR CUSTGROUP IS SELECT CUSTOMER_NUM, CUSTOMER_NAME FROM CUSTOMER WHERE REP_NUM = I_REP_NUM; Three commands are needed OPEN, FETCH, CLOSE A Guide to SQL, Eighth Edition
339
A Guide to SQL, Eighth Edition
Opening a Cursor OPEN command Opens cursor Causes query to be executed Makes results available to the program Prior to opening, there are no rows available to be fetched OPEN CUSTGROUP A Guide to SQL, Eighth Edition
340
Opening a Cursor (continued)
A Guide to SQL, Eighth Edition
341
Fetching Rows from a Cursor
FETCH command Advances cursor to next row in set of retrieved rows Places contents of row in indicated variables FETCH CUSTGROUP INTO I_CUSTOMER_NUM, I_CUSTOMER_NAME; Execution of fetch command produces only a single row A Guide to SQL, Eighth Edition
342
Fetching Rows from a Cursor (continued)
A Guide to SQL, Eighth Edition
343
Fetching Rows from a Cursor (continued)
A Guide to SQL, Eighth Edition
344
A Guide to SQL, Eighth Edition
Closing a Cursor CLOSE command Closes a cursor and deactivates it Data retrieved by execution of the query is no longer available A Guide to SQL, Eighth Edition
345
Writing a Complete Procedure Using a Cursor
A Guide to SQL, Eighth Edition
346
Writing a Complete Procedure Using a Cursor (continued)
A Guide to SQL, Eighth Edition
347
Using More Complex Cursors
Any SLQ query is legitimate in a cursor definition More complicated retrieval requirements result in greater benefits A Guide to SQL, Eighth Edition
348
Using More Complex Cursors (continued)
A Guide to SQL, Eighth Edition
349
A Guide to SQL, Eighth Edition
Advantages of Cursors Simplified coding in the program Programs with embedded SQL utilize the optimizer Programmer doesn’t worry about the best way to retrieve data Program doesn’t have to change even if the underlying structure does Cursor definition only changes; not procedural code A Guide to SQL, Eighth Edition
350
Using T-SQL in SQL Server
T-SQL or Transact-SQL Extended version of SQL Create stored procedures and use cursors A Guide to SQL, Eighth Edition
351
Retrieving a Single Row and Column
Must assign data type to parameters Arguments start Use EXEC command to call a procedure CREATE PROCEDURE usp_DISP_REP_NAME @repnum char(2) AS SELECT RTRIM(FIRST_NAME)+' '+RTRIM(LAST_NAME) FROM REP WHERE REP_NUM EXEC usp_DISP_REP_NAME'20' A Guide to SQL, Eighth Edition
352
Changing Data with a Stored Procedure
CREATE PROCEDURE usp_CHG_CUST_NAME @custnum char(3), @custname char(35) AS UPDATE CUSTOMER SET CUSTOMER_NAME WHERE CUSTOMER_NUM EXEC usp_CHG_CUST_NAME'842','All Season Shop' A Guide to SQL, Eighth Edition
353
Deleting Data with a Stored Procedure
CREATE PROCEDURE usp_DEL_ORDER @ordernum char(5) AS DELETE FROM ORDER_LINE WHERE ORDER_NUM FROM ORDERS A Guide to SQL, Eighth Edition
354
A Guide to SQL, Eighth Edition
Using a Cursor CREATE PROCEDURE usp_DISP_REP_CUST @repnum char(2) AS char(3) char(35) DECLARE mycursor CURSOR READ_ONLY FOR SELECT CUSTOMER_NUM, CUSTOMER_NAME FROM CUSTOMER WHERE REP_NUM OPEN mycursor FETCH NEXT FROM mycursor @custname WHILE = 0 BEGIN END CLOSE mycursor DEALLOCATE mycursor A Guide to SQL, Eighth Edition
355
Using More Complex Cursors
Declare all variables Declare cursor SELECT statement Open cursor Fetch While loop Close cursor Deallocate cursor A Guide to SQL, Eighth Edition
356
Using SQL in Microsoft Access
In Access, programs are written in Visual Basic Does not allow inclusion of SQL commands in the code If the SQL command is stored in string variable, use the DoCmd.RunSQL command A Guide to SQL, Eighth Edition
357
Deleting Data with Visual Basic
Place the SQL command in the procedure, including arguments A Guide to SQL, Eighth Edition
358
A Guide to SQL, Eighth Edition
Running the Code Normally run by calling it from another procedure or by associating it with an event Can be run by using the Immediate window Normally used for testing A Guide to SQL, Eighth Edition
359
Running the Code (continued)
A Guide to SQL, Eighth Edition
360
Updating Data with Visual Basic
Similar to the procedure to delete a sales rep, except: Need the UPDATE command Two arguments rather than one Two portions of the construction of the SQL command that involve variables A Guide to SQL, Eighth Edition
361
Updating Data with Visual Basic (continued)
A Guide to SQL, Eighth Edition
362
Inserting Data with Visual Basic
Process is similar Create the appropriate INSERT command in the strSQL variable Multiple arguments One for each value inserted A Guide to SQL, Eighth Edition
363
Finding Multiple Rows with Visual Basic
SELECT commands handled differently than in PL/SQL No cursors Handle results of query just as you would use a loop to process through the records on the table A Guide to SQL, Eighth Edition
364
Finding Multiple Rows with Visual Basic (continued)
A Guide to SQL, Eighth Edition
365
A Guide to SQL, Eighth Edition
Using a Trigger Procedure that is executed automatically in response to an associated database operation CREATE TRIGGER SQL commands between BEGIN and END NEW qualifier refers to row that is added OLD qualifier refers to row that was deleted or updated A Guide to SQL, Eighth Edition
366
Using a Trigger (continued)
A Guide to SQL, Eighth Edition
367
Using a Trigger (continued)
T-SQL (example of trigger after INSERT) CREATE TRIGGER ADD_ORDER_LINE ON ORDER_LINE AFTER INSERT AS decimal(3,0) = (SELECT NUM_ORDERED FROM INSERTED) UPDATE PART SET ON_0RDER = ON_ORDER A Guide to SQL, Eighth Edition
368
A Guide to SQL, Eighth Edition
Summary Functions Character (UPPER, LOWER) Numeric (ROUND, FLOOR) Date (ADD_MONTHS, SYSDATE) Concatenation RTRIM (||) lines Stored procedure Query saved in a file that users can execute later CREATE PROCEDURE A Guide to SQL, Eighth Edition
369
A Guide to SQL, Eighth Edition
Summary (continued) Variables Declare %TYPE attribute INTO clause in SELECT places results in variables INSERT, UPDATE, and DELETE in PL/SQL and T-SQL Cursors OPEN, FETCH, CLOSE A Guide to SQL, Eighth Edition
370
A Guide to SQL, Eighth Edition
Summary (continued) SQL commands in Access Create in string variable Run with DoCmd.RunSQL command Trigger Action that occurs automatically Stored and compiled on server Executed in response to a database operation A Guide to SQL, Eighth Edition
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.