Listing 15.61 traverses the hierarchy byusing multiple self-joins to trace the chain of command from employee WS3 to the top of the tree.. In Microsoft SQL Server and DB2, to list everyo
Trang 1Listing 15.61 traverses the hierarchy by
using multiple self-joins to trace the chain
of command from employee WS3 to the top
of the tree See Figure 15.45 for the result.
Unfortunately, you must know the depth of
the hierarchy before you write this query;
use one of the alternatives given in the tip,
if possible
Listing 15.61 Show the full hierarchical relationship of
employee WS3 See Figure 15.45 for the result.
SELECT h1.emp_title || ' < ' ||
h2.emp_title || ' < ' ||
h3.emp_title || ' < ' ||
h4.emp_title
AS chain_of_command FROM hier h1, hier h2, hier h3, hier h4 WHERE h1.emp_title = 'WS3'
AND h1.boss_id = h2.emp_id AND h2.boss_id = h3.emp_id AND h3.boss_id = h4.emp_id;
Listing
chain_of_command -WS3 < DIR1 < VP1 < CEO
Figure 15.45 Result of Listing 15.61.
Trang 2In Microsoft SQL Server and DB2, to
list everyone who reports to a particular employee (VP1, in this example), either directly or indirectly (through a boss’s boss), use this query:
WITH recurse (emp_title, emp_id) AS (SELECT emp_title,emp_id
FROM hier WHERE emp_title = 'VP1' UNION ALL
SELECT hier.emp_title, hier.emp_id FROM hier, recurse
WHERE recurse.emp_id = hier.boss_id )
SELECT emp_title AS "Works for VP1"
FROM recurse WHERE emp_title <> 'VP1';
In Oracle 10g or later, use the
(nonstan-dard) CONNECT BYsyntax to traverse a hierarchy The following query is equiva-lent to Listing 15.61:
SELECT LTRIM(SYS_CONNECT_BY_PATH(
emp_title, ' < '), ' < ')
AS chain_of_command FROM hier
WHERE LEVEL = 4 START WITH emp_title = 'WS3' CONNECT BY PRIOR boss_id = emp_id;
In Oracle 10g or later, to list everyone
who reports to a particular employee (VP1, in this example), either directly or indirectly (through a boss’s boss), use this query:
SELECT emp_title AS "Works for VP1"
FROM hier WHERE emp_title <> 'VP1' START WITH emp_title = 'VP1' CONNECT BY PRIOR emp_id = boss_id;
✔ Tip
Microsoft Access and
Microsoft SQL Server, change each
||to+ In MySQL, use CONCAT()to
con-catenate strings See “Concatenating
Strings with ||” in Chapter 5
In Microsoft SQL Server and DB2, use
the (standard) recursive WITHclause to
traverse a hierarchy The following query
is equivalent to Listing 15.61 (in SQL
Server, change each ||to+.):
WITH recurse (chain, emp_level,
boss_id) AS
(SELECT
CAST(emp_title
AS VARCHAR(50)),
0,
boss_id
FROM hier
WHERE emp_title = 'WS3'
UNION ALL
SELECT
CAST(recurse.chain || ' < ' ||
hier.emp_title
AS VARCHAR(50)),
recurse.emp_level + 1,
hier.boss_id
FROM hier, recurse
WHERE recurse.boss_id =
hier.emp_id
)
SELECT chain AS chain_of_command
FROM recurse
WHERE emp_level = 3;
Trang 3Listing 15.62 traverses the hierarchy by
using multiple UNIONs and self-joins to trace
the chain of command for every employee
See Figure 15.46 for the result
Unfortu-nately, you must know the maximum depth
of the hierarchy before you write this query;
use one of the alternatives given in the tip,
if possible
✔ Tip
■ Microsoft Access won’t
run Listing 15.62 because of the restrictions Access puts on join
expressions
To run Listing 15.62 in Microsoft SQL
Server, change each ||to+
To run Listing 15.62 in MySQL, use
CONCAT()instead of ||to concatenate
strings
In Microsoft SQL Server and DB2, use
the (standard) recursive WITHclause to
traverse a hierarchy The following query
is equivalent to Listing 15.62 (in SQL
Server, change each ||to+.):
WITH recurse (emp_title, emp_id) AS
(SELECT
CAST(emp_title
AS VARCHAR(50)), emp_id
FROM hier
WHERE boss_id IS NULL
UNION ALL
SELECT
CAST(recurse.emp_title ||
' > ' ||
h1.emp_title
AS VARCHAR(50)), h1.emp_id
FROM hier h1, recurse
WHERE h1.boss_id =
recurse.emp_id )
SELECT emp_title emp_tree
Listing 15.62 Show the full hierarchal relationship of
every employee See Figure 15.46 for the result.
SELECT chain AS chains_of_command FROM
(SELECT emp_title as chain FROM hier
WHERE boss_id IS NULL UNION
SELECT h1.emp_title || ' > ' ||
h2.emp_title FROM hier h1 INNER JOIN hier h2
ON (h1.emp_id = h2.boss_id) WHERE h1.boss_id IS NULL UNION
SELECT h1.emp_title || ' > ' ||
h2.emp_title || ' > ' ||
h3.emp_title FROM hier h1 INNER JOIN hier h2
ON (h1.emp_id = h2.boss_id) LEFT OUTER JOIN hier h3
ON (h2.emp_id = h3.boss_id) WHERE h1.emp_title = 'CEO' UNION
SELECT h1.emp_title || ' > ' ||
h2.emp_title || ' > ' ||
h3.emp_title || ' > ' ||
h4.emp_title FROM hier h1 INNER JOIN hier h2
ON (h1.emp_id = h2.boss_id) INNER JOIN hier h3
ON (h2.emp_id = h3.boss_id) LEFT OUTER JOIN hier h4
ON (h3.emp_id = h4.boss_id) WHERE h1.emp_title = 'CEO' ) chains
WHERE chain IS NOT NULL ORDER BY chain;
Listing
Trang 4In Oracle 10g or later, use the
(nonstan-dard) CONNECT BYsyntax to traverse a hierarchy The following query is equiva-lent to Listing 15.62:
SELECT ltrim(SYS_CONNECT_BY_PATH(
emp_title, ' > '),' > ')
AS chains_of_command FROM hier
START WITH boss_id IS NULL CONNECT BY PRIOR emp_id = boss_id;
chains_of_command
-CEO
CEO > VP1
CEO > VP1 > DIR1
CEO > VP1 > DIR1 > WS1
CEO > VP1 > DIR1 > WS2
CEO > VP1 > DIR1 > WS3
CEO > VP1 > DIR2
CEO > VP2
CEO > VP2 > DIR3
CEO > VP2 > DIR3 > WS4
CEO > VP2 > DIR3 > WS5
Figure 15.46 Result of Listing 15.62.
Trang 5Listing 15.63 uses scalar subqueries to
determine whether each node in the
hierar-chy is a root, branch, or leaf node See
Figure 15.47 for the result A zero in the
result denotes True; nonzero, False
✔ Tip
Microsoft Access, change
eachSIGNtoSGN
In Oracle 10g or later, use the
(nonstan-dard) CONNECT BYsyntax to traverse a
hierarchy The following query is
equiva-lent to Listing 15.63:
SELECT
emp_title,
(CASE CONNECT_BY_ROOT(emp_title)
WHEN emp_title THEN 1
ELSE 0 END)
AS root_node, (SELECT COUNT(*)
FROM hier h1 WHERE h1.boss_id = hier.emp_id AND hier.boss_id IS NOT NULL AND rownum = 1)
AS branch_node, CONNECT_BY_ISLEAF AS leaf_node
FROM hier
START WITH boss_id IS NULL
CONNECT BY PRIOR emp_id = boss_id
ORDER BY root_node DESC,
branch_node DESC;
Listing 15.63 Determine whether each node is a root,
branch, or leaf node See Figure 15.47 for the result.
SELECT h1.emp_title, (SELECT SIGN(COUNT(*)) FROM hier h2 WHERE h1.emp_id = h2.emp_id AND h2.boss_id IS NULL)
AS root_node, (SELECT SIGN(COUNT(*)) FROM hier h2 WHERE h1.emp_id = h2.boss_id AND h1.boss_id IS NOT NULL)
AS branch_node, (SELECT SIGN(COUNT(*)) FROM hier h2 WHERE 0 = (SELECT COUNT(*) FROM hier h3 WHERE h1.emp_id = h3.boss_id))
AS leaf_node FROM hier h1;
Listing
emp_title root_node branch_node leaf_node
-CEO 1 0 0
VP1 0 1 0
VP2 0 1 0
DIR1 0 1 0
DIR2 0 0 1
DIR3 0 1 0
WS1 0 0 1
WS2 0 0 1
WS3 0 0 1
WS4 0 0 1
WS5 0 0 1
Figure 15.47 Result of Listing 15.63.
Trang 6about this book arrow indicating breaks in code, xvi audience for book, xv–xvi
companion website for, xiv knowledge needed by reader, xiv requirements for using book, xviii syntax conventions used, xvi, xvii typographic conventions used, xvi vendor-specific modifications of SQL, xvii absolute pathnames, 3
Access See Microsoft Access
ACID acronym, 403 addition operator (+), 130, 131–132 aggregate functions, 169–192
creating, 171
filtering groups with HAVING, 169, 190–192
inner join combined with GROUP BYand,
215, 217 listing of, 170
returning single values with subqueries, 276
ALLkeyword, 94, 288–290
alternate keys, 39
Symbols
+ (addition operator), 130, 131–132
\ (backslash), 3
[ ] (brackets), 67, 117
/* */ (bracketed comments), 64
^ (caret), 117
/ (division operator), 130, 131–132
\\ (double backslash), 3
= (equal to operator), 101, 110
> (greater than operator), 101
>= (greater than or equal to operator), 101
< (less than operator), 101
<= (less than or equal to operator), 101
* (multiplication operator), 130, 131–132
<> (not equal to operator), 101
( ) (parentheses), 63, 106
% (percent sign) operator, 114
; (semicolon), 62, 63
'(single quotes), xvi, 70, 71
/ (slash), 3
– (subtraction operator), 130, 131–132
_ (underscore) operator, 114
|| (concatenate operator), 134–136
Trang 7combining with NOTandORoperators, 109
using, 105, 106
ANSI (American National Standards
Institute)
about, xii, xiii
ANSI-89 vs ANSI-92 syntax mode (Access),
5
ANYkeyword
comparing equivalent subqueries using,
301–302
subquery comparisons using, 291–293
approximate numeric types, 75
arguments, 127
arithmetic operators
listing of, 130
order of evaluation of, 133
types of operations using, 127
arrows in code listings, xvi
ASclauses
creating column aliases with, 91–92, 170
table alias creation with, 196–197
ASCclause, 422–428
ASCII encoding, 71
atomic values, 46, 47, 403
authors
author/publisher queries using UNION
operations, 304–307
books written (by publisher), 223–224
books written (by title), 221
calculating greatest number of titles
written
by, 273
comparing values in subqueries with ALL,
289–290
creating table of unpublished, 244, 295
earned royalties by book and, 226–229
finding number of books by, 243, 272
finding pairs by location, 251–252
grouping names of coauthors and sole, 286
join listing cities of publisher and, 238
listed by above-average sales, 278
listing books by, 211
listing by latest date of publications, 272
listing by volume of book sales and, 245
living in different city from publisher, 297,
312
living in publisher’s city, 296, 310 names of sole, 285
outer joins listing all rows with nulls, 239 querying names of co-authors, 284, 285 residing in publisher’s city/state, 213 residing same state as publisher, 276–277 royalty comparisons with subqueries, 279 sorting by genre of writing, 284
sorting by specific location, 249 subquery comparisons using ANY, 292 total book royalties paid by publisher, 233–234
unpublished, 282, 283 using equivalent queries on, 301 writing different genres of books, 298 writing three or more books, 297
adding new rows to and listing, 321–322 creating views of, 388, 389
deleting rows from, 334 structure of, 51, 52
autocommit mode, 404 averages
moving, 407 running, 406
B
backslash (\), 3 balanced trees (B-trees), 382 batch files, 2
batch mode, 2
binary table operations, 36 BLOB (binary large object) data types, 72 books
advances by genre, 216–217 authors writing three or more, 297
by author and listed by publisher, 223–224 calculating running sum and average for, 406
changing prices by genre, 328 comparing values in subqueries with ALL, 289–290
computing running sum of sales, 273
Trang 8books (continued)
filtering books written by author’s name,
221
finding authors who haven’t written, 282,
283
genres listed by greater sales volume, 250
greatest number written by authors, 273
having above-average sales, 277
listed by sales volume and author, 245
listing authors by latest published, 272
listing by authors, 211
listing number by author, 243, 272
names and IDs of publisher and, 212
place of publication, 214
priced greater than highest price genre, 278
revenues greater than advance, 220
sale prices compared by genre, 280
subqueries listing publishers by genre,
254–255
subquery comparisons using ANY, 292, 293
total royalties for all, 225
types of published by several publishers,
286, 287
updating table values for, 329–330
about, 51
creating sample, 57
listing of books_standard.sqlscript,
57–60
Boolean types, 76
Boyce-Codd normal form (BCNF), 50
bracketed comments (/* */), 64
brackets ([ ])
filter patterns using, 117
using around identifiers, 67
branch nodes, 458
C
calculating statistics
mode, 177
medians, 451–452
overview, 177 running statistics, 406–408, 454–455 sum of set’s values, 174, 179–182 trimmed mean, 432
calendar tables, 414 candidate keys, 39 caret (^), 117
CASEexpression correlated subqueries vs., 274 evaluating conditional values with, 161–164 case sensitivity
changing, 140–141 comparisons and, 140, 173 keyword and identifier, 63 SQL and, xvi
catalogs, 439
character strings See also substrings
case sensitivity of comparisons, 140–141, 173
comparison operators with, 101 concatenating, 134–136 example of string operations, 127 extracting substrings, 137–139 finding length of, 147–148 trimming characters from, 142–146 types of, 70–71
clauses See also specific clauses
about, 62, 63, 64 clients, xv closure property for tables, 36 clustered indexes, 382
Codd, E F., 33, 34, 38 collating sequence, 96 column aliases creating, 91–92 sorting by, 99
columns about, 34, 35, 37 addingUNIQUEconstraints to, 359–362 comparing from similar domains, 199 constraints for, 339–340
creating aliases with ASclauses, 91–92
Trang 9columns (continued)
defining constraints for, 363–365
derived, 128–129
displaying table definitions for, 316–318
grouping, 171, 183, 184
inserting rows in, 320–322
joining unequal values in, 220
modifying with ALTER TABLE, 373–374
nullability in, 343–345
order in composite indexes, 379
qualifying column names, 194–195, 267
retrieving from SELECTandFROMclauses,
88–90
self-joins within, 247–252
sorting rows by, 95–96
specifying relative position for sorting, 97
subqueries vs joins for working with, 261
two tables on, 211–212
unordered, 35
using simple FOREIGN KEYconstraints,
355–356
when to use indexes for, 378
Command Center (IBM DB2 8.x), 21
Command Editor (IBM DB2 9.x), 22
command-line tools
IBM DB2 db2, 23–26
MySQL mysql, 27–29
Oracle sqlplus, 17–19
PostgreSQLpsql, 30–32
SQL Server osql, 11, 12–13
SQL Server sqlcmd, 10, 15
using SQL with, 2, 3
comments, 62, 64
committing transactions
about, 400
using COMMITstatement, 335, 404
companion website, xiv
comparison operators
ALLmodifications to, 288
ANYmodifications to, 291
listing of, 101
using in subqueries, 275–280
comparisons
case sensitivity of, 140, 173
changing string case, 140–141
composite constraints foreign key, 356–357 primary key, 352 unique, 361–362 composite indexes, 378, 379 concatenate operator (||), 134–136 concurrency transparency, 401 conditions
combining and negating, 105–109, 111–112 equivalent, 112–113
filtering lists with IN, 121–123 filtering with BETWEEN, 118–120 matching row patterns with LIKE, 114–117 re-expressing, 113
types of search, 101 consistency in transactions, 403 constant expressions, 128
constants See literal values
constraints altering or dropping, 375 check, 339, 363–365 column and table, 339–340 foreign key, 339, 353 nullability, 343 primary key, 339, 350 unique, 359–362 using CONSTRAINTclauses, 339–340 converting data types, 157–160
correlated subqueries See also subqueries
comparing author’s royalties with subqueries, 279
computing running sum of book sales, 273
including null values in list of books and authors, 272
listing data in spreadsheet fashion with, 271 qualifying column names in, 272
simple vs., 266 correlation variables, 263
about, 170 comparing equivalent subqueries using, 301–302
creating inner joins with GROUP BYclause and, 215, 230–232
Trang 10forms of, 178
listing with duplicate rows with, 436
nulls and, 170, 176
statistics using, 177
creating index with, 378–382
unique indexes vs unique constraints, 362
addingUNIQUEconstraints to columns, 360
defined, 337
defining foreign-key constraint in, 353
table creation with, 337, 338, 341–342
366–368
cross joins
accidentally turning inner to, 210
creating, 204–205
defined, 198
curly quotes, xvi
current date and time, 154–155
cursors, 99
D
data control language (DCL) statement, xiii
data definition language (DDL) statement, xiii
data manipulation language (DML)
statement, xiii
data types
approximate numeric, 75
characteristics of, 68–69
comparing subquery values of same, 275
compatibility of for join columns, 199
converting with CAST(), 157–160
datetime, 77–79
exact numeric, 73–74
interval, 80–81
database management systems See DBMSs;
DBMS-specific SQL features
databases See alsobookssample database
command and queries listing tables in, 318
DBMS vs., x
denormalizing, 50 learning to design, 38 picking random rows, 433–434 providing views of data, 386 recovering and restoring data, 401 renaming tables of, 375
rolling back transactions, 400, 403, 404 sample, xviii
dates listing author and publications by latest, 272
sequence tables for incrementing, 413 using in queries, 445
datetime operations data types for, 77–79 example of, 127 extracting part of, 152–153 formatting and, 90 sequence tables for, 412, 413 DB2 CLP windows, 23
db2command-line tool exiting, 26
interactive mode for, 24 script mode for, 25 showing options for, 26 starting, 23
DBMS icon, xvii
DBMSs (database management systems) See also DBMS-specific SQL features
ANSI-89 vs ANSI-92 syntax mode for (Access), 5
command line for, 2 covered by book, xvii databases vs., x determining SQL Server version running, 10 issuing SQL commands to, xii
running in autocommit mode, 404 SQL servers vs desktop, xv support for SQL, ix transactions in, 399–404 using SQL on, 2–3 using with book, xviii working with indexes, 378–382
DBMS-specific SQL features See also specific database programs
Access versions, 5 aggregate functions, 171