Documente Academic
Documente Profesional
Documente Cultură
The SELECT statement returns information from a database as a set of records without altering
the database. It searches the database, extracts the chosen columns and selects those records
that meet the criteria, sorting and grouping the results into a specified order.
A SELECT statement can be nested inside of another SELECT statement which is nested
inside of another SELECT and so on. When a SELECT is nested it is refered to as a subquery
clause.
At its simplest, you can use an asterisk ( * ) to select all of the fields in a table (in this case the
table 'Musicians' ):
Or you can be more selective and choose just one or a few of the fields in a table, and they will
be returned in the order listed:
You can also have a query display a field under a different heading than the one used in the
table by establishing an "alias" with the reserved word AS:
...and you can even have a query combine two or more fields from a table into one field in the
returned list under a new heading using the ampersand character:
WHERE
You can use the WHERE clause to further focus your selection by specifying certain criteria to
be met by the values. The following example returns the names of all musicians who play the
flute:
...and this example returns the names of all jigs in a 'Tunes' table:
You can combine more than one criterion in a WHERE clause using any of the logical
operators. Here the query returns a list of all items which are blue and cost less than $100:
If you want to get fields from a database other than the one you are currently working in, you
use the IN as a clause:
If the database is a non-Microsoft Jet database, you must append a semicolon ( ; ) to the
database file name and enclose it within a pair of single ( ' ) or double quotes ( " ).
You can also specify a path and designate the type of file. Note the position of the ( ; ):
When used as an operator, IN can determine if the values of a specified expression matches
any values in a specified list. This example determines if any piano tuners live in 'Knoxville',
'Nashville', or 'Memphis'. A pair of single quotes must enclose each value and commas must
separate each value:
You can also add a NOT. This causes the query to select all values other than those listed:
The SELECT statement can optionally be followed by one of these four predicates: ALL,
DISTINCT, DISTINCTROW, TOP. These limit the number of records returned.
The ALL predicate is the default, but it is rarely used. Note that the following two code examples
yield the exact same results:
SELECT *
FROM RockAndRoll
WHERE Artist = 'Elvis';
SELECT ALL *
FROM RockAndRoll
WHERE Artist = 'Elvis';
The DISTINCT predicate is used to omit duplicate values just in a field. Consider a table of
names, where you have the last name, "Jones", repeated numerous times. This code returns
only one "Jones":
The DISTINCTROW predicate is used to omit duplicate values in an entire record of fields. This
can be very useful when you use a INNER JOIN to join two tables together and you do not want
any duplication. This code create a table that does not repeat any of the last names:
SELECT DISTINCTROW LastName
FROM SongWriters INNER JOIN Performers
ORDER BY LastName;
The TOP predicate returns the specified number of records from the top of the specified table.
The following example returns the first 3 records:
You can also carry out calculations on fields containing numeric values using the aggregate
functions:
AVG - average
COUNT - count how many items
MAX - maximum value
MIN - minimum value
This next example uses the COUNT function to count the number of items that have an entry in
the SalePrice field (i.e. they are on sale) and returns that number under the heading
'ReducedCount':
...and this next one returns current prices along with what the prices would be after a 10%
increase:
...and this one lists all items that are reduced along with the price and the amount of the
reduction:
Of course, you may want to select fields from more than one table, and you can do that as well.
In this case it is best to precede a field name with the name of the table from which it comes,
followed by the dot operator ( . ). You must do this for fields of the same name, but from
different tables that are used in the SELECT statement. The following example uses two tables,
Task and Assignment, and returns the names of all Tasks belonging to Assignments that are
incomplete:
As an alternative to using the explicit INNER JOIN syntax, columns from multiple tables can be
combined in a single query by specifying the appropriate table list, and applying the filter
condition in the WHERE clause. This is illustrated in the following query, which returns the same
recordset as the previous example:
The optional GROUP BY clause groups into a single record all records that have identical
values in a particular field or combination of fields. The following example returns a list of the
different products in the Product field of Suppliers.
HAVING
The HAVING clause is optional and qualifies a GROUP BY clause. It is similar to the WHERE
clause but determines which records are displayed after they have been grouped. The following
example displays a list of different items, along with their count, but only where there are more
than one.
ORDER BY
The ORDER BY clause can be used to dictate the order of the records returned. The following
example returns records listed primarily in order of tune type (jigs then reels), and then for each
type the relevant names are also listed in alphabetical order.
SELECT TuneType AS Type, Name FROM Tunes WHERE TuneType = 'jig' OR TuneType =
'reel'
ORDER BY TuneType, Name;
The LIKE operator allows you to compare values in a field to a string (or pattern) and see if
there is a match. In the first example, a list is created of authors who have written a 'Cook Book'.
By using NOT, you can select everything that does not match a specific string. Adding NOT to
the previous example will create a list of all authors in BookList who have not written a 'Cook
Book'.
The LIKE operator can use what are called "wild card characters" to create search pattern
strings. Here are five wild card characters:
[!] Any single character not matching the specified set or range
The use of wild card characters, in the form of a regular expression, can be a very complex
subject. Fortunately, there are several simple ways to use wild cards that are very useful for
pattern matching. By placing a * before and after the string 'Cook Book' (i.e., '*Cook Book*' ) you
can search for a book title that contains the string 'Cook Book'. The * will accept zero or more
characters in the book title before or after the phrase 'Cook Book'.
Wild card characters can be combined together to create search patterns. In the next example,
the expression '[PT]*' searches for two patterns. It will look for all strings that start with a P and
have zero or more additional characters after the P. And it will also look for all strings that start
with a T and have zero or more additional characters after the T. So, Thompson would be
selected, but not Cussler.
In the previous example, by adding a dash (-) between the P and the T, the search pattern will
look for all authors whose last name starts with P, Q, R, S, and T.
'Chapter #' Search for digits 0-9 after the word Chapter
OPERATION: BETWEEN ... AND
SELECT * | list FROM table
WHERE expression [NOT] BETWEEN value1 AND value2
The BETWEEN ... AND operator is used to specify a selection criteria by requiring an
expression to be equal to one of, or fall between the range defined by, two values.
These values can be numbers, characters, strings, or dates, but you cannot use any
wildcard characters. The characters, strings, and dates must be enclosed by a pair of
single quotes.
In this query, we search for song titles released during the 1980s:
By using the NOT operator, you can search for values that lie outside the range:
The ORDER BY clause can be used to dictate the order of the records returned (i.e., how they
are sorted). The following example returns records listed primarily in order of tune type (jigs then
reels), and then for each type the relevant names are also listed in alphabetical order:
SELECT TuneType AS Type, Name FROM Tunes WHERE TuneType = 'jig' OR TuneType =
'reel'
ORDER BY TuneType, Name;
You can specify descending order (the default is ascending order) by adding the reserved word
DESC after the field name. The next example returns a list of all items in ascending alphabetical
order along with their prices in descending numerical order:
When a SELECT statement is nested inside of a DELETE, INSERT ... INTO, SELECT,
SELECT ... INTO, or a UPDATE statement, it is refered to as a subquery clause.
In this example we create a table of Medicare patients who also have dental insurance. The
social security number, ssn, is used as a key to compare the two tables, MediCarePatients and
DentalIns.
If we use a NOT, we create a table of Medicare patients who do not have dental insurance:
There are three reserved words, ALL, ANY, and SOME, that can be used in subqueries to
make comparisons. However, Microsoft states that ALL and SOME are synonymous.