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
Trang 1This chapter has introduced you to some simple, yet important, concepts—mainly data storage You learnedabout the skeleton of a database—which is composed of tables, columns, and rows—and about crucialconcepts 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 Yousaw how to obtain and install the necessary software, how to create tables, columns, and rows, and how toattach/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 tablescontained 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 workwith 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 indata access—SQL
Trang 2Generating Queries Visually
At this point, you are familiar with just how easy it is to create a database using Access, SQL Server 2005Express, or MySQL In the coming chapters, you'll learn just how easy Dreamweaver makes it to extractfrom, 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 eventuallybuild will have a direct impact on how complex your use of a data-access language will be Dreamweaverprovides a simple and easy-to-use process for commonly used data extraction and filtering tasks, but if youtruly want to get the most out of your application, you should become familiar with the topics discussed inthis 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, SQLquickly 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 anintroduction to beginning and advanced SQL statements, clauses, joins, subqueries, and action queries Theconcepts you learn in this chapter will help you, on a more advanced level, interact with data in yourdatabase using Dreamweaver
Trang 3Generating Queries Visually
At this point, you are familiar with just how easy it is to create a database using Access, SQL Server 2005Express, or MySQL In the coming chapters, you'll learn just how easy Dreamweaver makes it to extractfrom, 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 eventuallybuild will have a direct impact on how complex your use of a data-access language will be Dreamweaverprovides a simple and easy-to-use process for commonly used data extraction and filtering tasks, but if youtruly want to get the most out of your application, you should become familiar with the topics discussed inthis 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, SQLquickly 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 anintroduction to beginning and advanced SQL statements, clauses, joins, subqueries, and action queries Theconcepts you learn in this chapter will help you, on a more advanced level, interact with data in yourdatabase using Dreamweaver
Trang 4Basic 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 isthe 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 thatthe EmployeeStore table resembles the table that follows (although this table does not show the
ItemDescription and Headshot columns):
Field Name Date Type
You can then list products in rows that would look like the following:
Consider some important aspects about the previous table and the columns and data contained in the eightrows The EmployeeStore table contains four columns: an ItemID with an AutoNumber that increments avalue whenever an item is added, an ItemName that contains a Text data type allowing for a simple title ofthe 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 anumeric value indicating how many of a specific item we have left in our inventory The last thing to
Trang 5consider 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 ofdata in the table Our next step is to get to our data somehow The next few sections outline how to useSQL 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 statementprovides a means for retrieving the data from the database In its simplest form, the SELECT statement iswritten 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 toextract 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 requiredwith 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 allrecords from the EmployeeStore table The previous statement would produce the following results (somefields have been excluded in order to fit on the page):
Selecting Certain Fields
If you did not want to select all the fields in the database table, you could modify the field names to includeonly the fields that you wanted
SELECT ItemID, ItemName, Cost
Trang 6FROM EmployeeStore
Notice that the preceding statement retrieves the data only from the ItemID, ItemName, and Cost fields.The preceding query produces the following results:
Notice that in this case, the ItemDescription and Quantity columns are left off You could also modify thestatement in an effort to retrieve the same information in a different order For example, we could switchthe field names by placing ItemName in front of ItemID, like this:
SELECT ItemName, ItemID, Cost
FROM EmployeeStore
This code would give the following result:
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 ourdatabase, we would have to modify the statement to produce distinct results The DISTINCT keyword can beused before the Cost field in this case to extract from the table only unique instances of data contained inthat field
SELECT DISTINCT Cost
FROM EmployeeStore
The preceding statement would produce the following result:
Trang 7The 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 didnot exist, it wouldn't return anything But what if we had more than one Ada in the database? You couldrefine 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 samephone number In this situation, the query returns one result (assuming, of course, that the two Adas aren'troommates)
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:
Trang 8EmployeeID Name Email
SELECT *
FROM Employees
ORDER BY Name
The preceding statement would return results in the following order:
EmployeeID Name Email
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
Trang 9When a query statement includes a GROUP BY clause, the SELECT statement for that query can list functionswhile operating on groups of data values in other columns For example, data within the Orders table couldlook similar to the following table:
OrderID EmployeeID ItemID Quantity
You could use the GROUP BY clause in this instance to group the orders by EmployeeID as follows:
SELECT EmployeeID, Count(Quantity) AS NumberOfOrders
The INSERT Statement
Collecting information from your users is not uncommon and, in most cases, it is a necessity When you
Trang 10collect information such as registration information, you're not querying data, but rather you're insertingdata into the database In our Vecta Corp example, for instance, we'll create an Admin page that allowsadministrators to insert new employees into the database To illustrate this point, consider the Employeestable and some of the fields that make it up:
Field Name Date Type
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', 'zak@modulemedia.com', '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 Employeestable 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 onetable to the other:
INSERT INTO Transactions (EmployeeID, Name, Email)
SELECT EmployeeID, Name, Email
Trang 11FROM Employees WHERE EmployeeID = 1
The preceding statement assumes that we have a Transactions table At any rate, this statement effectivelycopies from the Employees table the EmployeeID, Name, and Email whose EmployeeID is equal to 1 andcopies 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 existingrecord 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 thespecific record, for instance:
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 asfollows:
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 youwanted 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, thisdoesn'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 thiswere the case, you could append a WHERE clause to your statement to remove one record:
DELETE
Trang 12WHERE Name = 'Agnes'
This statement removes all records from the Employees table whose Name field matches "Agnes."
Trang 13If 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 inSQL work similarly Consider the following data that could appear in the Employees table:
EmployeeID FirstName LastName
SELECT EmployeeID, FirstName & LastName AS Name
Trang 14Adding the space results in a gap between the first and last names as follows:
Trang 15In 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 withwhich 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:
Trang 16Operator Description
SELECT *FROM EmployeesWHERE 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 orwhen you can settle for a second, such as:
SELECT *FROM EmployeesWHERE 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 EmployeesWHERE 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 letterA
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 EmployeesWHERE 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 EmployeesWHERE 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 underscoreoperator allows for only two This operator is used in more situationsthan 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 orwhen 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 letterA
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 underscoreoperator allows for only two This operator is used in more situationsthan the underscore operator
Trang 17Aside 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 youwant the function to operate
Note
The functions outlined in the next sections represent a generic list of SQL functions It's important torealize that not all databases support the same functions Although some databases support similarfunctions, the way the function is written can differ syntactically from database to database In thenext sections, I'll provide you with a broad list of these functions It's up to you however, to consultyour 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
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
Trang 18In 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, youwould want to use one of a few values: m for month, w for week, d for day, h for hour, n for minute, sfor 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, asthe date I wanted to use When you use the Date() function, you are effectively reading the date andtime 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 andTime 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 youwant to perform a count of records Consider the following data from the Orders table:
OrderID EmployeeID ItemID Quantity DatePurchased
Trang 19Unlike 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 totalnumber of items you sold, you could modify the preceding statement to read:
SELECT Sum(Quantity) AS Total
The Avg() Function
The Avg() function returns the average of values in specific fields Consider the following orders in theOrders table:
OrderID EmployeeID ItemID Quantity DatePurchased
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 getthe 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):
Trang 201
To receive the maximum value of a record in the database, try this statement:
SELECT MAX(Quantity) AS Maximum
Ceil() Returns the largest integer value not greater than the
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
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, orpositive
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
Trang 21Function Description
Ln() Returns the natural logarithm of a value
Log() Returns the logarithm of a value in the base of a second
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 ofcharacters 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:
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 ofcharacters long Substr() takes three values:
string, position, and length
Length() Returns the string length in number of
characters
Trang 23problem, an INNER JOIN could be used as follows:
The join effectively produces one virtual table with the following results:
EmployeeID Name Type Number
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 matchingrows for the other table Suppose that you have two tables that contain the following information:
Trang 24EmployeeID Name AddressID
45634 555 Sample St., San Diego
34754 343 Chestnut Rd., San Diego
97895 523 Main St., San Diego
It returns the following results:
Name AddressID Address
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 OUTERJOIN 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
Cammy
Trang 25As you can see, in the case of the OUTER JOIN, all data is returned, even if no address is present forCammy.