Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Guide to SQL, Seventh Edition

Similar presentations


Presentation on theme: "A Guide to SQL, Seventh Edition"— Presentation transcript:

1 A Guide to SQL, Seventh Edition

2 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, Seventh Edition

3 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 parts ordered A Guide to SQL, Seventh Edition

4 The Premier Products Database
Premier 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, Seventh Edition

5 Required Data for Sales Reps
Number Last name First name Address Total commission Commission rate A Guide to SQL, Seventh Edition

6 Required Data for Customer
Customer number Name Address Current balance Credit limit Sales rep number A Guide to SQL, Seventh 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, Seventh Edition

8 A Guide to SQL, Seventh 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, Seventh 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, Seventh 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, Seventh Edition

12 Items Stored for Each Order
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, Seventh Edition

13 Sample Rep Table A Guide to SQL, Seventh Edition

14 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, Seventh Edition

15 Sample Customer Table A Guide to SQL, Seventh 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, Seventh Edition

17 A Guide to SQL, Seventh Edition

18 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, Seventh Edition

19 Sample Order Table A Guide to SQL, Seventh Edition

20 Order Table Example Seven orders listed by order number
Order date: 10/20/2007 Customer: 148 (Al’s Appliance and Sport) A Guide to SQL, Seventh Edition

21 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, Seventh Edition

22 A Guide to SQL, Seventh Edition

23 Alternate Order Table Example
Displays identical data in one table Each table row contains all 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, Seventh Edition

24 Issues with Alternate 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, Seventh Edition

25 Benefits of Order Lines 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, Seventh Edition

26 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, Seventh Edition

27 Branch Information Henry gathers specific information on each branch
Number Name Location Number of employees A Guide to SQL, Seventh Edition

28 Publisher Information
Henry gathers specific publisher information Identifying code Name City A Guide to SQL, Seventh Edition

29 A Guide to SQL, Seventh Edition

30 Author Information Henry gathers specific information for each author
Author number Last name First name A Guide to SQL, Seventh Edition

31 Book Information Henry gathers specific information for each book
Book ID code Title Publisher Type of book Price Paperback information A Guide to SQL, Seventh Edition

32 A Guide to SQL, Seventh Edition

33 Additional Information
Henry gathers specific information in the WROTE table Book code Author number Sequence, for books with multiple authors This table relates books and authors A Guide to SQL, Seventh Edition

34 Inventory Information
Henry gathers specific information in the INVENTORY table Book code Branch number On hand quantity This table indicates the number of copies currently on hand at a particular branch A Guide to SQL, Seventh Edition

35 A Guide to SQL, Seventh Edition

36 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, Seventh Edition

37 Marina Information MARINA table stores data on the two marinas
Marina number Name Street Address City, State, and Zip A Guide to SQL, Seventh Edition

38 Boat Owner Information
The marina also stores information on the boat owners in the OWNERS table Owner number Last and First names Street Address City, State, and Zip A Guide to SQL, Seventh Edition

39 Slip Information Information on the slips in each marina is stored in the MARINA_SLIP table Slip ID, Marina Number, Slip Number Length Rental fee Boat name and Boat type Owner number A Guide to SQL, Seventh Edition

40 A Guide to SQL, Seventh Edition

41 Service Information 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, Seventh Edition

42 A Guide to SQL, Seventh Edition

43 Summary Premiere Products Henry Books Alexamara Marina Group
Require rep, customer, parts, orders and order lines information Henry Books Requires branch, publisher, author, book, inventory and author sequence information Alexamara Marina Group Requires marina, owners, slips, service categories and service request information A Guide to SQL, Seventh Edition

44 A Guide to SQL, Seventh Edition

45 Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in Oracle, Microsoft Access, and MySQL Create tables using SQL A Guide to SQL, Seventh Edition

46 Objectives Identify and use data types to define columns in SQL tables
Understand and use nulls Add rows to tables Describe a table’s layout using SQL A Guide to SQL, Seventh Edition

47 Introduction Databases are found at school libraries, on the Internet, and other places where you retrieve data on a computer Learn concepts and terminology associated with relational model for database management Learn how to create a database by describing and defining tables and columns A Guide to SQL, Seventh Edition

48 Introduction SQL (Structured Query Language) is a widely used language for retrieving and manipulating data SQL was developed in the mid-1970’s for IBM under the name SEQUEL Renamed SQL in 1980 Most DBMSs use a version of SQL as their data manipulation language A Guide to SQL, Seventh Edition

49 Introduction You will learn to assign data types to columns and the use of null values You will learn how to load a database by creating tables and adding data to them You will learn how to describe a table’s layout using SQL A Guide to SQL, Seventh Edition

50 Relational Databases A relational database is a collection of tables
Tables are called relations This term is the basis for the name relational database A Guide to SQL, Seventh Edition

51 A Guide to SQL, Seventh Edition

52 A Guide to SQL, Seventh Edition

53 Entities, Attributes, and Relationships
An entity is a person, place, object, event, or idea for which you want to store and process data Premier Product’s entities are customers, orders, parts, and sales reps Entities for a school would be students, faculty, and classes A Guide to SQL, Seventh Edition

54 Entities, Attributes, and Relationships
Attribute is a character or property of an entity Premiere Products attributes for the entity “customer” are customer name, street, city, and so on Also called a field or column in many database systems A Guide to SQL, Seventh Edition

55 Entities, Attributes, and Relationships
A relationship is the association between entities At Premiere Products, there is a relationship between customers and sales reps One-to-many relationship Each sales rep has many customers Each customer has only one sales rep A Guide to SQL, Seventh Edition

56 Entities, Attributes, and Relationships
Premiere Products database One table for sales reps, one for customers, and so on for each entity Attributes become columns in each table Relationship is represented by using common columns in two or more tables A Guide to SQL, Seventh Edition

57 A Guide to SQL, Seventh Edition

58 Definitions A relation is a two-dimensional table in which:
Entries are single-valued Each column has a distinct name All values of the same attribute Order of columns and rows is immaterial Each row is distinct A Guide to SQL, Seventh Edition

59 Definitions A relational database is a collection of relations
A row in a table is called a record or a tuple Multiple entries in one position in a table are called a repeating group A Guide to SQL, Seventh Edition

60 Shorthand Representation
After the name of the table, the columns are listed within a set of parentheses 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) A Guide to SQL, Seventh Edition

61 Shorthand Representation
Not case-sensitive except when inserting character values in a table Use a period to separate the table and column name to avoid confusion The primary key uniquely identifies a row in a table Indicate primary key by underlining the column or collection of columns A Guide to SQL, Seventh Edition

62 Database Creation 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, Seventh Edition

63 Table and Column Name Restrictions
Names cannot exceed 18 characters In Oracle, can be up to 30 characters in length Must start with a letter Can contain letters, numbers, and underscores (_) Cannot contain spaces A Guide to SQL, Seventh Edition

64 Create Table Command A Guide to SQL, Seventh Edition

65 Create Table Command Table name is REP
Contains nine columns: REP_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, ZIP, COMMISSION, RATE REP_NUM is limited to two characters and is the primary key RATE column is limited to numbers, three digits with two decimal places A Guide to SQL, Seventh Edition

66 Create Table Command Commands are free-format; no rules stating specific words in specific positions Hit enter to move to the next line in a command Indicate the end of a command by typing a semicolon A Guide to SQL, Seventh Edition

67 Running SQL Commands Programs and individual preference determine method for running command Oracle 10g use SQL*Plus or SQL*Plus Worksheet Create queries in SQL view in Microsoft Access Commands are typed at prompt in MySQL A Guide to SQL, Seventh Edition

68 A Guide to SQL, Seventh Edition

69 A Guide to SQL, Seventh Edition

70 A Guide to SQL, Seventh Edition

71 A Guide to SQL, Seventh Edition

72 Editing SQL Commands Edit commands as you would in a word processor when using Oracle SQL*Plus Worksheet or Access SQL After making edits, click the Execute or Run button With Oracle SQL*Plus or MySQL the on-screen command must be edited to change it A Guide to SQL, Seventh Edition

73 Editing Oracle SQL*Plus
In Oracle SQL*Plus you must edit commands one line at a time The most recent command is stored in the command buffer (the buffer) Edit the command in the buffer by using editing commands A Guide to SQL, Seventh Edition

74 A Guide to SQL, Seventh Edition

75 A Guide to SQL, Seventh Edition

76 A Guide to SQL, Seventh Edition

77 Editing MySQL Commands
Most recent command is stored in memory area called statement history Edit command in statement history by using specific editing commands A Guide to SQL, Seventh Edition

78 A Guide to SQL, Seventh Edition

79 A Guide to SQL, Seventh Edition

80 Editing MySQL Commands
Press Up arrow key to go to top line Hit Enter key to move to next line if line is correct Use Right and Left arrow keys to move to point needing correction When line is correct hit Enter key If Enter is not hit on a line, that line will not be part of the revised command A Guide to SQL, Seventh Edition

81 Dropping a Table Another way to correct errors is to drop (delete) a table and start over Useful when table is created before errors are discovered Command is followed by the table to be dropped and a semicolon Data is deleted when a table is dropped A Guide to SQL, Seventh Edition

82 Data Types For each column, the type of data must be defined
Actual data types vary between SQL programs  there are some common types CHAR(n), DATE, DECIMAL(p,q), INTEGER, SMALLINT A Guide to SQL, Seventh Edition

83 Nulls A null is used as special value to represent situation when actual value is not known for a column Specify whether to allow nulls in the individual columns Nulls should not be allowed for primary key columns A Guide to SQL, Seventh Edition

84 Implementation of Nulls
NOT NULL clause is used in a 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, Seventh Edition

85 Loading a Table with Data
INSERT Command Adds rows to a table INSERT INTO followed by the table name VALUES command follows with specific values in parentheses Values for character columns are in single quotation marks A Guide to SQL, Seventh Edition

86 The Insert Command A Guide to SQL, Seventh Edition

87 Modifying the INSERT Command
To add new rows it is easier to modify previous insert command and execute it Oracle SQL*Plus Worksheet and Access SQL view, select the text, modify and execute Oracle SQL*Plus or MySQL, edit commands manually A Guide to SQL, Seventh Edition

88 A Guide to SQL, Seventh Edition

89 A Guide to SQL, Seventh Edition

90 A Guide to SQL, Seventh Edition

91 A Guide to SQL, Seventh Edition

92 A Guide to SQL, Seventh Edition

93 The INSERT Command with 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, then list only the non-null values after the VALUES command A Guide to SQL, Seventh Edition

94 The INSERT Command with Nulls
Enter only non-null values Precisely indicate values you are entering by listing the columns A Guide to SQL, Seventh Edition

95 Viewing Table Data SELECT command is complex
A simple version can display all the rows and columns in a table SELECT*FROM followed by the name of the table with the data you want to view As with other SQL commands, it ends with a semicolon A Guide to SQL, Seventh Edition

96 Correcting Errors in the Database
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, Seventh Edition

97 A Guide to SQL, Seventh Edition

98 A Guide to SQL, Seventh Edition

99 Saving SQL Commands Allows you to use commands again without retyping
Different methods for each SQL implementation you are using Oracle SQL*Plus and SQL*Plus Worksheet use a script file Access saves queries as objects MySQL uses an editor to save text files A Guide to SQL, Seventh Edition

100 Creating the Remaining Tables
Execute appropriate CREATE TABLE and INSERT commands Save these commands on your hard drive or a floppy disk for backup A Guide to SQL, Seventh Edition

101 A Guide to SQL, Seventh Edition

102 A Guide to SQL, Seventh Edition

103 Describing a Table When working with a table, there may not be access to the CREATE TABLE command used for the table Examining the table’s structure will show details about the columns Each DBMS has a method to examine a table’s structure A Guide to SQL, Seventh Edition

104 Describing a Table Oracle SQL*Plus and SQL*Plus Worksheet use DESCRIBE command Access uses the Documenter MySQL uses the SHOW COLUMNS command A Guide to SQL, Seventh Edition

105 Summary Use the CREATE TABLE command to create tables
DROP TABLE, INSERT, SELECT, UPDATE and DELETE commands are used to edit tables Display a table’s structure and layout for information A Guide to SQL, Seventh Edition

106 A Guide to SQL, Seventh Edition

107 Objectives Retrieve data from a database using SQL commands
Use compound conditions Use computed columns Use the SQL LIKE operator Use the SQL IN operator Sort data using the ORDER BY clause A Guide to SQL, Seventh Edition

108 Objectives Sort data using multiple keys and in ascending and descending order Use SQL aggregate functions Use subqueries Group data using the GROUP BY clause Select individual groups of data using the HAVING clause Retrieve columns with null values A Guide to SQL, Seventh Edition

109 Constructing Simple Queries
Important feature of DBMS is ability to answer a wide variety of questions about the data A query is a question represented in a way that the DBMS can understand Use the SELECT command to query a database A Guide to SQL, Seventh Edition

110 Constructing Simple Queries
SELECT-FROM-WHERE is the basic form of the command SELECT clause is the list of columns to include in query results FROM clause is the name of the table with the data being queried WHERE clause is optional, listing any conditions to apply to the data A Guide to SQL, Seventh Edition

111 Retrieving Certain Columns and Rows
A command can retrieve specified columns and all rows List the number, name and balance of all customers No WHERE clause is needed, because all customers are requested A Guide to SQL, Seventh Edition

112 A Guide to SQL, Seventh Edition

113 Retrieving All Columns and Rows
Use an asterisk (*) to indicate all columns in the SELECT clause Results will list all columns in the order in the description when the table was created List columns in SELECT clause to present columns in a different order A Guide to SQL, Seventh Edition

114 A Guide to SQL, Seventh Edition

115 Using a WHERE Clause WHERE clause is used to retrieve rows that satisfy some condition What is the name of customer number 148? A simple condition form: column name, comparison operator, and then either a column name or a value A Guide to SQL, Seventh Edition

116 A Guide to SQL, Seventh Edition

117 A Guide to SQL, Seventh Edition

118 Using a WHERE Clause Character values in SQL are case sensitive
“Grove” is different than “grove” Simple conditions can compare columns WHERE BALANCE > CREDIT_LIMIT A Guide to SQL, Seventh Edition

119 Using Compound Conditions
Compound conditions connect two or more simple conditions with AND, OR, and NOT operators AND operator shows results that all simple conditions are true OR operator shows results that any simple condition is true NOT operator reverses the truth of the original condition A Guide to SQL, Seventh Edition

120 A Guide to SQL, Seventh Edition

121 A Guide to SQL, Seventh Edition

122 A Guide to SQL, Seventh Edition

123 A Guide to SQL, Seventh Edition

124 Using the BETWEEN Operator
Not an essential feature in SQL Same results can be obtained without it Does make certain SELECT commands simpler to construct BETWEEN operator is inclusive When using BETWEEN 2000 and 5000, values of or 5000 would be true A Guide to SQL, Seventh Edition

125 A Guide to SQL, Seventh Edition

126 A Guide to SQL, Seventh Edition

127 Using Computed Columns
Computed column does not exist in the database but is computed using data in existing columns Computations can involve arithmetic operators + for addition - for subtraction * for multiplication / for division A Guide to SQL, Seventh Edition

128 A Guide to SQL, Seventh Edition

129 Using the LIKE Operator
Used to retrieve data where there may not be an exact match using wildcards 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, Seventh Edition

130 Using the IN Operator IN operator allows for concise phrasing of certain conditions A Guide to SQL, Seventh Edition

131 Sorting ORDER BY clause to list data in a specific order
Column on which data is to be sorted is the sort key Use ORDER BY clause followed by sort key Rows are sorted in ascending order unless another order is specified A Guide to SQL, Seventh Edition

132 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, Seventh Edition

133 A Guide to SQL, Seventh Edition

134 Using Functions Aggregate functions calculate sums, averages, counts, minimum and maximum values to groups of rows A Guide to SQL, Seventh Edition

135 Using the COUNT Function
Counts the number of rows in a table Use of an asterisk allowed to represent any column A Guide to SQL, Seventh Edition

136 Using the SUM Function Used to calculate totals of columns
Column to be summed must be specified and must be numeric AVG, MAX, and MIN functions are similar, resulting in different statistics Null values are ignored and not used in these calculations A Guide to SQL, Seventh Edition

137 Using the DISTINCT Operator
Used to ensure uniqueness in the data results A Guide to SQL, Seventh Edition

138 A Guide to SQL, Seventh Edition

139 A Guide to SQL, Seventh Edition

140 Nesting Queries Some queries will take two or more steps to obtain desired results A subquery is an inner query placed inside another query Outer query can use results of the subquery to find its results A Guide to SQL, Seventh Edition

141 A Guide to SQL, Seventh Edition

142 A Guide to SQL, Seventh Edition

143 Grouping Grouping creates groups of rows that share common characteristics Calculations in the SELECT command are performed for entire groups Data can be GROUPED BY a particular column, such as REP_NUM and then the statistics are calculated One line of output is produced for each group A Guide to SQL, Seventh Edition

144 Using a HAVING Clause The HAVING clause is used to restrict groups that will be included A Guide to SQL, Seventh Edition

145 Nulls Sometimes a condition involves a column that can be null
A Guide to SQL, Seventh Edition

146 A Guide to SQL, Seventh Edition

147 Summary Create queries that retrieve data from single tables using SELECT commands Comparison operators: =, >,=>,<,=<, or <>, or != Compound conditions using AND,OR, and NOT Use the BETWEEN operator Use the LIKE operator A Guide to SQL, Seventh Edition

148 Summary Use the IN operator Use and ORDER BY clause to sort data
Process aggregate functions with COUNT, SUM,AVG,MAX, and MIN Use the DISTINCT operator and subqueries Use GROUP BY, HAVING and IS NULL A Guide to SQL, Seventh Edition

149 A Guide to SQL, Seventh Edition

150 Objectives Use joins to retrieve data from more than one table
Use the IN and EXISTS operators to query multiple tables Use a subquery within a subquery Use an alias A Guide to SQL, Seventh Edition

151 Objectives 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, Seventh Edition

152 Querying Multiple Tables
When querying more than one table, the tables must be joined Join tables by finding columns with matching data Join tables by using a condition in the WHERE clause A Guide to SQL, Seventh Edition

153 Joining Two Tables In the SELECT clause, list all columns you want to display In the FROM clause, list all tables involved in the query In the WHERE clause, restrict to the rows that have common values in matching columns A Guide to SQL, Seventh Edition

154 A Guide to SQL, Seventh Edition

155 A Guide to SQL, Seventh Edition

156 A Guide to SQL, Seventh Edition

157 Comparing JOIN, IN, and EXISTS
Tables can be joined using IN or EXISTS clause Use IN operator with a subquery Use the EXISTS operator to retrieve data from more than one table A Guide to SQL, Seventh Edition

158 A Guide to SQL, Seventh Edition

159 A Guide to SQL, Seventh Edition

160 A Guide to SQL, Seventh Edition

161 A Guide to SQL, Seventh Edition

162 Correlated Subquery Subquery involves a table listed in the outer query In Figure 4.7 the ORDERS table, listed in the FROM clause of the outer query, is used in the subquery You need to qualify ORDER_NUM column in subquery as ORDERS.ORDER_NUM A Guide to SQL, Seventh Edition

163 Correlated Subquery For each row in the ORDERS table
Subquery executed using the value of ORDERS.ORDER_NUM that appears in the row The inner query makes a list of rows in the ORDER_LINE table Where ORDER_LINE.ORDER_NUM matches this value and In which PART_NUM is equal to DR93 A Guide to SQL, Seventh Edition

164 Using a Subquery within a Subquery
A nested subquery is a subquery within a subquery SQL evaluates the queries from the innermost query to the outermost It is possible that there is more than one approach to formulation of the queries Many DMBS have optimizers that analyze queries for efficiency A Guide to SQL, Seventh Edition

165 A Guide to SQL, Seventh Edition

166 Using an Alias An alias is an alternate name for a table
Used when tables are listed in the FROM clause Created by typing the name of the table, hitting a space, then typing the name of the alias Allows for simplicity A Guide to SQL, Seventh Edition

167 Joining a Table to Itself
A self-join is when you are joining a table to itself A second use for using an alias Used when comparing records within one table Alias allows you to treat one table as two separate tables A Guide to SQL, Seventh Edition

168 A Guide to SQL, Seventh Edition

169 Using a Self-Join on a Primary Key
It is possible to create a self-join that involves the primary key of the table Just as in previous examples, you would list the table twice in the FROM clause with aliases A Guide to SQL, Seventh Edition

170 A Guide to SQL, Seventh Edition

171 Joining Several Tables
Condition shows how the columns are related for each pair of tables A Guide to SQL, Seventh Edition

172 Joining Several Tables Step-By-Step
In the SELECT clause list all the columns to display Qualify the column name if needed In the 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, Seventh Edition

173 Joining Several Tables Step-By-Step
Take one pair of related tables at a time Indicate in the WHERE clause the condition that relates the tables Join conditions with the AND operator Include any additional conditions in the WHERE clause Connect them with the AND operator A Guide to SQL, Seventh Edition

174 Set Operations Set operations are used for taking the union, intersection, and differences of two tables The union of two tables is a table containing every row that is in either the first table, the second table, or both tables A Guide to SQL, Seventh Edition

175 Set Operations The intersection (intersect) of two tables is a table containing all rows that are in both tables The difference (minus) of two tables is the set of all rows that are in the first tables but are not in the second table A Guide to SQL, Seventh Edition

176 Restrictions to Set Operations
Requirements for tables to be union compatible Have the same number of columns AND Their corresponding columns have identical data types and lengths A Guide to SQL, Seventh Edition

177 Special Operations Inner Join Outer Join
A join that compares the tables in the FROM clause and lists on those rows that satisfy the condition in the WHERE clause Outer Join A join that lists all the rows from one of the tables in a join, regardless of matching A Guide to SQL, Seventh Edition

178 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, Seventh Edition

179 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, Seventh Edition

180 A Guide to SQL, Seventh Edition

181 Summary Join tables with various methods
A subquery can contain another subquery An alias can be used to simplify the SQL command as well to create self join UNION, INTERSECT, MINUS commands are introduced To form a product of two tables, include both tables in the FROM clause and omit the WHERE clause A Guide to SQL, Seventh Edition

182 A Guide to SQL, Seventh Edition

183 Objectives Create a new table from an existing table
Change data using the UPDATE command Add new data using the INSERT command Use the COMMIT and ROLLBACK commands to make permanent data updates or to reverse updates A Guide to SQL, Seventh Edition

184 Objectives Understand transactions and the role of COMMIT and ROLLBACK in supporting transactions Delete data using the DELETE command Use nulls in UPDATE commands Change the structure of an existing table Drop a table A Guide to SQL, Seventh Edition

185 Creating a New Table from an Existing Table
Possible to create a new table from existing table Use CREATE TABLE command Create a SELECT command to select the desired data You can add query results to the table by placing this SELECT command in an INSERT command A Guide to SQL, Seventh Edition

186 A Guide to SQL, Seventh Edition

187 A Guide to SQL, Seventh Edition

188 Changing Existing Data in a Table
The UPDATE command can change rows where specified conditions are true Command format UPDATE the name of the table to be updated SET the name of the column to be updated = and the new value A Guide to SQL, Seventh Edition

189 A Guide to SQL, Seventh Edition

190 Adding New Rows to an Existing Table
You can use the existing value in a column to calculate an update The INSERT command can be used to update table data A SELECT command shows the row was successfully added A Guide to SQL, Seventh Edition

191 A Guide to SQL, Seventh Edition

192 A Guide to SQL, Seventh Edition

193 Commit and Rollback Updates to a table are only temporary and can be cancelled at any time during the 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, Seventh Edition

194 Transactions A transaction is a logical unit of work
A sequence of steps that accomplish a single task Essential that the entire sequence is completed successfully COMMIT and ROLLBACK commands support transactions A Guide to SQL, Seventh Edition

195 Transaction Support 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, Seventh Edition

196 Delete Existing Rows from a Table
Use the DELETE command to delete data from the database Command format DELETE followed by the table from which the row(s) is to be deleted Next, use a WHERE clause with a condition to select the row(s) to delete All rows satisfying the condition will be deleted A Guide to SQL, Seventh Edition

197 A Guide to SQL, Seventh Edition

198 Executing a Rollback ROLLBACK command returns data to its original state All updates made prior to the previous commit are still reflected in the data A Guide to SQL, Seventh Edition

199 Changing a Value in a Column to Null
Command for changing the 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, Seventh Edition

200 A Guide to SQL, Seventh Edition

201 Changing a Table’s Structure
Relational DBMS allow changes to table 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, Seventh Edition

202 ALTER TABLE Command ALTER TABLE command allows for changing a table’s structure Use the ADD clause to add a new column ADD clause is followed by the name of the column to be added, followed by its characteristics A Guide to SQL, Seventh Edition

203 ADD Clause Value is needed in the new column
Simplest approach for the DBMS is to assign NULL as the value Some systems allow for the specification of an initial value ADD Cust_Type CHAR(1) INIT = R Others require an UPDATE command A Guide to SQL, Seventh Edition

204 A Guide to SQL, Seventh Edition

205 A Guide to SQL, Seventh Edition

206 DESCRIBE Command Command describes the table, including the addition of new column Access uses Documentor MySQL uses SHOW COLUMNS A Guide to SQL, Seventh Edition

207 A Guide to SQL, Seventh Edition

208 MODIFY Clause MODIFY clause of the ALTER TABLE command changes the characteristics of existing columns Can be used to change a column that currently rejects null values Use NULL in place of NOT NULL A Guide to SQL, Seventh Edition

209 A Guide to SQL, Seventh Edition

210 A Guide to SQL, Seventh Edition

211 Making Complex Changes
Changes to table structure may be beyond the capabilities of DBMS Eliminate column Change column order Combine data from two tables to one Reduce the size of a column Change data type A Guide to SQL, Seventh Edition

212 Making Complex Changes
Use the CREATE TABLE command to describe the new table Insert values into new table with the INSERT command and the appropriate SELECT command A Guide to SQL, Seventh Edition

213 Dropping a Table Use the DROP TABLE command to delete a table
Permanently removes the table and all its data from the database A Guide to SQL, Seventh Edition

214 Summary CREATE TABLE command is used to make a new table from an existing table UPDATE command to change data INSERT command adds new rows COMMIT command saves changes ROLLBACK reverses changes DELETE command deletes rows SET clause used to make values NULL A Guide to SQL, Seventh Edition

215 Summary DELETE command deletes rows
SET clause used to make values NULL Change a specific value to null with a condition to select the row Add a column to a table with ALTER TABLE command and the ADD clause Change a table with the ALTER TABLE command and the MODIFY clause A Guide to SQL, Seventh Edition

216 A Guide to SQL, Seventh Edition

217 Objectives Understand, create, and drop views
Recognize the benefits of using views Grant and revoke user’s database privileges Understand the purpose, advantages, and disadvantages of using an index A Guide to SQL, Seventh Edition

218 Objectives 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, Seventh Edition

219 Views A view is an application program’s or individual user’s picture of the database Base tables are the existing, permanent tables in a relational database A view is a derived table because data in it is retrieved from the base table A Guide to SQL, Seventh Edition

220 Views To user, a view appears as an actual table, but it is not
A view usually includes less information than the full database Its use represents a great simplification Provides a measure of security by omitting sensitive information unavailable to user A Guide to SQL, Seventh Edition

221 Defining Views A view is defined by creating a defining query
Indicates rows and columns to include Use CREATE VIEW command CREATE VIEW, followed by the name of the view, AS, and then a query A Guide to SQL, Seventh Edition

222 Defining Views MySQL does not support views at this time
Access users would create the defining query and save the query with view name Data shown in the view does not exist in this form, nor will it ever Not a temporary table A Guide to SQL, Seventh Edition

223 A Guide to SQL, Seventh Edition

224 A Guide to SQL, Seventh Edition

225 Queries Involving Views
If a query involves a view, SQL changes the query to select data from the table in the database that created the view DBMS does not execute the query in the form Entered query is merged with original query that defined the view to create the final query that is executed A Guide to SQL, Seventh Edition

226 The query executed by SQL
A Guide to SQL, Seventh Edition

227 Renaming Columns In a View
Column names can be assigned in new view Include new column names in parentheses, following the name of the view Output will display new column names A Guide to SQL, Seventh Edition

228 A Guide to SQL, Seventh Edition

229 View Joining Two Tables
Defining query of a view can be any valid SQL query A view can join two or more tables A Guide to SQL, Seventh Edition

230 A Guide to SQL, Seventh Edition

231 A View with Statistics A view can involve statistics
A Guide to SQL, Seventh Edition

232 Benefits of Views Views provide data independence
Views can often be used even after database structure changes Different users can view same data differently A view can contain only those columns required by a given user A Guide to SQL, Seventh Edition

233 Row-and-Column Subsets
When attempting to add a row to a row-and-column subset view, the DBMS must determine how to enter data Provided every column not included in a view can accept nulls, use INSERT Data may be rejected on some attempts when problems arise A Guide to SQL, Seventh Edition

234 Row-and-Column Subsets
Updates or deletes are not a problem in this view Not every row-and-column subsets are updatable A Guide to SQL, Seventh Edition

235 Joins Views that involve joins of base tables can cause problems at update A Guide to SQL, Seventh Edition

236 A Guide to SQL, Seventh Edition

237 Updatable Views Updatable view is when a view is derived by joining two tables on primary key of each table Views involving joins by matching the primary key of one table with a column that is not the primary key are not updatable More severe problems are encountered if neither of the join columns is a primary key A Guide to SQL, Seventh Edition

238 Statistics Most difficult views to update are those that involve statistics You can not add rows to a view that includes calculations A Guide to SQL, Seventh Edition

239 Dropping a View Remove a view that is no longer needed with DROP VIEW command The DROP VIEW command removes only the view definition Table and data remain unchanged A Guide to SQL, Seventh Edition

240 Security Security is the prevention of unauthorized access to a database Some may be able to retrieve and update anything in a database Others may be able to retrieve data but not change data Others may be able to access only a portion of data A Guide to SQL, Seventh Edition

241 Access Using the GRANT Command
Main mechanism for providing access to a database is the GRANT command 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, Seventh Edition

242 Using the REVOKE Command
Database administrator uses the REVOKE command to remove privileges from users Format is similar to GRANT command A Guide to SQL, Seventh Edition

243 Indexes An index speeds up the searching of tables
Similar to an index in a book Indexes are more complicated than that shown in the figures A Guide to SQL, Seventh Edition

244 A Guide to SQL, Seventh Edition

245 Indexes The DBMS system manages indexes
User determines the columns on which to build indexes Disadvantages Index occupies disk space DBMS must update the index as data is entered A Guide to SQL, Seventh Edition

246 A Guide to SQL, Seventh Edition

247 Dropping an Index The command to drop or delete an index is DROP INDEX
DROP INDEX followed by the name of the index to drop Permanently deletes index A Guide to SQL, Seventh Edition

248 Unique Indexes To ensure uniqueness of non-primary key data, you can create a unique index Command is CREATE UNIQUE INDEX A unique index will reject any update that would cause a duplicate value in the specified column A Guide to SQL, Seventh Edition

249 System Catalog Information about tables in the database is kept in the system catalog or data dictionary Describes types of items kept in the catalog Also describes the way in which you can query it to access information about the database structure A Guide to SQL, Seventh Edition

250 System Catalog The DBMS automatically maintains system catalog
SYSTABLES, information about the tables known to SQL SYSCOLUMNS, information about the columns within those tables SYSVIEWS, information about the views that have been used A Guide to SQL, Seventh Edition

251 A Guide to SQL, Seventh Edition

252 A Guide to SQL, Seventh Edition

253 A Guide to SQL, Seventh Edition

254 A Guide to SQL, Seventh Edition

255 Integrity Rules in SQL An integrity constraint is a rule for the data in the database Examples in Premier 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, Seventh Edition

256 Integrity Support Integrity support is the process of specifying integrity constraints for the database Clauses to support three types of integrity constraints that can be specified within a CREATE TABLE or ALTER TABLE command A Guide to SQL, Seventh Edition

257 Adding and Changing Integrity Constraints
An ALTER TABLE command is followed by ADD to indicate the addition of the constraint To change an integrity constraint, simply enter a new constraint New constraint will immediately replace the original A Guide to SQL, Seventh Edition

258 Types of Constraints Primary keys Foreign keys Legal values
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, Seventh Edition

259 A Guide to SQL, Seventh Edition

260 A Guide to SQL, Seventh Edition

261 Parent and Child When specifying a foreign key, the table containing the foreign key is the child Table referenced by the foreign key is the parent A Guide to SQL, Seventh Edition

262 CHECK Clause The CHECK clause of the ALTER TABLE command is used to ensure only legal values satisfying a particular condition are allowed in a given column Check (Class in (‘AP’, ‘HW’, ‘SG’) ) or Check (Class = ‘AP’ OR CLASS = ‘HW’ OR CLASS = ‘SG’) A Guide to SQL, Seventh Edition

263 A Guide to SQL, Seventh Edition

264 A Guide to SQL, Seventh Edition

265 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 Calculate the number of days between two dates Use concatenation in a query A Guide to SQL, Seventh Edition

266 Objectives Create a view for a report Create a query for a report
Change column headings and formats in a report Add a title to a report Group data in a report Include totals and subtotals in a report Send a report to a file that can be printed A Guide to SQL, Seventh Edition

267 Using Functions Using GROUP BY function with aggregate functions will provide sums for each record in a group Other functions are available that work with single records Functions vary among applications A Guide to SQL, Seventh Edition

268 Character Functions Several functions work with character data
UPPER function for changing a value to uppercase letters LOWER function changes values to lowercase letters A Guide to SQL, Seventh Edition

269 Number Functions Number functions affect numeric data
ROUND function rounds values to a specified number of places Has two arguments: the value to be rounded and the number of decimal places FLOOR function removes values to the right of the decimal point A Guide to SQL, Seventh Edition

270 Working With Dates Functions and calculations are used for manipulating dates ADD_MONTHS function allows for adding a specific number of months to a date Has two arguments: date to add to and the number of months to add In Access, use DATEADD function In MySQL, use ADDDATE function A Guide to SQL, Seventh Edition

271 Working With Dates No function is needed to add a specific number of days to a date In Access, use the DATEADD function with the letter “d” as the time interval In MySQL, use the ADDDATE function with the DAY interval A Guide to SQL, Seventh Edition

272 A Guide to SQL, Seventh Edition

273 Working With Dates Use SYSDATE to obtain today’s date
A Guide to SQL, Seventh Edition

274 Concatenating Columns
Concatenation is the process of combining two or more character columns into a single expression In Access, use the & symbol Select REP_NUM, FIRST_NAME&LAST_NAME FROM REP; In MySQL, use the CONCAT function Select REP_NUM,CONCAT(FIRST_NAME, LAST_NAME) FROM REP; A Guide to SQL, Seventh Edition

275 A Guide to SQL, Seventh Edition

276 Creating and Using Scripts
Saving commands in a script file eliminates retyping Creating views Entering report formatting command When creating a report you typically create a view and three files Script to create the view Script to format the report Report output A Guide to SQL, Seventh Edition

277 Naming Conventions Save script to create the view with the view name
SLSR_REPORT as SLSR_REPORT_VIEW.sql Save the script to format the view SLSR_REPORT as SLSR_REPORT_FORMAT.sql Save the file with report output SLSR_REPORT as SLSR_REPORT_OUTPUT.sql A Guide to SQL, Seventh Edition

278 Running Script Files Example: @SLSR_REPORT
To run a script file, followed by the file name Script files can be saved to any storage location Scripts allow you to develop your report in stages A Guide to SQL, Seventh Edition

279 A Guide to SQL, Seventh Edition

280 Creating the Data for the Report
To produce a report, run a SELECT command to create data to use in report In the following example, rows in output are wider than the screen Each row is displayed on two lines A Guide to SQL, Seventh Edition

281 A Guide to SQL, Seventh Edition

282 Changing Column Headings
Column headings can be changed to improve readability Type the COLUMN command followed by the name of the column to change Follow with the HEADING clause and new heading To break a heading on two lines, use single vertical line (|) A Guide to SQL, Seventh Edition

283 A Guide to SQL, Seventh Edition

284 A Guide to SQL, Seventh Edition

285 Changing Column Formats
COLUMN command and FORMAT clause work together A Guide to SQL, Seventh Edition

286 A Guide to SQL, Seventh Edition

287 Adding a Title to a Report
TTITLE command will place a title at the top BTITLE command will place a title at the bottom Desired title is placed within single quotation marks To format title with line breaks, use single vertical line (|) A Guide to SQL, Seventh Edition

288 Adding a Title to a Report
Adjust line size with SET LINESIZE command Line size is the maximum number of characters each line can contain Adjust the number of lines per page with SET PAGESIZE command A Guide to SQL, Seventh Edition

289 Grouping Data in a Report
Group data in a report by using BREAK command BREAK command identifies a column on which to group data Value in the column is displayed only at the beginning of the group It is possible to specify the number of blank lines following a group A Guide to SQL, Seventh Edition

290 A Guide to SQL, Seventh Edition

291 A Guide to SQL, Seventh Edition

292 Including Totals and Subtotals in a Report
Subtotal is a total that appears after each group To calculate a subtotal, include BREAK command to group the rows COMPUTE command indicates computation for subtotal Statistical functions are used to calculate the values A Guide to SQL, Seventh Edition

293 A Guide to SQL, Seventh Edition

294 A Guide to SQL, Seventh Edition

295 A Guide to SQL, Seventh Edition

296 Sending the Report to a File
SPOOL command is used in Oracle to create a report output file This file has many uses: Printing Editing Importing into a document Other options A Guide to SQL, Seventh Edition

297 The SPOOL Command Sends output of subsequent commands to designated file Final command of SPOOL OFF turns off spooling and stops further output to designated file Include path name to save output file to a specific drive or folder A Guide to SQL, Seventh Edition

298 A Guide to SQL, Seventh Edition

299 A Guide to SQL, Seventh Edition

300 A Guide to SQL, Seventh Edition

301 Summary Use of functions Perform calculations with dates
UPPER and LOWER ROUND and FLOOR Perform calculations with dates Concatenate columns Commands to create and format reports A Guide to SQL, Seventh Edition

302 A Guide to SQL, Seventh Edition

303 Objectives Embed SQL commands in PL/SQL programs
Retrieve single rows using embedded SQL Update a table using embedded INSERT, UPDATE, and DELETE commands Use cursors to retrieve multiple rows in embedded SQL A Guide to SQL, Seventh Edition

304 Objectives Update a database using cursors
Manage errors in programs containing embedded SQL commands Use SQL in a language that does not support embedded SQL commands A Guide to SQL, Seventh Edition

305 Introduction A procedural language requires a step-by-step process to accomplish tasks You can embed, or include, SQL commands in the programs using procedural languages Useful when needed tasks are beyond the capabilities of SQL A Guide to SQL, Seventh Edition

306 Using Prompt Variables
Sources of input for SQL commands Onscreen form Passed as arguments from procedure Prompt variables Prompt variables are when user is prompted to enter a value when the program is run Precede the variable with an “&” A Guide to SQL, Seventh Edition

307 A Guide to SQL, Seventh Edition

308 PL/SQL Programs Embed SQL commands in PL/SQL programs
Create and save the programs as script files Run the script files to run the programs A Guide to SQL, Seventh Edition

309 Retrieving a Single Row and Column
To place the results of a command in a variable, use the INTO clause SELECT LAST_NAME INTO I_LAST_NAME FROM REP WHERE REP_NUM = ‘&I_REP_NUM;’ A Guide to SQL, Seventh Edition

310 Retrieving a Single Row and Column
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, Seventh Edition

311 Retrieving a Single Row and Column
Procedure uses one argument and produces a single line of text containing this argument output To see the output, execute the command SET SERVEROUTPUT ON Include this command in the PL/SQL program to ensure it will be executed A Guide to SQL, Seventh Edition

312 A Guide to SQL, Seventh Edition

313 Retrieving a Single Row and Column
Procedural code are commands that specify exactly what program is to do Procedural code located between BEGIN and END commands Each variable declaration and command as well as the word END are followed by semicolons A Guide to SQL, Seventh Edition

314 Retrieving a Single Row and Column
The slash (/) at the end of the program appears on its own line When the script is run, the slash causes commands in the program to be executed immediately With the slash, commands are only loaded into memory Typing the slash runs the program A Guide to SQL, Seventh Edition

315 A Guide to SQL, Seventh Edition

316 Using the %TYPE Attribute
The %TYPE attribute ensures the variable has the same type as a particular column in a table Do not enter a data type  it is automatically assigned from the corresponding column I_REP_NUM REP.REP_NUM%TYPE A Guide to SQL, Seventh Edition

317 Retrieving a Single Row from a Join
Use embedded SQL commands to join tables A Guide to SQL, Seventh Edition

318 Inserting a Row into a Table
When updating a database from the PL/SQL program, use appropriate SQL commands A Guide to SQL, Seventh Edition

319 A Guide to SQL, Seventh Edition

320 Changing a Single Row in a Table
Use the SQL command to insert rows in a database A Guide to SQL, Seventh Edition

321 Deleting Rows from a Table
SQL commands are used to delete rows from a table A Guide to SQL, Seventh Edition

322 Multiple-Row Select PL/SQL can process only one record at a time
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, Seventh Edition

323 Using Cursors 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, Seventh Edition

324 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, Seventh Edition

325 A Guide to SQL, Seventh Edition

326 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 I_CUSTOMER_NUM, I_CUSTOMER_NAME; Execution of fetch command produces only a single row A Guide to SQL, Seventh Edition

327 A Guide to SQL, Seventh Edition

328 A Guide to SQL, Seventh Edition

329 Closing a Cursor CLOSE command Closes a cursor Deactivates it
Data retrieved by execution of the query is no longer available A Guide to SQL, Seventh Edition

330 A Guide to SQL, Seventh Edition

331 A Guide to SQL, Seventh Edition

332 More Complex Cursors Any SLQ query is legitimate in a cursor definition More complicated retrieval requirements result in greater benefits A Guide to SQL, Seventh Edition

333 A Guide to SQL, Seventh Edition

334 A Guide to SQL, Seventh Edition

335 Advantages of Cursors Simplified coding in the program
Progams with embedded SQL utilizes 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, Seventh Edition

336 Updating Cursors Update the rows encountered in processing cursors with FOR UPDATE OF A Guide to SQL, Seventh Edition

337 A Guide to SQL, Seventh Edition

338 Error Handling Handle errors with the EXCEPTION command
A Guide to SQL, Seventh Edition

339 Using SQL in Microsoft Access Programs
In Access, programs are written in Visual Basic Does not allow inclusion of SQL commands in the code If the SQL command is store in string variable, use the DoCmd.RunSQL command A Guide to SQL, Seventh Edition

340 Deleting Rows DELETE FROM REP WHERE REP_NUM = ’20’
Place the SQL command in the procedure, including arguments Example DELETE FROM REP WHERE REP_NUM = ’20’ A Guide to SQL, Seventh Edition

341 A Guide to SQL, Seventh Edition

342 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 for testing A Guide to SQL, Seventh Edition

343 A Guide to SQL, Seventh Edition

344 Updating Rows 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, Seventh Edition

345 A Guide to SQL, Seventh Edition

346 Inserting Rows Process is similar
Create the appropriate INSERT command in the strSQL variable Multiple arguments Once for each value inserted A Guide to SQL, Seventh Edition

347 Finding Rows 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, Seventh Edition

348 A Guide to SQL, Seventh Edition

349 A Guide to SQL, Seventh Edition

350 Summary How to embed SQL commands in PL Created programs
Retrieved single rows Inserted new rows Changed and deleted existing rows Cursors to update database Error Handling Using SQL command in Access A Guide to SQL, Seventh Edition


Download ppt "A Guide to SQL, Seventh Edition"

Similar presentations


Ads by Google