Sunteți pe pagina 1din 10

SQL and iSeries Computing

These notes are being compiled as a supplement to the required labs for the DBS201 course. There will be no attempt to unravel the intricacies of the iSeries; rather, these notes will focus on the SQL scripts that can be written on the green screen without the use of any additional assistance from the system itself. With the assistance of instructions from the introductory lab, students should be able to start SQL, and reach a screen headed Enter SQL Statements. This is the screen that we will work from. Using SQL code, we are able to formulate queries or write commands that will: a) retrieve data from existing databases b) create and update the tables of a new or existing database. The iSeries contains a library of database collections or schema. Each schema or collection contains tables. We can retrieve data from an existing database collection by using a SQL query in the following form: SELECT <attributes> FROM <schema.entity (or schema.entities)> WHERE <certain conditions exist> this clause is optional. Note that the query is directed at a particuar table (or tables) of a schema. When we are querying the system, the attributes that we select must be written in exactly the same form as exist in the table. Alternately, if we are writing these commands on paper, any the attributes can be written in any short form that is representative of the attributes in question. To create database tables in your account, you use the SQL CREATE TABLE command to create the table and describe its layout. As is shown below, tables that are created require that you list a column name, define its data type, and indicate whether a value must be entered for that attribute, or if it can be left empty. Column Name Data Type Allow Nulls O

The Column Name column lists the name of the table attribute(s). The data types that you will most often encounter are listed below: INTEGER - uses integers, numbers without a decimal part. You can use the contents of INTEGER fields for calculations. DECIMAL(p,q) Stores a decimal number p digits long with q of those digits being decimal places. For example, DECIMAL(5,2) represents a number

Page 1 of 10

with 3 places to the left of the decimal point, and 2 places top the right of the decimal point.

CHAR - Stores a character string n characters long. You use the CHAR type for fields that contain letters and other special characters and for numbers that will not be used for calculations. For example, since neither the sales rep number nor the customer number will be used in any calculations, it is best to assign both of them the CHAR data type. DATE Stores dates in the form DD-MM-YYYY or MM/DD/YYYY. To enter date data , key in the form of YYYY_MM_DD. Allowing NULLS means that it is possible for the field to be EMPTY and not destroy the integrity of the database. A NULL does not mean that the value of the field is 0 (zero).

CREATE TABLE Premiere.Rep (RepNum CHAR(2) not null, LastName CHAR(15) not null,

FirstName CHAR(15) not null, Street CHAR(15) not null, City CHAR(15) not null, State CHAR(2) not null, ZipCode CHAR(5) not null, Commission DECIMAL(7,2) not null, Rate DECIMAL(3,2) not null) (Note: there is no rule that says you must write the SQL in the format given above. It is simply written that way to make the command more readable.) Examples of Simple Retrieval

Recall that the basic form of an SQL retrieval command is SELECT-FROMWHERE. There are no special formatting rules in SQL; putting the SELECT, FROM, and WHERE clauses on separate lines is done so as to make the commands more readable. Also, so that you can try these queries on your own, the attributes of the Customer table will be listed here as they are written in the Premiere database : CUSTOMER [customer_number, last_name, first_name, street, city, state, zip_code, balance, credit_limit, sales_rep_number] Consider the following examples:

Page 2 of 10

a)List the number, name and balance of all customers.


SELECT customer_number, last_name, first_name, balance FROM premiere.customer (there is no WHERE clause because no conditions have to be met)

b)List the complete PART table


SELECT * FROM premiere.part

c)List the name of every customer with a $1000 credit limit


SELECT first_name, last_name FROM premiere.customer WHERE credit_limit=1000

d)Find the name of customer 124


SELECT first_name, last_name FROM premiere.customer Where customer_number = 124

Note that the customer number is enclosed by single parentheses because it was defined as a CHAR field. e)Find the customer name for every customer located in Lansing
SELECT first_name, last_name FROM premiere.customer WHERE city = Lansing

f)List the number, name, credit limit and balance for all customers with credit limits that exceed their balances.
SELECT customer_number, first_name, last_name, balance FROM Customer WHERE credit_limit > balance

SQL Commands with Compound Conditions A compound condition is formed by connecting two or more simple conditions using one both of the following operators: AND and OR. You can also precede a single condition with the NOT operator to negate the condition.

Page 3 of 10

When you connect simple conditions using the AND operator, all simple conditions must be true for the compound condition to be true. When you connect simple conditions using the OR operator, the compound condition will be true whenever any of the simple conditions are true. Preceding a condition with the NOT operator reverses the truth or falsity of the original condition. Further Examples: g)List the descriptions of all parts that are located in warehouse 3 and for which there are more than 20 units on hand.
SELECT part_description FROM premiere.part WHERE warehouse = 3 and on hand>20

h)List the description of all parts that are located in warehouse 3 or for which there are more than 20 units on hand
SELECT part_description FROM premiere.part WHERE warehouse = 3 or on_hand>20

i)List the description of all parts that are not in warehouse 3


SELECT part_description FROM premiere.part WHERE NOT Warehouse =3

j)List the number, name, and balance of all customers with balances greater than or equal to $500 and less than or equal to $2,000
SELECT customer_number, last_name, first_name, balance FROM premiere.customer WHERE balance BETWEEN 500 and 2000

COMPUTED FIELDS You can include fields in queries that are not in a database, but whose values you can compute from existing database fields. A field whose values you derive from existing fields is called a computed or calculated field. Computed fields can include addition (+), subtraction (-), multiplication (*), or division(/). More Examples: k)List the number, name and available credit for all customers.
SELECT customer_number, last_name, first_name, credit_limit-balance as available credit FROM premiere.customer

There is no field in the database that stores available credit, but you can compute it using two fields that are available in the database: Credit Limit and Balance.

Page 4 of 10

l)List the number, name, and available credit for all customers with credit limits that exceed their balances
SELECT customer_number, last_name, first_name, credit_limit-balance as available credit FROM premiere.customer WHERE credit_limit > balance

USING SPECIAL OPERATORS


In most cases, your conditions will involve exact matches such as finding customers located in a particular city. In some cases however, exact matches will not work. For example, you might know only that the desired value contains a certain collection of characters. In such cases, you use the LIKE operator with a wildcard as shown below: Example: m)List the number, name and exact address of every customer located on a street that contains the letters oak.
SELECT customer_number, last_name, first_name, street, city, state, zip_code FROM premiere.customer WHERE street LIKE %oak%

Another operator, IN, provides a concise way of phrasing certain conditions; n)List the number, name, and credit limit for every customer with a credit limit of $7,500, $10,000 or $15,000
SELECT customer_number ,last_name, first_name, creditlimit FROM premiere.customer WHERE credit_limit IN (750, 1000, 1500)

SORTING

It was earlier indicated that the order of the rows in a table is immaterial. For all practical purposes, this means that when you query a relational database, there are no guarantees in what order the results will be displayed. The

Page 5 of 10

results might appear in the order in which the data was originally entered, but that is not a certainty. If the order in which the data is displayed IS important, you should specifically request that the results be displayed in the desired order. o)List the number, name, street and credit limit for all customers. Order (sort) the customers by name.
SELECT customer_number, last_name, first_name, street, credit_limit FROM premiere.customer ORDER BY custname

p) List the number, name, street and credit limit for all customers. Order the customers by name within a descending credit limit. (In other words, sort the customers by credit limit in descending order. Within each group of customers that have a common credit limit, sort the customers by name. When you need to sort data on two fields, the more important sort key is called the major sort key or the primary sort key, and the less important sort key is called the minor sort key or the secondary sort key. In this example, because you need to sort the output by name within credit limit, the CreditLimit field is the major sort key, and the CustomerName field is the minor sort key. You can specify to sort the output in descending order (high to low) by following the major sort key by DESC minor sort key.
SELECT customer_number,,last_name, first_name, street, credit_limit FROM premiere.customer ORDER BY credit_limit , last_name

BUILT-IN FUNCTIONS

SQL has built-in functions, also called aggregate functions to calculate the number of entries, the sum or average of all the entries in a given column, and the largest or smallest value in a given column. In SQL, these functions are called COUNT, SUM, AVG, MAX or MIN, respectively. q)How many items are in item class HW?
SELECT COUNT(*) FROM Premiere.part WHERE Class = HW

r)Find the number of customers and the total of their balances.


SELECT COUNT(*), SUM(Balance)

Page 6 of 10

FROM Premiere.Customer

s) Find the number of customers and the total of their balances. Change the column names for the number of customers and the total of their balances to Customer Count and Balance Total respectively.
SELECT COUNT(*) AS Customer Count , SUM(Balance) AS Balance Total FROM premiere.customer

JOINING TABLES Many queries require date from more than one table. If this is the case, it is necessary to be able to join tables so that you can find rows in two or more tables that have identical values in matching fields. In SQL, this is accomplished by entering the appropriate conditions in the WHERE clause. t)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.
SELECT premiere.customer.customer_number, premiere.customer.last_name, premiere.customer.first_name, premiere.salesrep.sales_rep_number, premiere.salesrep.last_name, premiere.salesrep.first_name FROM premiere.salesrep, premiere.customer WHERE premiere.customer.sales_rep_number = premiere.salesrep.sales_rep_number ORDER BY premiere.customer.customer_number

u)List the number and name of each customer whose credit limit is $10,000 together with the number, last name, first name of the sales rep who represents the customer. Order the records by customer number.
SELECT premiere.customer.customer_number, premiere.customer.last_name, premiere.customer.first_name, premiere.salesrep.sales_rep_number, premiere.salesrep.last_name, premiere.salesrep.first_name FROM premiere.salesrep, premiere.customer WHERE customer.repnum = rep.repnum And credit_limit =1000 ORDER BY premiere.customer.customer_number

Page 7 of 10

It is possible to join more than two tables. For each pair of tables that you join, you must include a condition indicating how the tables are related. v)For every order, list the order number, order date, customer number , and customer name. In addition, for each order line within the order, list the part number, description, number ordered and quoted price. Order the records by order number.
SELECT order.ordernum, order.orderdate, order.customernum, customer.custname, orderline.ordernum, orderline.partnum, part.descrip, orderline.numberordered, orderline.quotedprice FROM order, customer, orderline, part WHERE order.custnum = customer.custnum And orderline.ordernum = order.ordernum And orderline.partnum = part.partnum ORDER By order.ordernum

Chapter 4 Exercises
1. List the part number, description, and price for all parts. select part_num, description, price from part; 2. List all rows and columns for the complete ORDERS table. select * from orders; 3. List the names of customers with credit limits of $10,000 or more. select customer_name from customer where credit_limit >= 10000; 4. List the order number for each order placed by customer number 608 on 10/23/2010. select * from orders where customer_num = '608' and order_date ='10/23/2010'; 5. List the number and name of each customer represented by sales rep 35 or sales rep 65. select customer_num, customer_name, from customer where rep_num = '35' or rep_num = '65'; 6. List the part number and part description of each part that is not in item class AP.

Page 8 of 10

select part_num, description from part where class !='AP'; 7. List the part number, description, and number of units on hand for each part that has between 10 and 25 units on hand, including both 10 and 25. Do this two ways. select part_num, description, on_hand from part where (on_hand >= '10') and (on_hand <= '25'); AND select part_num, description, on_hand from part where on_hand between 10 and 25; 8. List the part number, part description, and on-hand value (units on hand* unit price) of each part in item class SG. (On-hand value is really units on had * cost, but there is no COST column in the PART table.) Assign the name ON_HAND_VALUE to the computed column. select part_num, description, (on_hand * price) as on_hand_value from part where class = 'SG'; 9. List the part number, part description, and on-hand value for each part whose on-hand value is at least $7,500. Assign the name ON_HAND_VALUE to the computed column. select part_num, description, (on_hand * price) as on_hand_value from part where (on_hand * price) >= 7500 10. Use the IN operator to list the part number and part description of each part in item class AP or SG. select part_num, description from part where class in ('AP', 'SG'); 11. Find the number and name of each customer whose name begins with the letter "B". select customer_num, customer_name from customer where customer_name like 'B%'; 12. List all details about all parts. Order the output by part description. select * from part order by description; 13. List all details about all parts. Order the output by part number within warehouse. (That is, order the output by warehouse and then by part number.) select * from part order by warehouse, part_num; 14. How many customers have balances that are more than their credit limits?

Page 9 of 10

select count(*) from customer where balance > credit_limit; 15. Find the total of the balances for all customers represented by sales rep 65 with balances that are less than their credit limits. select sum(balance) from customer where rep_num = 65 and balance < credit_limit; 16. List the part number, part description, and on-hand value of each part whose number of units on hand is more than the average number of units on hand for all parts. (Use a subquery) select part_num, description, (on_hand * price) as on_hand_value from part where on_hand > (select avg(on_hand) from part); 17. What is the price of the least expensive part in the database? select min(price) from part; no data found 18. What is the part number, description, and price of the least expensive part in the database? select part_num, description, price from part where price = (select min(price) from part); 19. List the sum of the balances of all customers for each sales rep. Order and group the results by sales rep number. select rep_num, sum(balance) from customer group by rep_num order by rep_num; 20. List the sum of the balances of all customers for each sales rep, but restrict the output to those sales reps for which the sum is more than $10,000. select rep_num, sum(balance) from customer group by rep_num having sum(balance) >= 10000; 21. List the part number of any part with an unknown description. select part_num from part where description ='unknown';

Page 10 of 10

S-ar putea să vă placă și