Tải bản đầy đủ (.pdf) (50 trang)

Adobe Dreamweaver CS3 Unleashed- P22 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (351.56 KB, 50 trang )


Summary
This chapter has introduced you to some simple, yet important, concepts—mainly data storage. You learned
about the skeleton of a database—which is composed of tables, columns, and rows—and about crucial
concepts that can aid in performance, maintenance, and efficiency.
More importantly, you looked at the various databases supported in this book. You learned about Access,
SQL Server 2005 Express Edition, and MySQL as well as the DBMSs that work in conjunction with them. You
saw how to obtain and install the necessary software, how to create tables, columns, and rows, and how to
attach/restore the Vecta Corp database so that you can work with dynamic Vecta Corp data in your
database of choice from Dreamweaver. As the chapter progressed, we also looked at the many tables
contained within the Vecta Corp database. You looked at the Employees, Departments, CreditCards,
EmployeeStore, and Orders tables as well as the other tables left open so that you can continue to work
with the Vecta Corp web application on your own.
The next chapter, "A SQL Primer," goes beyond data storage and introduces you to the language used in
data access—SQL.


Chapter 23. A SQL Primer
IN THIS CHAPTER
The Structured Query Language
Basic SQL
Expressions
Operators
Functions
Joins
Subqueries
Generating Queries Visually
At this point, you are familiar with just how easy it is to create a database using Access, SQL Server 2005
Express, or MySQL. In the coming chapters, you'll learn just how easy Dreamweaver makes it to extract
from, insert into, update within, and delete information from your database. Although Dreamweaver
provides a simple process for the extraction of data from your database, you may quickly find your


application growing far beyond the scope of simple data extraction. The kind of applications you eventually
build will have a direct impact on how complex your use of a data-access language will be. Dreamweaver
provides a simple and easy-to-use process for commonly used data extraction and filtering tasks, but if you
truly want to get the most out of your application, you should become familiar with the topics discussed in
this chapter.
The Structured Query Language
This chapter focuses on the language of today's database. The Structured Query Language, or SQL
(pronounced "sequel"), was established in the 1970s as a way of interacting with current database
technologies and the tables that made them up. With dozens of clauses, keywords, and operators, SQL
quickly became the language standard for simple and complex database operations. The keywords that you
construct, also known as statements, range from a simple few to a complex string of subqueries and joins.
Although this chapter cannot begin to cover all there is to know on the subject, it can provide you with an
introduction to beginning and advanced SQL statements, clauses, joins, subqueries, and action queries. The
concepts you learn in this chapter will help you, on a more advanced level, interact with data in your
database using Dreamweaver.


Chapter 23. A SQL Primer
IN THIS CHAPTER
The Structured Query Language
Basic SQL
Expressions
Operators
Functions
Joins
Subqueries
Generating Queries Visually
At this point, you are familiar with just how easy it is to create a database using Access, SQL Server 2005
Express, or MySQL. In the coming chapters, you'll learn just how easy Dreamweaver makes it to extract
from, insert into, update within, and delete information from your database. Although Dreamweaver

provides a simple process for the extraction of data from your database, you may quickly find your
application growing far beyond the scope of simple data extraction. The kind of applications you eventually
build will have a direct impact on how complex your use of a data-access language will be. Dreamweaver
provides a simple and easy-to-use process for commonly used data extraction and filtering tasks, but if you
truly want to get the most out of your application, you should become familiar with the topics discussed in
this chapter.
The Structured Query Language
This chapter focuses on the language of today's database. The Structured Query Language, or SQL
(pronounced "sequel"), was established in the 1970s as a way of interacting with current database
technologies and the tables that made them up. With dozens of clauses, keywords, and operators, SQL
quickly became the language standard for simple and complex database operations. The keywords that you
construct, also known as statements, range from a simple few to a complex string of subqueries and joins.
Although this chapter cannot begin to cover all there is to know on the subject, it can provide you with an
introduction to beginning and advanced SQL statements, clauses, joins, subqueries, and action queries. The
concepts you learn in this chapter will help you, on a more advanced level, interact with data in your
database using Dreamweaver.


Basic SQL
Just as your savings account would be useless without a valid ID or bank card to get to that money,
information contained within a database is useless data unless you have the means of extracting it. SQL is
the language that does just that; it allows for quick and complex access to the data contained in your
database through the use of queries. Queries pose the questions and return the results to your application,
usually in the form of a recordset.
Caution
Don't think of SQL as simply a way of extracting information. The SQL language can be complex,
allowing not only queries from a database, but can add, modify, and delete information from a
database as well.
Consider trying to extract information from the EmployeeStore table of the Vecta Corp database. Recall that
the EmployeeStore table resembles the table that follows (although this table does not show the

ItemDescription and Headshot columns):
Field Name
Date Type
ItemID
AutoNumber
ItemName
Text
Quantity
Currency
Cost
Number
You can then list products in rows that would look like the following:
ItemID
ItemName
Cost
Quantity
1
Vecta Corp Shirt
$12.99
100
2
Vecta Corp Hooded
$29.99
100
3
Vecta Corp Longsleeve
$19.99
100
4
Vecta Corp Polo

$23.99
100
5
Vecta Corp Sticker
$1.99
100
6
Vecta Corp Mousepad
$4.99
100
7
Vecta Corp Coffee Mug
$6.99
100
8
Vecta Corp Water Bottle
$9.99
100
Consider some important aspects about the previous table and the columns and data contained in the eight
rows. The EmployeeStore table contains four columns: an ItemID with an AutoNumber that increments a
value whenever an item is added, an ItemName that contains a Text data type allowing for a simple title of
the product to be added, a column for Cost with a Currency data type that allows us to store price
information for each specific item, and a Quantity column with a Number data type that allows us to store a
numeric value indicating how many of a specific item we have left in our inventory. The last thing to
consider is the data contained in the table. We are storing a list of Vecta Corp employee store items that are
to be sold from the Web Store application.
Now what? You have the table created, columns and data types have been outlined, and you have rows of
data in the table. Our next step is to get to our data somehow. The next few sections outline how to use
SQL to extract data from your tables.
The SELECT Statement

The foundation to all SQL queries is the SELECT statement. Made up of two keywords, the SELECT statement
provides a means for retrieving the data from the database. In its simplest form, the SELECT statement is
written using the following elements:
SELECT—The SELECT keyword is used to identify the statement or action you are attempting to
perform on the database. Other keywords include INSERT, DELETE, and UPDATE. More on these later.
* or field names—The asterisk or names of the fields tell the statement which columns you want to
extract data from. In this case, the asterisk means "all fields."
FROM—The FROM keyword identifies which table to extract the data from. The FROM keyword is required
with all SELECT statements.
Table name(s)—The table name from which you want to extract the data.
The following example extracts all records from your EmployeeStore table:
SELECT * FROM EmployeeStore
The preceding statement uses two keywords—the SELECT keyword and the FROM keyword—to extract all
records from the EmployeeStore table. The previous statement would produce the following results (some
fields have been excluded in order to fit on the page):
ItemID
ItemName
Cost
Quantity
1
Vecta Corp Shirt
$12.99
100
2
Vecta Corp Hooded
$29.99
100
3
Vecta Corp Longsleeve
$19.99

100
4
Vecta Corp Polo
$23.99
100
5
Vecta Corp Sticker
$1.99
100
6
Vecta Corp Mousepad
$1.99
100
7
Vecta Corp Coffee Mug
$1.99
100
8
Vecta Corp Water Bottle
$9.99
100
Selecting Certain Fields
If you did not want to select all the fields in the database table, you could modify the field names to include
only the fields that you wanted.
SELECT ItemID, ItemName, Cost
FROM EmployeeStore
Notice that the preceding statement retrieves the data only from the ItemID, ItemName, and Cost fields.
The preceding query produces the following results:
ItemID
ItemName

Cost
1
Vecta Corp Shirt
$12.99
2
Vecta Corp Hooded
$29.99
3
Vecta Corp Longsleeve
$19.99
4
Vecta Corp Polo
$23.99
5
Vecta Corp Sticker
$1.99
6
Vecta Corp Mousepad
$1.99
7
Vecta Corp Coffee Mug
$1.99
8
Vecta Corp Water Bottle
$9.99
Notice that in this case, the ItemDescription and Quantity columns are left off. You could also modify the
statement in an effort to retrieve the same information in a different order. For example, we could switch
the field names by placing ItemName in front of ItemID, like this:
SELECT ItemName, ItemID, Cost
FROM EmployeeStore

This code would give the following result:
ItemName
ItemID
Cost
Vecta Corp Shirt
1
$12.99
Vecta Corp Hooded
2
$29.99
Vecta Corp Longsleeve
3
$19.99
Vecta Corp Polo
4
$23.99
Vecta Corp Sticker
5
$1.99
Vecta Corp Mousepad
6
$1.99
Vecta Corp Coffee Mug
7
$1.99
Vecta Corp Water Bottle
8
$9.99
Selecting Unique Data
The information in the EmployeeStore table contains duplicate values. As you can see, we have three items

in our table that are priced at $1.99. If someone wanted to know about the unique variety of prices in our
database, we would have to modify the statement to produce distinct results. The DISTINCT keyword can be
used before the Cost field in this case to extract from the table only unique instances of data contained in
that field.
SELECT DISTINCT Cost
FROM EmployeeStore
The preceding statement would produce the following result:
Cost
$12.99
$29.99
$19.99
$23.99
$1.99
$9.99
As you can see, in this case, all cost information is displayed, but the results are limited to unique price
instances. $1.99 is listed only once rather than three times.
Clauses
Clauses are portions of SQL that allow for further refinement of the query or additional work that must be
accomplished by the SQL statement. The following clauses are covered in this section:
The WHERE clause
The ORDER BY clause
The GROUP BY clause
The WHERE Clause
The WHERE clause is used in conjunction with the SELECT statement to deliver a more refined search based
on individual field criteria. This example could be used to extract a specific employee based on a name:
SELECT *
FROM Employees
WHERE Name = 'Ada'
Notice that the selection is made only when a certain criteria is true. If a record with the name of Ada did
not exist, it wouldn't return anything. But what if we had more than one Ada in the database? You could

refine your search even further by using the AND operator:
SELECT *
FROM Employees
WHERE Name = 'Ada' AND Phone = '5555551111'
In this case, even if two Adas were listed in our database, we can assume that they don't have the same
phone number. In this situation, the query returns one result (assuming, of course, that the two Adas aren't
roommates).
The ORDER BY Clause
The ORDER BY clause provides you with a quick way of sorting the results of your query in either ascending
or descending order. Consider the following table of information:
EmployeeID
Name
Email
1
Cammy

2
Ferris

3
Ada

4
Dave

5
Agnes

If you selected all the records by using a SELECT all statement (SELECT *), it would return all the results,
ordering them based on the value in the EmployeeID field: 1 through 5. Using the SELECT statement with an

ORDER BY clause allows you to sort based on a different field name:
SELECT *
FROM Employees
ORDER BY Name
The preceding statement would return results in the following order:
EmployeeID
Name
Email
3
Ada

5
Agnes

1
Cammy

4
Dave

2
Ferris

You can also order by multiple columns by adding a comma after the field name and entering a second field
name:
SELECT *
FROM Employees
ORDER BY Name, Phone
In this case, all records with identical Name fields are sorted by phone.
Tip

You might decide to sort the results of your query in either ascending or descending order. When this
is the case, you can use the ASC and DESC keywords preceding the field names as follows:
SELECT *
FROM Employees
ORDER BY Name, Phone DESC
The GROUP BY Clause
When a query statement includes a GROUP BY clause, the SELECT statement for that query can list functions
while operating on groups of data values in other columns. For example, data within the Orders table could
look similar to the following table:
OrderID
EmployeeID
ItemID
Quantity
1
1
2
2
2
1
4
4
3
3
8
4
4
4
7
2
5

5
2
2
6
5
7
1
If you wanted to retrieve the total number of orders that were received, you could run the following query:
SELECT Count(Quantity) AS NumberOfOrders
FROM Orders
The result would return the following:
NumberOfOrders
6
In this case, we're exploring two unique concepts. First, we're selecting a count, using the built in Count
function to return a total number of orders for the Quantity column. Second, we're using the AS keyword to
create a virtual field called "NumberOfOrders." This gives us a total count of orders and stores that number
(6) temporarily within a virtual field called NumberOfOrders.
You could use the GROUP BY clause in this instance to group the orders by EmployeeID as follows:
SELECT EmployeeID, Count(Quantity) AS NumberOfOrders
FROM Orders
GROUP BY EmployeeID
The result would be as follows:
EmployeeID
NumberOfOrders
1
2
3
1
4
1

5
2
The result is based on the fact that employees 1 and 5 made two orders each while employees 3 and 4
made one order each.
The INSERT Statement
Collecting information from your users is not uncommon and, in most cases, it is a necessity. When you
collect information such as registration information, you're not querying data, but rather you're inserting
data into the database. In our Vecta Corp example, for instance, we'll create an Admin page that allows
administrators to insert new employees into the database. To illustrate this point, consider the Employees
table and some of the fields that make it up:
Field Name
Date Type
EmployeeID
AutoNumber
DepartmentID
Number
Name
Text
Username
Text
Password
Text
Email
Text
Phone
Text
Headshot
Text
BillingShippingAddress
Text

BillingShippingCity
Text
BillingShippingState
Text
BillingShippingZip
Text
You could easily insert a new record into the Employees table using the following INSERT statement:
INSERT INTO Employees
(DepartmentID, Name, Username, Password, Email,
Phone, Headshot, BillingShippingAddress, BillingShippingCity,
BillingShippingState, BillingShippingZip)
VALUES
(1, 'Zak', 'zak', 'zak', '', '5555555555',
'Images\head_zak.gif', '555 Sample St.', 'San Diego', 'Ca', '92115')
The preceding statement inserts all the values you specified into the proper columns within the Employees
table. The INSERT keyword generally uses the following elements:
INSERT—The INSERT keyword is used to identify the statement or action you are attempting to
perform on the database.
INTO—The INTO keyword specifies that you are inserting something into a specific table.
Table name—The name of the table into which you want to insert the values.
VALUES—The actual values to be inserted.
You could also use the SELECT statement within the INSERT statement to literally copy information from one
table to the other:
INSERT INTO Transactions (EmployeeID, Name, Email)
SELECT EmployeeID, Name, Email
FROM Employees WHERE EmployeeID = 1
The preceding statement assumes that we have a Transactions table. At any rate, this statement effectively
copies from the Employees table the EmployeeID, Name, and Email whose EmployeeID is equal to 1 and
copies this data into the Transactions table.
The UPDATE Statement

The UPDATE statement is used to define changes within your database tables. As you're probably aware,
database information is not static, rather, it is constantly changing depending on user feedback or input. As
an example, assume that an administrator wanted to change specific data (maybe a username and
password) for a particular employee within the Employees table. To make these changes to an existing
record in the table, an UPDATE statement would have to be used.
The UPDATE statement requires certain keywords, operators, and usually a WHERE clause to modify the
specific record, for instance:
UPDATE Employees
SET Name = "Cammi"
WHERE EmployeeID = 3
This statement effectively changes Cammy's name to "'Cammi" because she matches the EmployeeID of 3.
Note
Operators enable you to connect certain portions of your statement, whereas clauses allow for more
refined queries and searches. Both are discussed later in the chapter.
You don't have to use the EmployeeID field with the WHERE clause. Instead, you could use Cammy's name as
follows:
UPDATE Employees
SET Name = "Cammi"
WHERE Name = "Cammy"
In this case, all instances of "Cammy" are replaced with "Cammi" in the database.
The DELETE Statement
The DELETE statement can be used to remove unneeded records from the database. For instance, if you
wanted to remove all employees from the Employees table, we might write a DELETE statement as follows:
DELETE
FROM Employees
The preceding statement effectively removes all the employees from the Employees table. Of course, this
doesn't make much sense! You wouldn't want to just go and remove all employees from your database.
Instead, you might want to delete a specific employee—for instance, if an employee quits or is fired. If this
were the case, you could append a WHERE clause to your statement to remove one record:
DELETE

FROM Employees
WHERE EmployeeID = 2
This statement removes only the record where the EmployeeID is equal to 2. As was the case with the
UPDATE example, you could also delete a user by name:
DELETE
FROM Employees
WHERE Name = 'Agnes'
This statement removes all records from the Employees table whose Name field matches "Agnes."


Expressions
If you are the least bit familiar with programming languages, you know that expressions are anything that,
when calculated, result in a value. For instance, 1 + 1 = 2 is an example of an expression. Expressions in
SQL work similarly. Consider the following data that could appear in the Employees table:
EmployeeID
FirstName
LastName
1
Ada
Spada
2
Agnes
Senga
3
Cammy
Franklin
4
Dave
Terry
5

Ferris
Wheel
You could use a simple SELECT statement to display the information exactly as it appears in the preceding
table, or you could write an expression that appends the FirstName and LastName fields together. The query
would look like this:
SELECT EmployeeID, FirstName & LastName AS Name
FROM Employees
Notice the & operator. The & operator is used to concatenate, or join, two fields into one virtual field using
the AS keyword. The results would display as follows:
EmployeeID
Name
1
AdaSpada
2
AgnesSenga
3
CammyFranklin
4
DaveTerry
5
FerrisWheel
Notice that there is no space between the first and last names. To add a space, you need to add a literal
string value as follows:
SELECT EmployeeID, FirstName & ' ' & LastName AS Name
FROM Employees
Note
You might have noticed that we've been using single quotes in every SQL statement. The reason for
this is simple: When you construct your SQL statements in Dreamweaver, the server-side language
encloses the entire statement in double quotes. For the statement to be valid, strings within a SQL
statement must be enclosed within single quotes.

Adding the space results in a gap between the first and last names as follows:
EmployeeID
Name
1
Ada Spada
2
Agnes Senga
3
Cammy Franklin
4
Dave Terry
5
Ferris Wheel


Operators
In the previous section, you were introduced to the use of the & operator. Operators are used in
programming languages to aid in the evaluation of expressions. The following table lists operators with
which you should become familiar:
Operator

Description
*

The multiplication operator is used when multiplying fields or values.
/

The divide operator is used when dividing fields or values.



The minus operator is used when subtracting fields or values.
>

The greater-than operator is used in WHERE clauses to determine
whether a first value is greater than the second, such as:

SELECT *
FROM Employees
WHERE EmployeeID > 10


The result returns all the EmployeeIDs after 10.
<

The less-than operator is used in WHERE clauses to determine whether
a first value is less than the second, such as:

SELECT *
FROM Employees
WHERE EmployeeID < 10


The result returns EmployeeIDs 1–9.
>=

The greater than or equal to operator is used in WHERE clauses to
determine whether a first value is greater than or equal to the second,
such as:

SELECT *

FROM Employees
WHERE EmployeeID >= 10


The result returns EmployeeIDs of 10 and greater.
<=

The less than or equal to operator is used in WHERE clauses to
determine whether a first value is less than or equal to the second,
such as:

SELECT *
FROM Employees
WHERE EmployeeID <= 10


The result returns all the EmployeeIDs between 1 and 10.
<>, !=

When comparing values, use these keywords to check and make sure
that one value is not equal to a second value.
AND

Typically used with the WHERE clause in the SELECT statement. The AND
operator returns a second value, such as:
Operator

Description

SELECT *

FROM Employees
WHERE EmployeeID = 1 AND EmployeeID = 2
OR Typically used with the WHERE clause in the SELECT statement. The OR
operator can be used when a certain condition needs to be met or
when you can settle for a second, such as:

SELECT *
FROM Employees
WHERE EmployeeID = 1 OR EmployeeID = 2
LIKE The LIKE operator is generally used with WHERE clauses when a
wildcard needs to be performed, such as:

SELECT *
FROM Employees
WHERE Name LIKE 'A%'
This result returns all employees whose names start with A. Our result
returns Ada and Agnes because both their names begin with the letter
A.
NOT Typically used in conjunction with the LIKE operator, the NOT operator
is used when a value is not going to be LIKE the value of a second,
such as:

SELECT *
FROM Employees
WHERE Name NOT LIKE 'A%'
In this case, all names other than Ada and Agnes are returned.
_ The underscore operator is used with WHERE clauses and is performed
when you do not know the second value, such as:

SELECT *

FROM Employees
WHERE BillingShippingState LIKE 'A_'
The result, in this case, returns all states that begin with the letter A,
such as AK, AL, AR, and AZ.
% The multiple-character operator is similar to the underscore operator
except that it allows for multiple characters, whereas the underscore
operator allows for only two. This operator is used in more situations
than the underscore operator.


SELECT *
FROM Employees
WHERE EmployeeID = 1 AND EmployeeID = 2
OR

Typically used with the WHERE clause in the SELECT statement. The OR
operator can be used when a certain condition needs to be met or
when you can settle for a second, such as:

SELECT *
FROM Employees
WHERE EmployeeID = 1 OR EmployeeID = 2
LIKE

The LIKE operator is generally used with WHERE clauses when a
wildcard needs to be performed, such as:

SELECT *
FROM Employees
WHERE Name LIKE 'A%'



This result returns all employees whose names start with A. Our result
returns Ada and Agnes because both their names begin with the letter
A.
NOT

Typically used in conjunction with the LIKE operator, the NOT operator
is used when a value is not going to be LIKE the value of a second,
such as:

SELECT *
FROM Employees
WHERE Name NOT LIKE 'A%'


In this case, all names other than Ada and Agnes are returned.
_

The underscore operator is used with WHERE clauses and is performed
when you do not know the second value, such as:

SELECT *
FROM Employees
WHERE BillingShippingState LIKE 'A_'


The result, in this case, returns all states that begin with the letter A,
such as AK, AL, AR, and AZ.
%


The multiple-character operator is similar to the underscore operator
except that it allows for multiple characters, whereas the underscore
operator allows for only two. This operator is used in more situations
than the underscore operator.


Functions
Aside from using operators to manually construct expressions, SQL provides built-in functions (small blocks
of code that can perform operations and return a value) you can use.
Functions are available simply by making a call to them and passing the value and/or values on which you
want the function to operate.
Note
The functions outlined in the next sections represent a generic list of SQL functions. It's important to
realize that not all databases support the same functions. Although some databases support similar
functions, the way the function is written can differ syntactically from database to database. In the
next sections, I'll provide you with a broad list of these functions. It's up to you however, to consult
your database documentation for the appropriate syntax variation for the function.
Date and Time Functions
Date and Time functions allow for manipulations using dates and times that are stored within your database.
For instance, if you wanted to return all items from the Orders table that were purchased on October 30,
2007, you might write the following code:
SELECT *
FROM Orders
WHERE DatePurchased LIKE '10/30/2007'
This code would produce the following results:
OrderID
EmployeeID
ItemID
Quantity

DatePurchased
24
3
2
1
10/30/07
If you wanted to find all the orders from the previous month, you could use the DateAdd() function:
SELECT *
FROM Orders
WHERE DatePurchased > DateAdd(m, -1, Date())
Assuming that the current date was 6/30/05, the results would be as follows:
OrderID
EmployeeID
ItemID
Quantity
DatePurchased
24
3
2
1
6/15/05
2
2
2
1
6/11/05
11
6
3
1

6/14/05
Tip
In the preceding example, we included three values within parenthesis of the DateAdd function.
These values are known as parameters. Parameters are values that you pass into the function so that
it knows what to do or how to return the value.
Also notice that the DateAdd() function accepts parameters. These parameters include the following:
This parameter specifies which part of the date/time object you want to work with. Typically, you
would want to use one of a few values: m for month, w for week, d for day, h for hour, n for minute, s
for second, and so forth.
How much time to add or subtract—In the preceding example, I subtracted one month.
The date you want to use—In the preceding example, I called another function, the system date, as
the date I wanted to use. When you use the Date() function, you are effectively reading the date and
time from the computer and passing it in as a value.
There are many other Date and Time functions. Too many, in fact, to cover in this small section. Date and
Time functions are among the widely used functions in SQL and are worth the research.
The Count() Function
One of the most obvious functions available is the Count() function. The Count() function is used when you
want to perform a count of records. Consider the following data from the Orders table:
OrderID
EmployeeID
ItemID
Quantity
DatePurchased
24
3
2
1
6/30/05
2
2

2
2
6/30/05
11
6
3
2
6/30/05
You could use the following code to count the number of orders you have taken in a day from the Orders
table:
SELECT Count(Quantity) AS NumberOfOrders
FROM Orders
The statement would result in the following:
NumberOfOrders
3
Notice that you pass in the field name as a parameter in the Count() function. The parameter is evaluated,
and a value is returned into a virtual field named NumberOfOrders.
The Sum() Function
Unlike the Count() function that returns a value from a calculation on the number of fields, the Sum()
function performs a calculation on data within those fields. If, for instance, you needed to know the total
number of items you sold, you could modify the preceding statement to read:
SELECT Sum(Quantity) AS Total
FROM Orders
The statement would produce the following results:
Total
5
Rather than simply doing a count on the records, the sum is calculated based on the values within the
specified field. Because a total of five items were ordered, this value is shown.
The Avg() Function
The Avg() function returns the average of values in specific fields. Consider the following orders in the

Orders table:
OrderID
EmployeeID
ItemID
Quantity
DatePurchased
24
3
2
1
6/30/05
2
2
2
3
6/30/05
11
6
3
5
6/30/05
To get the total average of items being ordered, we might write a statement that resembled the following:
SELECT Avg(Quantity) AS Average
FROM Orders
The statement would produce the following result:
Average
3
Of course, this is because the average of the numbers 1, 3, and 5 is 3.
The Min() and Max() Functions
The Min() and Max() functions enable you to find the smallest and largest values of a specific record. To get

the minimum quantity ordered, you could write a statement such as this one:
SELECT Min(Quantity) AS Minimum
FROM Orders
Based on the Orders table data from the previous section, the preceding statement produces this result
(because the minimum value in the Quantity field is 1):
Minimum
1
To receive the maximum value of a record in the database, try this statement:
SELECT MAX(Quantity) AS Maximum
FROM Orders
Based on the Orders table data from the previous section, the preceding statement produces this result
(because the maximum value in the Quantity field is 5):
Maximum
5
Arithmetic Functions
Aside from using Sum(), Min(), Max(), and Avg(), a few other arithmetic functions can help you when
calculating fields in your database. They are as follows:
Function
Description

Abs()

Returns the absolute value.
Ceil()

Returns the largest integer value not greater than the
value.
Floor()

Returns the smallest integer value not greater than the

value.
Cos()

Returns the cosine of the value where the value is
provided in radians.
Cosh()

Returns the hyperbolic cosine of the value where the
value is provided in radians.
Sin()

Returns the sine of the value where the value is provided
in radians.
Sinh()

Returns the hyperbolic sine of the value where the value
is provided in radians.
Tan()

Returns the tangent of the value where the value is
provided in radians.
Tanh()

Returns the hyperbolic tangent of the value where the
value is provided in radians.
Exp()

Returns the mathematical constant e raised to the
provided exponential value.
Mod()


Returns the remainder of a value divided by a second
value.
Sign()

Returns the sign of the argument as –1, 0, or 1,
depending on whether the value is negative, zero, or
positive.
Sqrt()

Returns the non-negative square root of a value.
Power()

Returns the result of a value raised to the power of a
second value.
Function
Description

Ln() Returns the natural logarithm of a value.
Log() Returns the logarithm of a value in the base of a second
value.
String Functions
String functions are similar to other functions except that they work with literal text values rather than
numerical values. The following string functions are the most common:
Function Description
Chr() Converts an ASCII value to its string equivalent.
Concat() Concatenates (merges) two strings into one.
Initcap() Capitalizes the first letter of each word in
provided string.
Upper() Returns the provided string in all uppercase.

Lower() Returns the provided string in all lowercase.
Lpad() Returns a value padded on the left based on the
numerical value you specify.
Rpad() Returns a value padded on the right based on the
numerical value you specify.
Ltrim() Trims a specified amount of space or characters
off the left side of a string.
Rtrim() Trims a specified amount of space or characters
off the right side of a string.
Replace() Changes a portion of the string with a value that
you specify. Replace() takes three values:
string, target, and replacement string.
Substr() Returns the substring of a value that begins at a
positive value and is certain number of
characters long. Substr() takes three values:
string, position, and length.
Length() Returns the string length in number of
characters.

Ln()

Returns the natural logarithm of a value.
Log()

Returns the logarithm of a value in the base of a second
value.
String Functions
String functions are similar to other functions except that they work with literal text values rather than
numerical values. The following string functions are the most common:
Function

Description
Chr()
Converts an ASCII value to its string equivalent.
Concat()
Concatenates (merges) two strings into one.
Initcap()
Capitalizes the first letter of each word in
provided string.
Upper()
Returns the provided string in all uppercase.
Lower()
Returns the provided string in all lowercase.
Lpad()
Returns a value padded on the left based on the
numerical value you specify.
Rpad()
Returns a value padded on the right based on the
numerical value you specify.
Ltrim()
Trims a specified amount of space or characters
off the left side of a string.
Rtrim()
Trims a specified amount of space or characters
off the right side of a string.
Replace()
Changes a portion of the string with a value that
you specify. Replace() takes three values:
string, target, and replacement string.
Substr()
Returns the substring of a value that begins at a

positive value and is certain number of
characters long. Substr() takes three values:
string, position, and length.
Length()
Returns the string length in number of
characters.


Joins
Up to this point, you have focused primarily on extracting data from a single table. Depending on how
advanced your database becomes, at times you might want to extract data from multiple tables at once. If
that is the case, you will need to use joins. Although there are several types of joins, two types will be
covered here:
Inner joins
Outer joins
Inner Joins
Of the different types of joins, inner joins are by far the most popular. Inner joins enable you to see all the
records of two tables that have a relationship established. Remember that the Employees and the
CreditCards tables have a one-to-many relationship established. The two tables in the Vecta Corp database
resemble the following:
EmployeeID
Name

1
Ada

2
Agnes

3

Cammy

4
Dave




EmployeeID
Type
Number
1
Visa
6345438789678076
2
Visa
3456878097356256
3
Visa
3276798579737256
4
Visa
4357568356245244



Assume that you wanted to extract the information from the Employees table for EmployeeID 2. If not for
inner joins, you would have to use two SELECT statements as follows:
SELECT *
FROM Employees

WHERE EmployeeID = 2
and
SELECT *
FROM CreditCards
WHERE EmployeeID = 2
You can begin to see how tedious this could get, not to mention that it is completely inefficient. To solve this
problem, an INNER JOIN could be used as follows:
SELECT
Employees.EmployeeID, Employees.Name,
CreditCards.Type, CreditCards.Number
FROM Employees
INNER JOIN CreditCards
ON Employees.EmployeeID = CreditCards.EmployeeID
The join effectively produces one virtual table with the following results:
EmployeeID
Name
Type
Number
1
Ada
Visa
6345438789678076
2
Agnes
Visa
3456878097356256
3
Cammy
Visa
3276798579737256

4
Dave
Visa
4357568356245244




Notice that the preceding table now becomes more efficient and manageable. Also notice that, rather than
referencing the names of the tables, you used the TableName.Field notation. This is crucial when using
joins; otherwise, you would end up with two EmployeeIDs without a direct reference to its corresponding
table.
Note
Note the use of the ON operator in the preceding SQL INNER JOIN statement. The ON operator
instructs the SQL statement to join two tables on a specific primary and foreign key pairing.
Outer Joins
Outer joins enable rows to be returned from a join in which one of the tables does not contain matching
rows for the other table. Suppose that you have two tables that contain the following information:
EmployeeID
Name
AddressID
2
Ada
45634
4
Agnes
34754
5
Cammy


10
Dave
97895



AddressID
Address

45634
555 Sample St., San Diego
34754
343 Chestnut Rd., San Diego
97895
523 Main St., San Diego


Consider the following INNER JOIN statement, issued on the preceding tables:
SELECT
Employees.Name, Employees.AddressID,
Address.AddressID, Address.Address
FROM Employees
INNER JOIN Address
ON Employees.AddressID = Address.AddressID
It returns the following results:
Name
AddressID
Address
Ada
45634

555 Sample St., San Diego
Agnes
34754
343 Chestnut Rd., San Diego
Dave
97895
523 Main St., San Diego
Notice that the record that did not contain an AddressID was excluded. Now consider the following OUTER
JOIN statement:
SELECT
Employees.Name, Employees.AddressID,
Address.AddressID, Address.Address
FROM Employees
OUTER JOIN Address ON Employees.AddressID = Address.AddressID
The results of this statement are slightly different:
FirstName
AddressID
Address
Ada
45634
555 Sample St., San Diego
Agnes
34754
343 Chestnut Rd., San Diego
Dave
97895
523 Main St., San Diego
Cammy



As you can see, in the case of the OUTER JOIN, all data is returned, even if no address is present for
Cammy.

×