Professional Documents
Culture Documents
Lesson objectives
To be able to understand database concepts, you will:
· Explain the term database and describe what it typically consists of.
A client/server architecture is made up of a server and one or more clients. In this model,
processing functions are distributed between the server and client to provide greater efficiency.
The server, or back-end, is responsible for such tasks as optimizing and parsing queries,
processing data and queries, and returning the results.
A client, or front-end, is usually a PC. This computer contains software to enable users to access
and work with the data on the server. For example, with a client you can write and send queries
to the server, and analyze the results when they are returned with such tools as graphs and
reports.
In developing this course, a client/server architecture was used. Microsoft SQL Server was the
software running on the back-end to enable that computer to understand and process requests.
SQL Server Query Analyzer was the application running on the front-end to provide an
environment in which to write the requests and view the results. Transact-SQL was the language
version used to compose the requests.
Keep in mind that this is only one example of a database management system. Other software is
available for the server, such as Oracle. Similarly, other software is available for the client, such
as Access. Finally, there are even other variations of the SQL language.
In an effort to maintain some similarity among language versions, the American National
Standards Institute (ANSI) is responsible for setting standards for languages such as SQL.
Transact-SQL is extremely close to ANSI-SQL; therefore, it provides a good introduction to the
language. This course is primarily concerned with those standards that are applicable across
software products and generally refrains from discussing product-specific information.
Using a Query Editor to Access a Database
The software running on a client is sometimes referred to as the front-end application. The
phrase front-end refers to the fact that the application provides a user-friendly tool to
communicate with the server working behind-the-scenes. As mentioned earlier, there are many
front-end applications available to create SQL statements. Each of these applications may look
and work slightly different from its counterparts; however, the overall purpose of each is the
same. The examples of front-end applications you will see in this course are SQL Server Query
Analyzer, and Microsoft Access.
An Introduction to the SQL Server Query Analyzer
The SQL Server Query Analyzer is the front-end application used in developing this course. It
provides a generic, yet user-friendly, editing environment in which to compose SQL statements.
Follow the steps given below to learn how to work with the SQL Server Query Analyzer...
1. List and describe the three language components that currently make up SQL.
The three language components are: DML (Data Manipulation Language) that provides
statements to enable the user to query, update, delete, or insert database information. DDL (Data
Definition Language) that provides statements to enable a database designer to create and delete
such database objects as tables, views, and indexes. DCL (Data Control Language) that provides
statements to enable a database administrator to grant and revoke privileges to the database.
2. What is the function of the SQL Server Query Analyzer?
It is the front-end application used to provide a generic, user-friendly editing environment in
which to compose SQL statements. It is a front-end tool and it communicates with the server that
is working behind the scenes.
An Overview of the SELECT Statement
Lesson objectives
To be able to use a select statement, you will:
· In the SELECT clause, if more than one column is listed, each column must be separated
by a comma (,).
After these rules are followed, you are left to your own creativity. For example, columns must be
separated by a comma; however, once that is done, you can decide whether they will also have a
space between them, or no space between them, or if they will be written on separate lines. Your
goal is to achieve clarity. Use your best judgement to write statements that are easy to read and
understand.
Each of the following SELECT clauses is acceptable:
· SELECT bktitle, devcost, pubdate
· SELECT bktitle,devcost,pubdate
· SELECT bktitle,
devcost,
pubdate
Throughout this book, queries are written with each clause beginning on its own line. The second
bullet below is an example of this style. However, this style was chosen for clarity and is not
required. Both of the following queries are correct:
· SELECT bktitle, devcost FROM titles
· SELECT bktitle, devcost
FROM titles
Rearranging the Order of the Results
The order of the columns in the SELECT clause determines the order in which the results are
displayed. Therefore, the user has control over this display. In the SELECT clause, list the
columns in the order in which you desire to see them in the results.
Viewing all Columns in the Output
In addition to retrieving one or two columns from a table, it might be necessary to retrieve all
columns from a table. This type of SELECT statement would need to include all column names
and, depending on the size of the table, this could be a large amount of typing. You will be glad
to know that the asterisk (*) can be used as shorthand. Use the asterisk when you want to retrieve
all columns of information in the table listed in the FROM clause.
Generic example:
SELECT *
FROM table
Applied example:
SELECT *
FROM titles
The order of the columns displayed in the result is identical to the order in which the columns
appear in the original table. You have no control over the ordering of the display when the
asterisk is used.
1. What are the syntax rules to follow when writing SELECT statements?
The syntax rules to follow are: Each keyword should be followed by a space. In the SELECT
clause, if more than one column is listed, each column must be separated by a comma.
2. Write the syntax for viewing all the columns of information in a table.
SELECT * FROM table
Syntax Rules You'll Want to Know
Lesson objectives
To be able to understand syntax rules, you will:
· In the SELECT clause, if more than one column is listed, each column must be separated
by a comma (,).
After these rules are followed, you are left to your own creativity. For example, columns must be
separated by a comma; however, once that is done, you can decide whether they will also have a
space between them, or no space between them, or if they will be written on separate lines. Your
goal is to achieve clarity. Use your best judgement to write statements that are easy to read and
understand.
Each of the following SELECT clauses is acceptable:
· SELECT bktitle, devcost, pubdate
· SELECT bktitle,devcost,pubdate
· SELECT bktitle,
devcost,
pubdate
Throughout this book, queries are written with each clause beginning on its own line. The second
bullet below is an example of this style. However, this style was chosen for clarity and is not
required. Both of the following queries are correct:
· SELECT bktitle, devcost FROM titles
· SELECT bktitle, devcost
FROM titles
Rearranging the Order of the Results
The order of the columns in the SELECT clause determines the order in which the results are
displayed. Therefore, the user has control over this display. In the SELECT clause, list the
columns in the order in which you desire to see them in the results.
Viewing all Columns in the Output
In addition to retrieving one or two columns from a table, it might be necessary to retrieve all
columns from a table. This type of SELECT statement would need to include all column names
and, depending on the size of the table, this could be a large amount of typing. You will be glad
to know that the asterisk (*) can be used as shorthand. Use the asterisk when you want to retrieve
all columns of information in the table listed in the FROM clause.
Generic example:
SELECT *
FROM table
Applied example:
SELECT *
FROM titles
The order of the columns displayed in the result is identical to the order in which the columns
appear in the original table. You have no control over the ordering of the display when the
asterisk is used.
. What are the syntax rules to follow when writing SELECT statements?
The syntax rules to follow are: Each keyword should be followed by a space. In the SELECT
clause, if more than one column is listed, each column must be separated by a comma.
2. Write the syntax for viewing all the columns of information in a table.
SELECT * FROM table
Aggregate Functions
Lesson objectives
To be able to use Aggregate functions, you will:
Introduction
Up to this point, you have been writing queries that return data exactly as it is stored in the
Bindery database. The results are very straightforward, but limited in what they can readily
communicate. For example, suppose you want to know what the average sale price is for a
Bindery book? You could write a query to return all the sales prices, get out your trusty
calculator, and perform the math yourself; or, you could write a query to do that for you and
simply return the average sale price. The latter option certainly sounds more appealing. It
involves using aggregate functions.
An aggregate function produces a single, summary value for a group of values in a specified
column.
You can use aggregate functions in two clauses: the SELECT clause and the HAVING clause.
Aggregates require an expression, which is enclosed in parentheses. In general, aggregate
functions are written as follows:
aggregate_function(expression)
An expression is usually a column name, or any combination of column names, constants, and
functions connected by arithmetic operators. It might be helpful to think of the parentheses, (), as
"of." In other words, sum(devcost) could be thought of as "the sum OF the devcost column."
Throughout this book, aggregate function names are capitalized within the topic sections. This is
done only for clarity and is not required syntax.
The SUM and AVG functions will operate only on numeric values and therefore require numeric
expressions. The MAX, MIN, and COUNT functions will operate on all types of data.
Aggregate Functions and NULL Values
Now that you have been introduced to aggregate functions, there is something you should know
about how they work:
Aggregate functions ignore NULL values.
This piece of information will be very important when you interpret results produced by
aggregate functions. A NULL value is used to represent an unknown value. It does not equate to a
value of zero. Therefore, if the development cost, or devcost, of a book is NULL, rest assured
there is a development cost, you just do not know what that cost is.
When you use an aggregate function on a column that contains NULL values, those values are
ignored. For example, suppose your SELECT statement contained the following aggregate
function:
COUNT(devcost)
If there were 90 devcosts in your database, but 3 of them had a value of NULL, the COUNT
function would return 87. The NULL values would be ignored.
Consider the effect on AVG(devcost). Because there are no values for the 3 NULL devcosts, they
are not included in the average calculation. This certainly produces a more accurate result than
averaging the NULLs in as zero values. However, because the data is not 100% accurate (there
are NULLs), it follows that the average will not be 100% accurate. This is very important to note
when interpreting results.
Multiple Aggregates
There is no limit to the number of aggregate functions that you can use in a query. They can be
written on separate lines for clarity, or on a single line. The only requirement is that a comma
separates each function. Each of the following examples is correct:
· SELECT aggregate_fcn(col),aggregate_fcn(col)
· SELECT aggregate_fcn(col), aggregate_fcn(col)
· SELECT aggregate_fcn(col),
aggregate_fcn(col)
In the SQL Server Query Analyzer, aggregate functions are not automatically given a column
heading in the output. This is addressed in Topic B of this lesson.
Distinct Aggregates
The DISTINCT keyword can be added to aggregate functions to eliminate duplicate values
before a calculation is performed. For example, AVG(DISTINCT slprice) would include a
specific value only once in the average; whereas AVG(slprice) would include all prices in the
average, even if they were duplicated. Similarly, COUNT(DISTINCT slprice) would include a
specific value once in the count; any duplicates would not be counted. COUNT(slprice) would
count all sale prices.
TIP The DISTINCT keyword does not have to be used with aggregate functions only.
:
Generic example:
SELECT AVG(DISTINCT col)
FROM table
As illustrated in the examples above, the word DISTINCT must be written inside the parentheses
before the argument; however, the word DISTINCT does not have to be capitalized. DISTINCT
is not used with MAX and MIN functions.
1. What are Aggregate functions?
Aggregate functions, such as AVG, COUNT, MAX, MIN, SUM, produce a single summary
value for a group of values in a specified column.
2. What is the DISTINCT keyword used for?
The DISTINCT keyword is added to aggregate functions to eliminate duplicate values before a
calculation is performed.
Column Aliases
Lesson objectives
To be able to use column aliases, you will:
· Explain the use of column aliases for both aggregate and non-aggregate columns.
Introduction
As you have seen, if you're using the SQL Server Query Analyzer, aggregate columns are not
automatically given a heading in the results. This can make reading and interpreting the results a
challenge.
You can remedy this, however, by creating your own headings for these columns. These headings
are called column aliases. To create a column alias, simply add the desired column heading after
the appropriate argument in the SELECT statement. Some things to keep in mind when creating
column aliases:
· If the alias has any spaces, then the alias should be inside single quotes. Although you can
use double quotes, single quotes are recommended to be in compliance with ANSI
standards, thereby making SQL applications more portable.
TIP If you are using an Oracle database, column aliases must be inside double
: quotes(""). Like Transact_SQL, Oracle databases also have a limit of 30 characters
for column aliases.
Following are some generic examples of code:
SELECT ColumnAlias = AVG(col)
FROM table
FROM table
FROM table
Performing Calculations
Lesson objectives
To be able to perform calculations, you will:
FROM table
Applied example:
FROM slspers
There are several functions available to manipulate strings. One such function is the RTRIM
function. This function trims space to the right of a given string. It is used as follows to reduce
the blank space to the right of the specified column or expression:
RTRIM(expression)
Date Functions
Lesson objectives
To be able to use date functions, you will:
TIP If you are using an Oracle database, the to_char function is used to specify a date
: formt. It looks like this: to_char(pubdate,'Day dth Month yyyy') where "Day"
represents the day of the week. If you choose not to use the to_char function, dates
must be specified in the following format: 'DD-MON-YY', such as '13-JUL-99'.
TIP If you are using Oracle, the months_between function returns the difference in
: months between dates. If you use the minus sign(-) between the two dates instead,
the difference is given in days.
The following is a list of functions, their arguments, and their descriptions. If you are not using
Transact-SQL, use your SQL reference material to determine if each of these functions is
available and what syntax is required.
TIP Date functions are not a part of ANSI SQL, and the syntax or very existence of such
: functions will differ in Oracle, Informix, and so forth.
1. Explain the purpose of Date functions.
Date functions are used to manipulate date/time values and return a value you can easily read and
understand.
2. Explain what the datepart function does?
The datepart function is used to return a specified portion of the date (hour, day, month, year) as
an integer.
· Explain the syntax for using the LIKE keyword in a WHERE clause
Introduction
In addition to searching for rows that meet a numeric criteria, you can also search for rows that
meet a string criteria. The LIKE keyword is used to match portions of character strings. A
character string is made up of alphabetic and numeric characters. Numeric characters are
considered text; they do not have a value.
You can use wildcards in conjunction with the LIKE keyword for a more powerful effect. Below
are listed some of the wildcards that may be available in your version of SQL. For further
information, consult your SQL reference material.
When you use the LIKE keyword, the wildcard and character string must be enclosed in single
quotes. Listed below are some examples of how the LIKE keyword might be used with
alphabetic characters, and a corresponding description (Note: Although SQL Server is not case
sensitive, most databases (such as Oracle) are case sensitive. Therefore, it is good practice to
write your search criteria as if the database you are working with were case sensitive.).
TIP If you're using an Oracle database, enclose text in single quotes ('text') when writing
: a text comparison. Also remember Oracle databases are case sensitive.
Although these examples deal with letters, keep in mind that numeric characters can also be used
with the LIKE keyword. Below is an example of using the LIKE keyword in a query to find all
customer numbers that begin with a "9." Because these are numeric characters, the customer
number is considered text rather than a value.
Here is a generic example:
SELECT col1, col2, col3_FROM table_WHERE condition LIKE condition
Here is an applied example:
SELECT custnum_FROM customer_WHERE custnum LIKE `9%'
1. Explain what the LIKE keyword is used for?
The LIKE keyword is used to match portions of character strings which could be made up of
alphabetic and numeric characters.
2. Write an example of a WHERE clause that uses the LIKE keyword to search for a numeric
string of your choice.
select bktitle, partnum from titles where partnum like '406%'
Logical Operators
Lesson objectives
To be able to use logical operators, you will:
The HAVING clause specifies a condition that is similar to the purpose of a WHERE clause;
however, these two clauses are not interchangeable. Listed below are some differences to help
distinguish between the two:
· The WHERE clause can be used without the GROUP BY clause; the HAVING clause
cannot be used without the GROUP BY clause.
· The WHERE clause selects rows before grouping; the HAVING clause selects rows after
grouping.
· The WHERE clause cannot contain aggregate functions; the HAVING clause can contain
aggregate functions.
1. Find the book title and sale price of books whose sale price is over $32.
select bktitle, slpricefrom titleswhere slprice > 32 There should be 41 records listed in the
Results page.
2. Find the customer number, sale date, and the sum of all books sold for each sale date. Only
include books sold after the month of March.
select custnum, sldate, sum(qty)from saleswhere datepart(month, sldate) > 3group by custnum,
sldate There should be 64 records listed.
3. Find the sale date, and total books sold each day. Only include days in which the total
exceeded $600.
select sldate, sum(qty)from salesgroup by sldatehaving sum(qty) > 600 There should be 7
records listed.
1. Compare the WHERE and HAVING clauses.
The WHERE clause can be used without the GROUP BY clause; the HAVING clause cannot be
used without the GROUP BY clause. The WHERE clause selects rows before grouping; the
HAVING clause selects rows after grouping. The WHERE clause cannot contain aggregate
functions; the HAVING clause can contain aggregate functions.
2. Write a SELECT statement to find the book titles and development costs of only those books
titled 'How to'.
select bktitle, devcost from titles where bktitle like 'How to %'
Joins
Lesson objectives
To be able to use joins, you will:
· State the syntax for constructing two and three table joins.
· Explain the difference between the left outer join and the right outer join.
Using Outer Joins
The inner join, discussed in Topic B of this lesson, returns only those rows that satisfy the join
condition. Sometimes, in addition to that information, it is necessary to return rows from one
table that do not satisfy the condition. This is known as an outer join. In the graphical
representation below, an outer join performed on Table A will return rows from areas 1 and 3; an
outer join performed on Table B will return rows from areas 2 and 3.
Typically, an outer join returns all rows that satisfy a join condition and all rows that did not
qualify from the specified table. Some SQL systems provide additional outer-join operators, such
as the asterisk (*), to specify which table the outer join is to be performed on. For example in
Transact-SQL:
*= returns all rows from the first-named table (referred to as a left outer join)
=* returns all rows from the second-named table (referred to as a right outer join)
TIP If you are using an Oracle database, the plus sign (+) is substituted for the asterisk.
: For example, a left outer join would be represented as +=. A right outer join would
be represented as =+.
The following example will return all titles, even those that did not sell. This is considered a left
outer join.
Here is an applied example:
SELECT bktitle, sum(qty)
FROM titles AS t
LEFT OUTER JOIN sales AS s ON t.partnum* = s.partnum
GROUP BY bktitle
1. Explain what is an Outer join?
Typically an outer join returns all rows that satisfy a join condition and also all rows that did not
qualify from the specified table.
2. What is the difference between the left outer join and the right outer join and how does it
work?
In some SQL systems, the asterisk (*) may be used as an additional outer join operator to specify
which table the outer join is to be performed on. In Transact-SQL, the *= returns all rows from
the first-named table. This is referred to as a left outer join. the =* returns all rows from the
second-named table. This is referred to as a right outer join.
Querying a Database
Lesson objectives
To be able to query a database, you will: