Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL Objectives • Introduce Structured Query Language (SQL) • Use simple and compound conditions in SQL • Use computed fields in SQL • Use built-in SQL functions • Use subqueries in SQL 2 Objectives (continued) • Group records in SQL • Join tables using SQL • Perform union operations in SQL • Use SQL to update database data • Use an SQL query to create a table in a database 3 Introduction • SQL (Structured Query Language) – Allows users to query a relational database – Must enter commands to obtain the desired results – Standard language for relational database manipulation 4 Getting Started with SQL • If you are completing the work in this chapter using Microsoft Office Access 2007, Microsoft Office Access 2010, or MySQL version 4.1 or higher, the following sections contain specific information about your DBMS 5 Getting Started with Microsoft Office Access 2007 and 2010 • If you are using the Access 2007 or 2010 version of the Premiere Products database provided with the Data Files for this text: – Tables in the database have already been created – You will not need to execute the CREATE TABLE commands to create the tables or the INSERT commands to add records to the tables 6 Getting Started with Microsoft Office Access 2007 and 2010 (continued) • To execute SQL commands shown in the figures in Access 2007 or Access 2010: – Open the Premiere Products database – Click the Create tab on the Ribbon – Click the Query Design button in the Other group – Click the Close button in the Show Table dialog box – Click the View button arrow in the Results group on the Query Design Tools tab, then click SQL View – The Query1 tab displays the query in SQL 7 Getting Started with MySQL • MySQL-Premiere script provided with the Data Files for this text will: – Activate the database – Create the tables – Insert the records • To run a script in MySQL: – Type the SOURCE command followed by the name of the file – Press the Enter key 8 Getting Started with MySQL (continued) • Before typing commands in MySQL, you must activate the database by typing the USE command followed by the name of the database • The most recent command entered in MySQL is stored in a special area of memory called the statement history 9 Table Creation • SQL CREATE TABLE command – Creates a table by describing its layout • Typical restrictions placed on table and column names by DBMS – Names cannot exceed 18 characters – Names must start with a letter – Names can contain only letters, numbers, and underscores (_) – Names cannot contain spaces 10 Table Creation (continued) • INTEGER – Number without a decimal point • SMALLINT – Uses less space than INTEGER • DECIMAL(p,q) – P number of digits; q number of decimal places • CHAR(n) – Character string n places long • DATE – Dates in DD-MON-YYYY or MM/DD/YYYY form 11 Table Creation (continued) CREATE TABLE Rep ( RepNum CHAR( 2) , LastName CHAR( 15) , FirstName CHAR(15) , Street CHAR(15) , City CHAR( 15) , State CHAR(2) , Zip CHAR( 5) , Commission DECIMAL(7, 2) , Rate DECIMAL( 3, 2) ) ; 12 Simple Retrieval • SELECT-FROM-WHERE: SQL retrieval command – SELECT clause: lists fields to display – FROM clause: lists table or tables that contain data to display in query results – WHERE clause (optional): lists any conditions to be applied to the data to retrieve • Simple condition: field name, a comparison operator, and either another field name or a value 13 Simple Retrieval (continued) SELECT CustomerNum, CustomerName, Balance FROM Customer WHERE CreditLimit >= 10000; Customer Num Customer Name Balance 282 Brookings Direct 431.50 462 Bargains Galore 3412.00 524 Kline's 608 Johnson's Department Store 2106.00 12762.00 14 Simple Retrieval (continued) FIGURE 3-8: Comparison operators used in SQL commands 15 Compound Conditions • Compound condition – Connecting two or more simple conditions using one or both of the following operators: AND and OR – Preceding a single condition with the NOT operator • Connecting simple conditions using AND operator – All of the simple conditions must be true for the compound condition to be true • Connecting simple conditions using OR operator – Any of the simple conditions must be true for the compound condition to be true 16 Compound Conditions (continued) SELECT Description FROM Part WHERE Warehouse =3 AND OnHand >20 17 Compound Conditions (continued) • Preceding a condition by NOT operator – Reverses the truth or falsity of the original condition • BETWEEN operator – Value must be between the listed numbers SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20; 18 Computed Fields • Computed field or calculated field – Field whose values you derive from existing fields – Can involve: • • • • Addition (+) Subtraction (-) Multiplication (*) Division (/) 19 Computed Fields (continued) SELECT CustomerNum, CustomerName, CreditLimit - Balance AS AvailableCredit FROM Customer WHERE CreditLimit > Balance 20 Using Special Operators (LIKE and IN) • Wildcards in Access SQL – Asterisk (*): collection of characters – Question mark (?): any individual character • Wildcards in MySQL – Percent sign (%): any collection of characters – Underscore (_): any individual character • To use a wildcard, include the LIKE operator in the WHERE clause • IN operator provides a concise way of phrasing certain conditions 21 Using Special Operators (LIKE and IN) (continued) SELECT CustomerNum, CustomerName, Street, City, State, Zip FROM Customer WHERE Street LIKE "%Oxford" 22 Using Special Operators (LIKE and IN) (continued) SELECT CustomerNum, CustomerName, CreditLimit FROM Customer WHERE CreditLimit IN (7500, 10000, 15000) 23 Sorting • Sort data using the ORDER BY clause • Sort key: field on which to sort data • When sorting data on two fields: – Major sort key (or primary sort key): more important sort key – Minor sort key (or secondary sort key): less important sort key 24 Sorting (continued) FIGURE 3-33: SQL query to sort data on multiple fields FIGURE 3-34: Query results 25 Built-in Functions • Built-in functions (aggregate functions) in SQL – COUNT: calculates number of entries – SUM or AVG: calculates sum or average of all entries in a given column – MAX or MIN: calculates largest or smallest values respectively 26 Built-in Functions (continued) SELECT COUNT(*) FROM Part WHERE CLASS="HW" 27 Subqueries • Subquery: inner query • Subquery is evaluated first • Outer query is evaluated after the subquery 28 Subqueries (continued) List the order number for each order that contains an order line for a part located in warehouse 3. 29 Grouping • Create groups of records that share a common characteristic • GROUP BY clause indicates grouping in SQL • HAVING clause is to groups what the WHERE clause is to rows 30 Grouping (continued) SELECT RepNum, COUNT(*) AS NumCustomers, AVG(Balance) AS AverageBalance FROM Customer GROUP BY RepNum HAVING COUNT(*) < 4 ORDER BY RepNum 31 Joining Tables • Queries can locate data from more than one table • Enter appropriate conditions in the WHERE clause • To join tables, construct the SQL command as: 1. SELECT clause: list all fields you want to display 2. FROM clause: list all tables involved in the query 3. WHERE clause: give the condition that will restrict the data to be retrieved to only those rows from the two tables that match 32 Joining Tables (continued) • List the number and name of each customer together with the number, last name, and first name of the sales rep who represents the customer. Order the records by customer number. 33 Joining Tables (continued) SELECT CustomerNum,CustomerName, Customer. RepNum, LastName, FirstName FROM Customer, Rep WHERE Customer.RepNum = Rep.RepNum 34 Union • Union of two tables is a table containing all rows in the first table, the second table, or both tables • Two tables involved must be union compatible – Same number of fields – Corresponding fields must have same data types 35 Union (continued) • List the number and name of all customers that are represented by sales rep 35 or that currently have orders on file or both. SELECT CustomerNum, CustomerName FROM Customer WHERE RepNum=35 UNION SELECT Customer.CustomerNum, CustomerName FROM Customer, Orders WHERE Customer.CustomerNum = Orders.CustomerNum 36 Updating Tables • UPDATE command makes changes to existing data • INSERT command adds new data to a table • DELETE command deletes data from the database 37 Updating Tables (continued) • Change the street address of customer 524 to 1445 Rivard. • Change the street address of customer 524 to 1445 Rivard. • Delete any row in the OrderLine table in which the part number is BV06. 38 Updating Tables (continued) UPDATE Customer SET Street="1445 Riverd" WHERE CustomerNum =524 INSERT INTO Rep VALUES ('16','Rands','Sharon','820 Raymond Street','Clintonsburg','Ohio','43551',0.00,0.05) 39 Updating Tables (continued) • DELETE FROM OrderLine WHERE PartNum="BV06" 40 Creating a Table from a Query • INTO clause – Saves the results of a query as a table – Specified before FROM and WHERE clauses • MySQL – Create the new table using a CREATE TABLE command – Use an INSERT command to insert the appropriate data into the new table 41 Creating a Table from a Query (continued) • Create a new table named SmallCust consisting of all fields from the Customer table and those rows in which the credit limit is less than or equal to $7,500. 42 Creating a Table from a Query (continued) CREATE TEMPORARY TABLE CustNew AS (SELECT * FROM Customer WHERE CreditLimit<=7500); SELECT * FROM CustNew; 43 Creating a Table from a Query (continued) FIGURE 3-60b: Query to create a new table (for Oracle and MySQL) 44 Create • Use SQL to create the Rep table by describing its layout. CREATE TABLE Rep ( RepNum CHAR(2) , LastName CHAR( 15) , FirstName CHAR(15) , Street CHAR( 15) , City CHAR( 15) , State CHAR( 2) , Zip CHAR( 5) , Commission DECIMAL( 7, 2) , Rate DECIMAL( 3, 2) ); 45 Summary of SQL Commands • Generic versions of SQL commands for every example presented in this chapter • In most cases, commands in Access are identical to the generic versions • For those commands that differ, both the generic version and the Access version are included 46 Summary • Structured Query Language (SQL) is a language that is used to manipulate relational databases • Basic form of an SQL query: SELECT-FROM-WHERE • Use CREATE TABLE command to describe table layout to the DBMS, which creates the table • In SQL retrieval commands, fields are listed after SELECT, tables are listed after FROM, and conditions are listed after WHERE • In conditions, character values must be enclosed in single quotation marks 47 Summary (continued) • Compound conditions are formed by combining simple conditions using either or both of the following operators: AND and OR • Sorting is accomplished using ORDER BY clause • When the data is sorted in more than one field, can have a major and minor sort key • Grouping: use the GROUP BY clause • HAVING clause: restricts the rows to be displayed 48 Summary (continued) • Joining tables: use a condition that relates matching rows in the tables to be joined • Built-in (aggregate) functions: COUNT, SUM, AVG, MAX, and MIN • One SQL query can be placed inside another; the subquery is evaluated first • UNION operator: unifies the results of two queries 49 Summary (continued) • Calculated fields: include the calculation, the word AS, the name of the calculated field • INSERT command adds a new row to a table • UPDATE command changes existing data • DELETE command deletes records • INTO clause is used in a SELECT command to create a table containing the results of the query 50