Wednesday, May 4, 2011

A Quick Tour of SQL : SQL Online Training


Overview
Before diving into the details of SQL, it's a good idea to develop an overall perspective on
the language and how it works. This chapter contains a quick tour of SQL that illustrates its
major features and functions. The goal of the quick tour is not to make you proficient in
writing SQL statements; that is the goal of Part II of this book. Rather, by the time you've
finished this chapter, you will have a basic familiarity with the SQL language and an
overview of its capabilities.

A Simple Database


The examples in the quick tour are based on a simple relational database for a small
distribution company. The database, shown in Figure 2-1, stores the information needed
to implement a small order processing application. Specifically, it stores the following
information:


                                                Figure 2-1: A simple relational database




• the customers who buy the company's products,
• the orders placed by those customers,


• the salespeople who sell the products to customers, and
• the sales offices where those salespeople work.

This database, like most others, is a model of the "real world." The data stored in the
database represents real entities—customers, orders, salespeople, and offices. There is a
separate table of data for each different kind of entity. Database requests that you make
using the SQL language parallel real-world activities, as customers place, cancel, and
change orders, as you hire and fire salespeople, and so on. Let's see how you can use
SQL to manipulate data.

Retrieving Data


First, let's list the sales offices, showing the city where each one is located and its yearto-
date sales. The SQL statement that retrieves data from the database is called
SELECT. This SQL statement retrieves the data you want:



SELECT CITY, OFFICE, SALES FROM OFFICES



CITY            OFFICE                     SALES
------------       -----------                     -----------
Denver            22                         $186,042.00

New York       11                         $692,637.00

Chicago          12                         $735,042.00

Atlanta           13                         $367,911.00

Los Angeles   21                        $835,915.00


The SELECT statement asks for three pieces of data—the city, the office number, and the
sales—for each office. It also specifies that the data comes from the OFFICES table,
which stores data about sales offices. The results of the query appear, in tabular form,
immediately after the request.

The SELECT statement is used for all SQL queries. For example, here is a query that lists
the names and year-to-date sales for each salesperson in the database. It also shows the
quota (sales target) and the office number where each person works.


In this case, the data comes from SALESREPS table:

SELECT NAME, REP_OFFICE, SALES, QUOTA
FROM SALESREPS



SQL also lets you ask for calculated results. For example, you can ask SQL to calculate
the amount by which each salesperson is over or under quota:

SELECT NAME, SALES, QUOTA, (SALES - QUOTA) FROM SALESREPS

The requested data (including the calculated difference between sales and quota for
each salesperson) once again appears in a row/column table. Perhaps you would like to
focus on the salespeople whose sales are less than their quotas. SQL lets you retrieve
that kind of selective information very easily, by adding a mathematical comparison to the
previous request:

SELECT NAME, SALES, QUOTA, (SALES - QUOTA) FROM SALESREPS WHERE SALES < QUOTA





NAME                 SALES                        QUOTA                                                      (SALES-QUOTA)
---------------------------------------------------------------------------------------------------------------------------------
Bob Smith         $142,594.00                   $200,000.00                                                     -$57,406.00
Nancy Angelli  $186,042.00                    $300,000.00                                                     -$113,958.00


The same technique can be used to list large orders in the database and find out which
customer placed the order, what product was ordered, and in what quantity. You can also
ask SQL to sort the orders based on the order amount:

SELECT ORDER_NUM, CUST, PRODUCT, QTY, AMOUNT
FROM ORDERS
WHERE AMOUNT > 25000.00
ORDER BY AMOUNT


ORDER_NUM           CUST       PRODUCT                   QTY                          AMOUNT   
-----------------------------------------------------------------------------------------------------------------------------------
112987                         2103           4100Y                            11                            $27,500.00
113069                         2109            775C                             22                            $31,350.00
112961                         2117           2A44L                            7                              $31,500.00
113045                         2112           2A44R                            10                           $45,000.00


Summarizing Data



SQL not only retrieves data from the database, it can be used to summarize the database
contents as well. What's the average size of an order in the database? This request asks
SQL to look at all the orders and find the average amount:

SELECT AVG(AMOUNT)
FROM ORDERS

AVG(AMOUNT)
------------
$8,256.37



You could also ask for the average amount of all the orders placed by a
particular customer:


SELECT AVG(AMOUNT)
FROM ORDERS
WHERE CUST = 2103
AVG(AMOUNT)
-----------
$8,895.50


Finally, let's find out the total amount of the orders placed by each customer. To do this,
you can ask SQL to group the orders together by customer number and then total the
orders for each customer:



SELECT CUST, SUM(AMOUNT)
FROM ORDERS
GROUP BY CUST


CUST               SUM(AMOUNT)


2101                   $1,458.00
2102                   $3,978.00
2103                   $35,582.00
2106                   $4,026.00
2107                   $23,132.00
2108                   $7,255.00
2109                   $31,350.00
2111                   $6,445.00
2112                   $47,925.00
2113                   $22,500.00
2114                   $22,100.00
2117                   $31,500.00
2118                   $3,608.00
2120                   $3,750.00
2124                   $3,082.00

Adding Data to the Database

SQL is also used to add new data to the database. For example, suppose you just
opened a new Western region sales office in Dallas, with target sales of $275,000. Here's
the INSERT statement that adds the new office to the database, as office number 23:

INSERT INTO OFFICES (CITY, REGION, TARGET, SALES, OFFICE)
VALUES ('Dallas', 'Western', 275000.00, 0.00, 23)
1 row inserted.

Similarly, if Mary Jones (employee number 109) signs up a new customer, Acme
Industries, this INSERT statement adds the customer to the database as customer
number 2125 with a $25,000 credit limit:

INSERT INTO CUSTOMERS (COMPANY, CUST_REP, CUST_NUM, CREDIT_LIMIT)
VALUES ('Acme Industries', 109, 2125, 25000.00)
1 row inserted.

Deleting Data
Just as the SQL INSERT statement adds new data to the database, the SQL DELETE
statement removes data from the database. If Acme Industries decides a few days later
to switch to a competitor, you can delete them from the database with this statement:

DELETE FROM CUSTOMERS
WHERE COMPANY = 'Acme Industries'
1 row deleted.
And if you decide to terminate all salespeople whose sales are less than their quotas, you
can remove them from the database with this DELETE statement:

DELETE FROM SALESREPS
WHERE SALES < QT<R
2 rows deleted.

Updating the Database

The SQL language is also used to modify data that is already stored in the database. For
example, to increase the credit limit for First Corp. to $75,000, you would use the SQL
UPDATE statement:
UPDATE CUSTOMERS
SET CREDIT_LIMIT = 75000.00
WHERE COMPANY = 'First Corp.'
1 row updated.

The UPDATE statement can also make many changes in the database at once. For
example, this UPDATE statement raises the quota for all salespeople by $15,000:

UPDATE SALESREPS
SET QUOTA = QUOTA + 15000.00
8 rows updated.


Protecting Data


An important role of a database is to protect the stored data from access by unauthorized
users. For example, suppose your assistant, named Mary, was not previously authorized
to insert data about new customers into the database. This SQL statement grants her
that permission:
GRANT INSERT
ON CUSTOMERS
TO MARY


Privilege granted.


Similarly, the following SQL statement gives Mary permission to update data about
customers and to retrieve customer data with the SELECT statement:


GRANT UPDATE, SELECT
ON CUSTOMERS
TO MARY


Privilege granted.


If Mary is no longer allowed to add new customers to the database, this REVOKE
statement will disallow it:


REVOKE INSERT
ON CUSTOMERS
FROM MARY


Privilege revoked.


Similarly, this REVOKE statement will revoke all of Mary's privileges to access customer
data in any way:


REVOKE ALL
ON CUSTOMERS
FROM MARY
Privilege revoked.


Creating a Database
Before you can store data in a database, you must first define the structure of the data.
Suppose you want to expand the sample database by adding a table of data about the
products sold by your company. For each product, the data to be stored includes:
• a three-character manufacturer ID code,
• a five-character product ID code,
• a description of up to thirty characters,
• the price of the product, and
• the quantity currently on hand.


This SQL CREATE TABLE statement defines a new table to store the products data:


CREATE TABLE PRODUCTS
(MFR_ID CHAR(3),
PRODUCT_ID CHAR(5),
DESCRIPTION VARCHAR(20),
PRICE MONEY,
QTY_ON_HAND INTEGER)


Table created.


Although more cryptic than the previous SQL statements, the CREATE TABLE statement
is still fairly straightforward. It assigns the name PRODUCTS to the new table and specifies
the name and type of data stored in each of its five columns.


Once the table has been created, you can fill it with data. Here's an INSERT statement
for a new shipment of 250 size 7 widgets (product ACI-41007), which cost $225.00
apiece:
INSERT INTO PRODUCTS (MFR_ID, PRODUCT_ID, DESCRIPTION, PRICE,
QTY_ON_HAND)
VALUES ('ACI', '41007', 'Size 7 Widget', 225.00, 250)


1 row inserted.


Finally, if you discover later that you no longer need to store the products data in the
database, you can erase the table (and all of the data it contains) with the DROP TABLE
statement:
DROP TABLE PRODUCTS


Table dropped.


Summary
This quick tour of SQL showed you what SQL can do and illustrated the style of the SQL
language, using eight of the most commonly used SQL statements. To summarize:

SQL is used to retrieve data from the database, using the SELECT statement. You can
retrieve all or part of the stored data, sort it, and ask SQL to summarize the data, using
totals and averages.

SQL is used to update the database, by adding new data with the INSERT statement,
deleting data with the DELETE statement, and modifying existing data with the UPDATE
statement.
• SQL is used to control access to the database, by granting and revoking specific
privileges for specific users with the GRANT and REVOKE statements.
• SQL is used to create the database by defining the structure of new tables and dropping
tables when they are no longer needed, using the CREATE and DROP statements.













No comments:

Post a Comment