100% found this document useful (2 votes)
32 views77 pages

SQL in A Nutshell, 4th Edition Kevin Kline Instant Download

SQL in a Nutshell, 4th Edition provides a comprehensive overview of SQL, including its history, implementations, and the relational model. The book covers the syntax for various SQL implementations such as ANSI/ISO SQL, MySQL, Oracle, PostgreSQL, and SQL Server. It emphasizes the importance of understanding Codd's principles for relational databases and the significance of data structures and constraints in SQL programming.

Uploaded by

tlmcenhupf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
32 views77 pages

SQL in A Nutshell, 4th Edition Kevin Kline Instant Download

SQL in a Nutshell, 4th Edition provides a comprehensive overview of SQL, including its history, implementations, and the relational model. The book covers the syntax for various SQL implementations such as ANSI/ISO SQL, MySQL, Oracle, PostgreSQL, and SQL Server. It emphasizes the importance of understanding Codd's principles for relational databases and the significance of data structures and constraints in SQL programming.

Uploaded by

tlmcenhupf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

SQL in a Nutshell, 4th Edition Kevin Kline

install download

https://ebookmeta.com/product/sql-in-a-nutshell-4th-edition-
kevin-kline/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

SQL in a Nutshell, 4th Edition (Third Early Release)


Kevin Kline & Regina O. Obe

https://ebookmeta.com/product/sql-in-a-nutshell-4th-edition-
third-early-release-kevin-kline-regina-o-obe/

Python in a Nutshell, 4th Edition Alex Martelli

https://ebookmeta.com/product/python-in-a-nutshell-4th-edition-
alex-martelli/

Consumer Protection Law in a Nutshell 4th Edition Dee


Pridgen Gene Marsh

https://ebookmeta.com/product/consumer-protection-law-in-a-
nutshell-4th-edition-dee-pridgen-gene-marsh/

Charlie s Good Tonight the Life the Times and the


Rolling Stones the Authorized Biography of Charlie
Watts 1st Edition Paul Sexton

https://ebookmeta.com/product/charlie-s-good-tonight-the-life-
the-times-and-the-rolling-stones-the-authorized-biography-of-
charlie-watts-1st-edition-paul-sexton/
Dessert Cookbook: A Dessert Cookbook with Delicious
Dessert Recipes 1st Edition Booksumo Press

https://ebookmeta.com/product/dessert-cookbook-a-dessert-
cookbook-with-delicious-dessert-recipes-1st-edition-booksumo-
press/

You're a Mean One, Matthew Prince (Boy Meets Boy 2) 1st


Edition Timothy Janovsky

https://ebookmeta.com/product/youre-a-mean-one-matthew-prince-
boy-meets-boy-2-1st-edition-timothy-janovsky-2/

All or None Cooperation and Sustainability in Italy s


Red Belt Anthropology of Europe 3 1st Edition Alison
Sánchez Hall

https://ebookmeta.com/product/all-or-none-cooperation-and-
sustainability-in-italy-s-red-belt-anthropology-of-europe-3-1st-
edition-alison-sanchez-hall/

Beginning Algebra, 6th Edition Miller

https://ebookmeta.com/product/beginning-algebra-6th-edition-
miller/

Food Chemistry: The Role of Additives, Preservatives


and Adulteration 1st Edition Mousumi Sen

https://ebookmeta.com/product/food-chemistry-the-role-of-
additives-preservatives-and-adulteration-1st-edition-mousumi-sen/
In the Moment: Build Your Confidence, Communication and
Creativity at Work 1st Edition Neil Mullarkey

https://ebookmeta.com/product/in-the-moment-build-your-
confidence-communication-and-creativity-at-work-1st-edition-neil-
mullarkey/
SQL in a Nutshell
A Desktop Quick Reference

With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.

Kevin Kline, Regina O. Obe, and Leo S. Hsu


SQL in a Nutshell
by Kevin Kline , Regina O. Obe , and Leo S. Hsu
Copyright © 2021 O’Reilly Media. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com ). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
[email protected] .
Acquisitions Editor: Andy Kwan

Development Editor: Rita Fernando

Production Editor: Beth Kelly

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Rebecca Demarest

November 2021: Fourth Edition


Revision History for the Early Release
2021-07-22: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781492088868 for


release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
SQL in a Nutshell , the cover image, and related trade dress are
trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the authors, and do
not represent the publisher’s views. While the publisher and the
authors have used good faith efforts to ensure that the information
and instructions contained in this work are accurate, the publisher
and the authors disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-492-08879-0
[FILL IN]
Chapter 1. SQL History and
Implementations

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 1st chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at [email protected].

In the early 1970s, the seminal work of IBM research fellow Dr. E. F.
Codd led to the development of a relational data model product
called SEQUEL, or Structured English Query Language . SEQUEL
ultimately became SQL, or Structured Query Language .
IBM, along with other relational database vendors, wanted a
standardized method for accessing and manipulating data in a
relational database. Although IBM was the first to develop relational
database theory, Oracle was first to market the technology. Over
time, SQL proved popular enough in the marketplace to attract the
attention of the American National Standards Institute (ANSI) in
cooperation with the International Standards Organization (ISO),
which released standards for SQL in 1986, 1989, 1992, 1999, 2003,
2006, 2011, and 2016.
Since 1986, various competing languages have allowed developers
to access and manipulate relational data. However, few were as easy
to learn or as universally accepted as SQL. Programmers and
administrators now have the benefit of being able to learn a single
language that, with minor adjustments, is applicable to a wide
variety of database platforms, applications, and products.
SQL in a Nutshell , Fourth Edition, provides the syntax for five
common implementations of SQL:
The ANSI/ISO SQL standard

MySQL version 8 and MariaDB 10.5

Oracle Database 19c

PostgreSQL version 13

Microsoft’s SQL Server 2019


The Relational Model and ANSI SQL
Relational database management systems (RDBMSs) such as those
covered in this book are the primary engines of information systems
worldwide, and particularly of web applications and distributed
client/server computing systems. They enable a multitude of users
to quickly and simultaneously access, create, edit, and manipulate
data without impacting other users. They also allow developers to
write useful applications to access their resources and provide
administrators with the capabilities they need to maintain, secure,
and optimize organizational data resources.
An RDBMS is defined as a system whose users view data as a
collection of tables related to each other through common data
values. Data is stored in tables , which are composed of rows and
columns . Tables of independent data can be linked (or related ) to
one another if they each have unique, identifying columns of data
(called keys ) that represent data values held in common. E. F. Codd
first described relational database theory in his landmark paper “A
Relational Model of Data for Large Shared Data Banks,” published in
the Communications of the ACM (Association for Computing
Machinery) in June, 1970. Under Codd’s new relational data model,
data was structured (into tables of rows and columns); manageable
using operations such as selections, projections, and joins; and
consistent as the result of integrity rules such as keys and referential
integrity. Codd also articulated rules that governed how a relational
database should be designed. The process for applying these rules is
now known as normalization .
Codd’s Rules for Relational Database Systems
Codd applied rigorous mathematical theories (primarily set theory)
to the management of data, and he compiled a list of criteria a
database must meet to be considered relational. At its core, the
relational database concept centers around storing data in tables.
This concept is now so common as to seem trivial; however, not long
ago the goal of designing a system capable of sustaining the
relational model was considered a long shot with limited usefulness.
Following are Codd’s Twelve Principles of Relational Databases :
1. Information is represented logically in tables.

2. Data must be logically accessible by table, primary key, and


column.

3. Null values must be uniformly treated as “missing information,”


not as empty strings, blanks, or zeros.

4. Metadata (data about the database) must be stored in the


database just as regular data is.

5. A single language must be able to define data, views, integrity


constraints, authorization, transactions, and data manipulation.

6. Views must show the updates of their base tables and vice
versa.

7. A single operation must be available to do each of the following


operations: retrieve data, insert data, update data, or delete
data.

8. Batch and end-user operations are logically separate from


physical storage and access methods.
9. Batch and end-user operations can change the database
schema without having to recreate it or the applications built
upon it.

10. Integrity constraints must be available and stored in the


metadata, not in an application program.

11. The data manipulation language of the relational system should


not care where or how the physical data is distributed and
should not require alteration if the physical data is centralized
or distributed.

12. Any row processing done in the system must obey the same
integrity rules and constraints that set-processing operations
do.
These principles continue to be the litmus test used to validate the
“relational” characteristics of a database platform; a database that
does not meet all of these rules is not fully relational. While these
rules do not apply to applications development, they do determine
whether the database engine itself can be considered truly
“relational.” Currently, most commercial RDBMS products pass Codd’s
test. All platforms discussed in the reference material of SQL in a
Nutshell , Fourth Edition satisfy these requirements, while the most
prominent NoSQL data platforms are discovered in Chapter 9.
Understanding Codd’s principles assists developers in the proper
development and design of relational databases (RDBs). The
following sections detail how some of these requirements are met
within SQL using RDBs.

Data structures (rules 1, 2, and 8)


Codd’s rules 1 and 2 state that “information is represented logically
in tables” and that “data must be logically accessible by table,
primary key, and column.” So, the process of defining a table for a
relational database does not require that programs instruct the
database how to interact with the underlying physical data
structures. Furthermore, SQL logically isolates the processes of
accessing data and physically maintaining that data, as required by
rule 8: “batch and end-user operations are logically separate from
physical storage and access methods.”
In the relational model, data is shown logically as a two-dimensional
table that describes a single entity (for example, business expenses).
Academics refer to tables as entities and to columns as attributes .
Tables are composed of rows , or records (academics call them
tuples ), and columns (called attributes , since each column of a
table describes a specific attribute of the entity). The intersection of
a record and a column provides a single value . However, it is quite
common to hear this referred to as a field , from spreadsheet
parlance. The column or columns whose values uniquely identify
each record can act as a primary key . These days this
representation seems elementary, but it was actually quite innovative
when it was first proposed.
The SQL standard defines a whole data structure hierarchy beyond
simple tables, though tables are the core data structure. Relational
design handles data on a table-by-table basis, not on a record-by-
record basis. This table-centric orientation is the heart of set
programming. Consequently, almost all SQL commands operate
much more efficiently against sets of data within or across tables
than against individual records. Said another way, effective SQL
programming requires that you think in terms of sets of data, rather
than of individual rows.
Figure 1-1 is a description of SQL’s terminology used to describe the
hierarchical data structures used by a relational database: clusters
contain sets of catalogs ; catalogs contain sets of s chemas ;
schemas contain sets of objects , such as tables and views ; and
tables are composed of sets of columns and records .
Figure 1-1. SQL3 dataset hierarchy

For example, in a Business_Expense table, a column called


Expense_Date might show when an expense was incurred. Each
record in the table describes a specific entity; in this case, everything
that makes up a business expense (when it happened, how much it
cost, who incurred the expense, what it was for, and so on).
Each attribute of an expense—in other words, each column—is
supposed to be atomic ; that is, each column is supposed to contain
one, and only one, value. If a table is constructed in which the
intersection of a row and column can contain more than one distinct
value, one of SQL’s primary design guidelines has been violated.
Some of the database platforms discussed in this book do allow you
to place more than one value into a column, via the VARRAY or
TABLE data types or, more common in the last several years, XML or
J SON data types.
Rules of behavior are specified for column values. Foremost is that
column values must share a common domain , better known as a
data type . For example, if the Expense_Date field is defined as
having a DATE data type, the value ELMER should not be placed into
that field because it is a string, not a date, and the Expense_Date
field can contain only dates. In addition, the SQL standard allows
further control of column values through the application of
constraints (discussed in detail in Chapter 2) and assertions . A SQL
constraint might, for instance, limit Expense_Date to expenses less
than a year old. Additionally, data access for all individuals and
computer processes is controlled at the schema level by an
AuthorizationID or user . Permissions to access or modify specific
sets of data may be granted or restricted on a per-user basis.
SQL databases also employ character sets and collations . Character
sets are the “symbols” or “alphabets” used by the “language” of the
data. For example, the American English character set does not
contain the special character for ñ in the Spanish character set.
Collations are sets of sorting rules that operate on a character set. A
collation defines how a given data manipulation operation sorts data.
For example, an American English character set might be sorted
either by character-order, case-insensitive , or by character-order,
case-sensitive .

NOTE
The ANSI/ISO standard does not say how data should be sorted, only
that platforms must provide common collations found in a given
language.

It is important to know what collation you are using when writing


SQL code against a database platform, as it can have a direct impact
on how queries behave, and particularly on the behavior of the
WHERE and ORDER BY clauses of SELECT statements. For example,
a query that sorts data using a binary collation will return data in a
very different order than one that sorts data using, say, an American
English collation. This is also very important when migrating SQL
code between database platforms since their default behavior may
vary widely. For example, Oracle is normally case-sensitive, while
Microsoft SQL Server is not case sensitive. So moving an unmodified
query from Oracle to SQL Server might produce a wildly different
result set because Oracle would evaluate “Halloween” and
“HALLOWEEN” as two unequal values, whereas SQL Server would
see them as equal, by default.

NULLs (rule 3)
Most databases allow any of their supported data types to store
NULL values. Inexperienced SQL developers tend to think of NULL as
zero or blank. In fact, NULL is neither of these. In SQL, NULL literally
means that the value is unknown or indeterminate. (This question
alone—whether NULL should be considered unknown or
indeterminate—is the subject of much academic debate.) This
differentiation enables a database designer to distinguish between
those entries that represent a deliberately placed zero, for example,
and those where either the data is not recorded in the system or a
NULL has been explicitly entered. As an illustration of this semantic
difference, consider a system that tracks payments. If a product has
a NULL price, that does not mean the product is free; instead, a
NULL price indicates that the amount is not known or perhaps has
not yet been determined.

NOTE
There is a good deal of differentiation between the database platforms
in terms of how they handle NULL values. This leads to some major
porting issues between those platforms relating to NULLs. For example,
an empty string (i.e., a NULL string) is inserted as a NULL value on
Oracle. All the other databases covered in this book permit the insertion
of an empty string into VARCHAR and CHAR columns.

One side effect of the indeterminate nature of a NULL value is that it


cannot be used in a calculation or a comparison. Here are a few brief
but very important rules, from the ANSI/ISO standard, to remember
about the behavior of NULL values when dealing with NULLs in SQL
statements:
A NULL value cannot be inserted into a column defined with NOT
NULL constraint.

NULL values are not equal to each other. It is a frequent mistake


to compare two columns that contain NULL and expect the NULL
values to match. (The proper way to identify a NULL value in a
WHERE clause or in a Boolean expression is to use phrases such
as “value IS NULL” and “value IS NOT NULL”.)
A column containing a NULL value is ignored in the calculation of
aggregate values such as AVG , SUM , or MAX COUNT .

When columns that contain NULL values are listed in the GROUP
BY clause of a query, the query output contains a single row for
NULL values. In essence, the ANSI/ISO standard considers all
NULLs found to be in a single group.

DISTINCT and ORDER BY clauses, like GROUP BY , also see NULL


values as indistinguishable from each other. With the ORDER BY
clause, the vendor is free to choose whether NULL values sort
high (first in the result set) or sort low (last in the result set) by
default.

Metadata (rules 4 and 10)


Codd’s fourth rule for relational databases states that data about the
database must be stored in standard tables, just as all other data is.
Data that describes the database itself is called metadata . For
example, every time you create a new table or view in a database,
records are created and stored that describe the new table.
Additional records are needed to store any columns, keys, or
constraints on the table. This technique is implemented in most
commercial and open source SQL database products. For example,
SQL Server uses what it calls “system tables” to track all the
information about the databases, tables, and database objects in
any given database. It also has “system databases” that keep track
of information about the server on which the database is installed
and configured. In addition to system tables, the SQL standard
defines a set of basic metadata available through a widely adopted
set of views referenced in the schema called Information _Schema .
Notably, Oracle (since 2015) and IBM DB2 do not support the SQL
standard information schema.
The language (rules 5 and 11)
Codd’s rules do not require SQL to be used with a relational
database. His rules, particularly rules 5 and 11, only specify how the
language should behave when coupled with a relational database. At
one time SQL competed with other languages (such as Digital’s RDO
and Fox/PRO) that might have fit the relational bill, but SQL won
out, for three reasons. First, SQL is a relatively simple, intuitive,
English-like language that handles most aspects of data
manipulation. If you can read and speak English, SQL simply makes
sense. Second, SQL is satisfyingly high-level. A developer or
database administrator (DBA) does not have to spend time ensuring
that data is stored in the proper memory registers or that data is
cached from disk to memory; the database management system
(DBMS) handles that task automatically. Finally, because no single
vendor owns SQL, it was adopted across a number of platforms
ensuring broad support and wide popularity.

Views (rule 6)
A view is a virtual table that does not exist as a physical repository
of data, but is instead constructed on the fly from a SELECT
statement whenever that view is queried. Views enable you to
construct different representations of the same source data for a
variety of audiences without having to alter the way in which the
data is stored.

NOTE
Some vendors support database objects called materialized views .
Don’t let the similarity of terms confuse you; materialized views are not
governed by the same rules as ANSI/ISO standard views.
Set operations (rules 7 and 12)
Other database manipulation languages, such as the venerable
Xbase, perform their data operations quite differently from SQL.
These languages require you to tell the program exactly how to treat
the data, one record at a time. Since the program iterates down
through a list of records, performing its logic on one record after
another, this style of programming is frequently called r ow,
processing or procedural programming .
In contrast, SQL programs operate on logical sets of data. Set theory
is applied in almost all SQL statements, including SELECT , INSERT ,
UPDATE , and DELETE statements. In effect, data is selected from a
set called a “table.” Unlike the row-processing style, set processing
allows a programmer to tell the database simply what is required,
not how each individual piece of data should be handled. Sometimes
set processing is referred to as declarative processing , since a
developer declares only what data is wanted (as in declaration,
“Return all employees in the southern region who earn more than
$70,000 per year”) rather than describing the exact steps used to
retrieve or manipulate the data.

NOTE
Set theory was the brainchild of mathematician Georg Cantor, who
developed it at the end of the nineteenth century. At the time, set
theory (and Cantor’s theory of the infinite) was quite controversial.
Today, set theory is such a common part of life that it is learned in
elementary school. Things like card catalogs, the Dewey Decimal
System, and alphabetized phone books are all simple and common
examples of applied set theory.
Relational databases use relational algebra and tuple relational calculus
to mathematically model the data in a given database and queries
acting upon that data. These theories were also introduced by E. F.
Codd along with his twelve rules for relational databases.
Examples of set theory in conjunction with relational databases are
detailed in the following section.
Codd’s Rules in Action: Simple SELECT
Examples
Up to this point, this chapter has focused on the individual aspects
of a relational database platform as defined by Codd and
implemented under ANSI/ISO SQL. This following section presents a
high-level overview of the most important SQL statement, SELECT ,
and some of its most salient points—namely, the relational
operations known as projections , selections , and joins :
Projection
Retrieves specific columns of data

Selection
Retrieves specific rows of data

Join
Returns columns and rows from two or more tables in a single
result set

Although at first glance it might appear as though the SELECT


statement deals only with the relational selection operation, in
actuality, SELECT deals with all three operations.
The following statement embodies the projection operation by
selecting the first and last names of an author, plus their home state,
from the authors table:

SELECT au_fname, au_lname, state


FROM authors;

The results from any such SELECT statement are presented as


another table of data:
au_fname au_lname state
---------------- -------------------- ---------
-------
Johnson White CA
Marjorie Green CA
Cheryl Carson CA
Michael O'Leary CA
Meander Smith KS
Morningstar Greene TN
Reginald Blotchet-Halls OR
Innes del Castillo MI

The resulting data is sometimes called a result set , work table , or


derived table , differentiating it from the base table in the database
that is the target of the SELECT statement.
It is important to note that the relational operation of projection, not
selection, is specified using the SELECT clause (that is, the keyword
SELECT followed by a list of expressions to be retrieved) of a
SELECT statement. Selection—the operation of retrieving specific
rows of data—is specified using the WHERE clause in a SELECT
statement. WHERE filters out unwanted rows of data and retrieves
only the requested rows. Continuing with the previous example, the
following statement selects authors from states other than
California:

SELECT au_fname, au_lname, state


FROM authors
WHERE state <> 'CA';

Whereas the first query retrieved all authors, the result of this
second query is a much smaller set of records:

au_fname au_lname state


---------------- ------------------------- --------
----
Meander Smith KS
Morningstar Greene TN
Reginald Blotchet-Halls OR
Innes del Castillo MI

By combining the capabilities of projection and selection in a single


query, you can use SQL to retrieve only the columns and records
that you need at any given time.
Joins are the next, and last, relational operation covered in this
section. A join relates one table to another in order to return a result
set consisting of related data from both tables.

NOTE
Different vendors allow you to join varying numbers of tables in a single
join operation. For example, older database platforms topped out at 256
tables join operations in a given query. Today, most database platforms
are limited only by available system resources.
However, keep in mind that your database engine will consume more
system resources and incur more latency the more tables you join in a
single query. For example, a single SELECT statement joining 12 tables
will have to consider up to 28,158,588,057,600 possible join orders.
Consequently, many experienced SQL developers try to limit their
SELECT statements to no more than 6 joins. When a SELECT statement
exceeds 6 joins, they usually break the query into multiple distinct
queries for faster processing.

The ANSI/ISO standard method of performing joins is to use the


JOIN clause in a SELECT statement. An older method, sometimes
called a theta join , analyzes the join search argument in the WHERE
clause. The following example shows both approaches. Each
statement retrieves employee information from the employee base
table as well as job descriptions from the jobs base table. The first
SEL ECT uses the newer, ANSI/ISO JOIN clause, while the second
SELECT uses a theta join:

-- ANSI style
SELECT a.au_fname, a.au_lname, t.title_id
FROM authors AS a
JOIN titleauthor AS t ON a.au_id = t.au_id
WHERE a.state <> 'CA';
-- Theta style
SELECT a.au_fname, a.au_lname, t.title_id
FROM authors AS a,
titleauthor AS t
WHERE a.au_id = t.au_id
AND a.state <> 'CA';

Although theta joins are universally supported across the various


platforms and incur no performance penalty, it is considered an
inferior coding pattern because anyone reading or maintaining the
query cannot immediately discern the arguments used to define the
join condition from those used as filtering conditions.
For more information about joins, see the “JOIN Subclause” section
in Chapter 4.
History of the SQL Standard
In response to the proliferation of SQL dialects, ANSI published its
first SQL standard in 1986 to bring about greater conformity among
vendors. This was followed by a second, widely adopted standard in
1989. The International Standards Organization (ISO) also later
approved the SQL standard in 1987. ANSI/ISO released their first
joint update in 1992, also known as SQL:1992, SQL92, or SQL2.
Another release came in 1999, termed SQL:1999, SQL99, or SQL3.
The next update, made in 2003, is referred to as SQL:2003, and so
on.
Each time it revises the SQL standard, ANSI/ISO adds new features
and incorporates new commands and capabilities into the language.
For example, the SQL:99 standard added a group of capabilities that
handled object-oriented data type extensions. Interestingly, though
the ANSI/ISO standards body often defines new parts to the SQL
standard, not every part is released nor, once released, does every
part see widespread adoption.
What’s New in SQL:2016
The ANSI/ISO standards body that regulates SQL issued a new
standard in 2016, which described an entirely new functional area of
behavior for the SQL standard, namely, how SQL interacts with JSON
(JavaScript Object Notation). Of the 44 new features in this release,
half detail JSON functionality. The SQL:2016 standard defines
storage data types, functions and syntax for ingesting and querying
JSON in a SQL database. In the same way that the SQL:2006
standard defined the details for database behavior using XML, so
SQL:2016 does for JSON.
The next largest set of features released in SQL:2016 support
Polymorphic table functions , which are table functions that enable
you to return a result set without a predefined return data type.
Other highlights include the new data type, DECFLOAT , the function
LISTAGG, allowing you to return a group of rows as a delimited
string, and improvements to regular expressions, along with date
and time handling features. Introductory level coverage is provided
for JSON functionality in Chapter 8.
What’s New in SQL:2011
SQL:2011 introduced new features for managing temporal data.
These include a number of new predicates OVERLAPS, EQUALS,
PRECEDES, AS OF SYSTEM_TIME, and several others. Along with
these new constructs, syntax was added for application time periods,
bitemporal tables, and system versioned temporal tables. These
features together provided the capability to do point-in-time
reporting and data management. Under this method of data
processing, for example, you could write a query “as-of” 5 months.
The query would then return a result set as if you were executing
the SELECT at precisely that point in time, excluding data newer
than 5-months ago that exists in the table which otherwise satisfy
the filter arguments of the query.
What’s New in SQL:2008
Released in the summer of 2008, SQL:2008 solidified improvements
and enhancements that were already well in place across several of
the most prominent relational database platforms. These
enhancements added, among other things, a handful of important
statements and improvements to the Foundation, such as
TRUNCATE TABLE , INSTEAD OF triggers, partitioned JOIN tables,
and improvements to CASE , MERGE , and DIAGNOSTIC statements.
What’s New in SQL:2006
The ANSI/ISO SQL:2006 release was evolutionary over the
SQL:2003 release, but it did not include any significant changes to
the SQL:2003 commands and functions that were described in the
second edition of this book. Instead, SQL:2006 described an entirely
new functional area of behavior for the SQL standard delineated in
Part 14 of the standard.
Briefly, SQL:2006 describes how SQL and XML (the eXtensible
Markup Language) interact. For example, the SQL:2006 standard
describes how to import and store XML data in a SQL database,
manipulate that data, and then publish the data both in native XML
form and as conventional SQL data wrapped in XML form. The
SQL:2006 standard provides a means of integrating SQL application
code using XQuery, the XML Query Language standardized by the
World Wide Web Consortium (W3C). Because XML and XQuery are
disciplines in their own right, they are considered beyond the scope
of this book and are not covered here. Introductory level coverage is
provided for this functionality in Chapter 8.
What’s New in SQL:2003 (aka SQL3)
SQL:1999 had two main parts, Foundation:1999 and Bindings:1999 .
The SQL3 Foundation section includes all of the Foundation and
Bindings standards from SQL:1999, as well as a new section called
Schemata .
The Core requirements of SQL3 did not change from Core SQL:1999,
so the database platforms that conformed to Core SQL:1999
automatically conform to SQL3. Although the Core of SQL3 had no
additions (except for a few new reserved words), a number of
individual statements and behaviors were updated or modified.
Because these updates are reflected in the individual syntax
descriptions of each statement in Chapter 3, we won’t spend time on
them here.
The ANSI/ISO standards body not only adds new elements to the
standards, it may also take elements away. For example, few
elements of the Core in SQL99 were deleted in SQL3, including:
The BIT and BIT VARYING data types

The UNION JOIN clause

The UPDATE . . . SET ROW statement

A number of other features, most of which were or are rather


obscure, have also been added, deleted, or renamed. Many of the
new features of the SQL3 standard are currently interesting mostly
from an academic standpoint, because none of the database
platforms support them yet. However, a few new features hold more
than passing interest:
Elementary OLAP functions
SQL3 adds an Online Analytical Processing (OLAP) amendment,
including a number of windowing functions to support widely
used calculations such as moving averages and cumulative sums.
Windowing functions are aggregates computed over a window of
data: ROW_NUMBER , RANK , DENSE_RANK , PERCENT_RANK ,
and CUME_DIST . OLAP functions are fully described in T611 of
the standard. Some database platforms are starting to support
the OLAP functions. Refer to Chapter 7 for details.

Sampling
SQL3 adds the TABLESAMPLE clause to the FROM clause. This is
useful for statistical queries on large databases, such as a data
warehouse.

Enhanced numeric functions


SQL3 adds a large number of numeric functions. In this case, the
standard was mostly catching up with the trend in the industry,
since one or more database platforms already supported the new
functions. Refer to Chapter 7 for details.
Levels of Conformance
SQL:1999 is built upon SQL:1992’s levels of conformance . SQL92
first introduced levels of conformance by defining three categories:
Entry , Intermediate , and Full . Vendors had to achieve at least
Entry-level conformance to claim ANSI/ISO SQL compliance. The
U.S. National Institute of Standards and Technology (NIST) later
added the Transitional level between the Entry and Intermediate
levels, so NIST’s levels of conformance were Entry, Transitional,
Intermediate, and Full, while ANSI/ISO’s were only Entry,
Intermediate, and Full. Each higher level of the standard was a
superset of the subordinate level, meaning that each higher level
included all the features of the lower levels of conformance.
Later, SQL99 altered the base levels of conformance, doing away
with the Entry, Intermediate, and Full levels. With SQL99, vendors
must implement all the features of the lowest level of conformance,
Core SQL99 (now commonly called simply ‘Core SQL’), in order to
claim (and advertise) that they are SQL99 compliant. Core SQL99
includes the old Entry SQL92 feature set, features from other SQL92
levels, and some brand new features. A vendor may also choose to
implement additional feature packages described in the SQL99
standard.
Supplemental Features Packages in the SQL3
Standard
The SQL3 standard represents the ideal, but very few vendors
currently meet or exceed the Core SQL3 requirements. The Core
standard is like the interstate speed limit: some drivers go above it
and others go below it, but few go exactly at the speed limit.
Similarly, vendor implementations can vary greatly.
Two committees—one within ANSI, the other within ISO, and both
composed of representatives from virtually every RDBMS vendor—
drafted the supplemental feature definitions described in this
section. In this collaborative and somewhat political environment,
vendors compromised on exactly which proposed features and
implementations would be incorporated into the new standard.
New features in the ANSI/ISO standard often are derived from an
existing product or are the outgrowth of new research and
development in the academic community. Consequently, vendor
adoption of specific ANSI/ISO standards can be spotty. A relatively
new addition to the SQL3 standard is SQL/XML (greatly expanded in
SQL:2006.) The other parts of the SQL99 standard remain in SQL3,
though their names may have changed and they may have been
slightly rearranged.
The nine supplemental features packages, representing different
subsets of commands, are platform-optional. Note that a handful of
these parts were never released and, thus, do not show up in the list
below. Also, some features might show up in multiple packages,
while others do not appear in any of the packages. These packages
and their features are described in the following list:
Part 1, SQL/Framework
Includes common definitions and concepts used throughout the
standard. Defines the way the standard is structured and how
the various parts relate to one another, and describes the
conformance requirements set out by the standards committee.

Part 2, SQL/Foundation
Includes the Core, an augmentation of the SQL99 Core. This is
the largest and most important part of the standard.

Part 3, SQL/CLI (Call-Level Interface)


Defines the call-level interface for dynamically invoking SQL
statements from external application programs. Also includes
over 60 routine specifications to facilitate the development of
truly portable shrink-wrapped software.

Part 4, SQL/PSM (Persistent Stored Modules)


Standardizes procedural language constructs similar to those
found in database platform-specific SQL dialects such as PL/SQL
and Transact-SQL.

Part 9, SQL/MED (Management of External Data)


Defines the management of data located outside of the database
platform using datalinks and a wrapper interface.

Part 10, SQL/OBJ (Object Language Binding)


Describes how to embed SQL statements in Java programs. It is
closely related to JDBC, but offers a few advantages. It is also
very different from the traditional host language binding possible
in early versions of the standard.

Part 11, SQL/Schemata


Defines over 85 views (three more than in SQL99) used to
describe the metadata of each database and stored in a special
schema called INFORMATION_SCHEMA . Updates a number of
views that existed in SQL99.
Part 12, SQL/JRT (Java Routines and Types)
Defines a number of SQL routines and types using the Java
programming language. Several features of Java, such as Java
static methods and classes, are now supported.

Part 14, SQL/XML


Adds a new type called XML , four new operators (XMLPARSE ,
XMLSERIALIZE , XMLROOT , and XMLCONCAT ), several new
functions (described in Chapter 4), and the new IS DOCUMENT
predicate. Also includes rules for mapping SQL-related elements
(like identifiers , schemas , and objects ) to XML-related
elements.
Note that parts 5 through 8, and part 12, are not released to the
public by design.
Be aware that an RDBMS platform may claim SQL3 compliance by
meeting Core SQL99 standards, so read the vendor’s fine print for a
full description of its ANSI/ISO conformity features. By
understanding what features comprise the nine packages, users can
gain a clear idea both of the capabilities of a particular RDBMS and
of how the various features behave when SQL code is transported to
other database products.
The ANSI/ISO standards—which cover retrieval, manipulation, and
management of data in commands such as SELECT , JOIN , ALTER
TABLE , and DROP —formalize many SQL behaviors and syntax
structures across a variety of platforms. These standards have
become even more important as open source database products,
such as MySQL and PostgreSQL, have grown in popularity and begun
being developed by virtual teams rather than large corporations.
SQL in a Nutshell , Fourth Edition explains the SQL implementation
of four popular RDBMSs. These vendors do not meet all the SQL3
standards; in fact, all RDBMS platforms play a constant game of tag
with the standards bodies. Often, as soon as vendors close in on the
standard, the standards bodies update, refine, or otherwise change
the benchmark. Conversely, the vendors often implement new
features that are not yet a part of the standard but that boost the
effectiveness of their users.
SQL3 Statement Classes
Comparing statement classes further delineates SQL3 from SQL92.
However, the older terms are still used frequently, so readers need
to know them. SQL92 grouped statements into three broad
categories:
Data Manipulation Language (DML)
Provides specific data-manipulation commands such as SELECT ,
INSERT , UPDATE , and DELETE

Data Definition Language (DDL)


Contains commands that handle the accessibility and
manipulation of database objects, including CREATE and DROP

Data Control Language (DCL)


Contains the permission-related commands GRANT and REVOKE

In contrast, SQL3 supplies seven core categories, now called classes


, that provide a general framework for the types of commands
available in SQL. These statement “classes” are slightly different
from the SQL92 statement categories, because they attempt to
identify the statements within each class more accurately and
logically and they provide for the development of new features and
statement classes. Additionally, the new statement classes now allow
some “orphaned” statements that did not fit well into any of the old
categories to be properly classified.
Table 1-1 identifies the SQL3 statement classes and lists some of the
commands in each class, each of which is fully discussed later. At
this point, the key is to remember the statement class titles.

Table 1-1.
SQL3 statement classes

Class Description Example


commands
SQL Start and end a client connection
connection CONNECT,
statements DISCONNECT
SQL control Control the execution of a set of SQL
statements statements CALL, RETURN
SQL data May have a persistent and enduring effect
statements upon data SELECT, INSERT,
UPDATE,
DELETE
SQL Provide diagnostic information and raise
diagnostic exceptions and errors GET
statements DIAGNOSTICS
SQL schema May have a persistent and enduring effect
statements on a database schema and objects within ALTER, CREATE,
that schema DROP
SQL session Control default behavior and other
statements parameters for a session SET
statements like
SET
CONSTRAINT
SQL Set the starting and ending point of a
transaction transaction COMMIT,
statements ROLLBACK

Those who work with SQL regularly should become familiar with
both the old (SQL92) and the new (SQL3 and later) statement
classes, since both nomenclatures are still used to refer to SQL
features and statements.
SQL Dialects
The constantly evolving nature of the SQL standard has given rise to
a number of SQL dialects among the various vendors and platforms.
These dialects commonly evolve because a given database vendor’s
user community requires capabilities in the database before the
ANSI/ISO committee creates an applicable standard. Occasionally,
though, the academic or research communities introduce a new
feature in response to pressures from competing technologies. For
example, many database vendors are augmenting their current
programmatic offerings with either JSON or . In the future,
developers will use these programming languages in concert with
SQL to build SQL programs.
Many of these dialects include conditional processing capabilities
(such as those that control processing through IF . . . THEN
statements), control-of-flow functions (such as WHILE loops),
variables, and error-handling capabilities. Because ANSI/ISO had not
yet developed a standard for these important features at the time
users began to demand them, RDBMS developers and vendors
created their own commands and syntax. In fact, some of the
earliest vendors from the 1980s have variances in the most
elementary commands, such as SELECT , because their
implementations predate the standards. When attempting to create
SQL code that is interoperable across database platforms, keep in
mind that your mileage may vary.
Some of these dialects introduced procedural commands to support
the functionality of a more complete programming language. For
example, these procedural implementations contain error-handling
commands, control-of-flow language, conditional commands,
variable-handling commands, support for arrays, and many other
extensions. Although these are technically divergent procedural
implementations, they are called dialects here. The SQL/PSM
(Persistent Stored Module) package provides many features
associated with programming stored procedures and incorporates
many of the extensions offered by these dialects.
Some popular dialects of SQL include:
PL/pgSQL
SQL dialect and extensions implemented in PostgreSQL. The
acronym stands for Procedural Language/PostgreSQL.

PL/SQL
Found in Oracle. PL/SQL stands for Procedural Language/SQL
and contains many similarities to the language Ada.

SQL/PSM
MySQL and MariaDB implement the SQL/Persistent Stored
Module of the Core SQL standard. MariaDB also supports PL/SQL.

Transact-SQL
Used by both Microsoft SQL Server and Sybase Adaptive Server,
now owned by SAP. As Microsoft and SAP/Sybase have moved
away from the common platform they shared early in the 1990s,
their implementations of Transact-SQL have also diverged widely.
But the most basic commands are still very similar.

Users who plan to work extensively with a single database system


should learn the intricacies of their preferred SQL dialect or platform.
Chapter 2. Foundational
Concepts

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 2nd chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at [email protected].

SQL provides an easy, intuitive way to interact with a database.


While the SQL standard does not define the concept of a “database,”
it does define all the functions and concepts needed for a user to
create, retrieve, update, and delete data. It is important to know the
types of syntax in the ANSI/ISO SQL standard and the particular
platform-specific syntax guidelines. This chapter will provide you
with a grounding in those areas. For brevity, we will refer to the
ANSI/ISO standard as, simply, SQL or “the SQL standard” in the
remainder of this chapter.
Database Platforms Described in This Book
SQL in a Nutshell , Fourth Edition describes the SQL standard and
the platform-specific implementations of several leading RDBMSs:
MySQL / MariaDB
MySQL is a popular open source DBMS that is known for its ease
of use and good performance. It runs on numerous operating
systems, including most Linux variants. To improve performance,
it has a slimmer feature set than many other DBMSs. Since the
purchase of Sun Microsystems by Oracle, the MySQL user-base
has been split into 2-factions - MySQL (maintained by Oracle)
and MariaDb (by MariaDB Foundation whose head, Monty
Widenius, was the original creator of MySQL). This book covers
MySQL 8, now owned by Oracle, and the most popular MySQL
fork MariaDB 10.5. Both have more or less equivalent and
compatible offering of functionality and MariaDb does pull in
changes from MySQL core. Where they deviate most is in the
storage engines they offer and their release cycle. At some point
in the near future, MySQL and MariaDB will be divergent enough
to warrant distinct entries throughout this book. For now, they
are maintained as one.

Oracle
Oracle is a leading RDBMS in the commercial sector. Oracle was
the first commercially available SQL database platform, released
in the summer of 1979, running on Vax computers as Oracle v2.
Since that time, Oracle has grown to run on a multitude of
operating systems and hardware platforms. Its scalable, reliable
architecture has made it the platform of choice for many users.
In this edition, we cover Oracle Database 19c .

PostgreSQL
PostgreSQL is the most feature-rich open source database
platform available. For the last several years, PostgreSQL has
seen a steep rise in popularity with a strongly upward trend.
PostgreSQL is best known for its excellent support for ANSI/ISO
standards and robust transaction processing capabilities, as well
as its rich data type and database object support. In addition to
its full set of features, PostgreSQL runs on a wide variety of
operating systems and hardware platforms. This book covers
PostgreSQL 13.

SQL Server
Microsoft SQL Server is a popular RDBMS that runs on the
Windows and Linux operating systems. Its features include ease
of use, an all-inclusive feature set covering OLTP and analytic
workloads, low cost, and high performance. This book covers
Microsoft SQL Server 2019.
Categories of Syntax
To begin to use SQL, readers should understand how statements are
written. SQL syntax falls into four main categories. Each category is
introduced in the following list and then explained in further detail in
the sections that follow:
Identifiers
Describe a user- or system-supplied name for a database object,
such as a database, a table, a constraint on a table, a column in
a table, a view, etc.

Literals
Describe a user- or system-supplied string or value that is not
otherwise an identifier or a keyword. Literals may be strings like
“hello” , numbers like 1234 , dates like “Jan 01, 2002”, or
Boolean values like TRUE .

Operators
Are symbols specifying an action to be performed on one or more
expressions, most often in DELETE , INSERT , SELECT , or
UPDATE statements. Operators are also used frequently in the
creation of database objects.

Reserved words and keywords


Have special meaning to the database SQL parser. Keywords such
as SELECT , GRANT , DELETE , or CREATE are words that cannot
be used as identifiers within the database platform. These are
usually commands or SQL statements. Reserved words are words
that may become reserved some time in the future. Elsewhere in
the book, we use the term keyword to describe both concepts.
You can circumvent the restriction on using reserved words and
keywords as identifiers by using quoted identifiers , which will be
described in a moment. However, this is not recommended since
a single typo could play havok with your code.
Random documents with unrelated
content Scribd suggests to you:
gaps. Sometimes the frame of a shōji gets sprung or thrown out of its
true rectangular shape; this is remedied by inserting at intervals in
the meshes of the frame-work elastic strips of bamboo, and the
constant pressure of these strips in one direction tends to bring the
[pg 132] frame straight again. Fig. 111 illustrates the appearance of
this; the curved lines representing the elastic strips.

Fig. 111.—Straightening shōji frame.

There are innumerable designs employed in the shōji; and in this, as


in many other parts of the interior, the Japanese show an infinite
amount of taste and ingenuity. Fig. 112 illustrates one of these
ornamental forms. At present in the cities it is common to see a
narrow strip of window glass inserted across the shōji about two feet
from the floor. It seems odd at first sight to see it placed so low, until
one recalls the fact that the inmates sit on the mats, and the glass in
this position is on a level with their line of vision. As a general rule
the designs for the shōji are more simple than those employed for
certain exterior openings which may be regarded as windows, while
those which cover the openings between the rooms are most
complex and elaborate. Further reference, however, will be made to
these in the proper place.
Fig. 112.—Shōji with ornamental frame.

It has been necessary to anticipate the special description of the


details of a room in so far as a description of the mats and screens
were concerned, since a general idea of the interior [pg 133] could
not be well understood without clearly understanding the nature of
those objects which form inseparable elements of every Japanese
room, and which are so unlike anything to which we are accustomed.
Having given these features, it may be well to glance at a general
view of the few typical rooms before examining farther into the
details of their finish.

The room shown in fig. 96 gives a fair idea of the appearance of the
guest-room with its two bays or recesses, the tokonoma and chigai-
dana,—one of which, the tokonoma, is a clear recess, in which
usually hangs a picture; and in the other is a small closet and shelf,
and an additional shelf above, closed by sliding doors. The sketch
was taken from the adjoining room, the fusuma between the two
having been removed. The grooves for the fusuma may be seen in
the floor and in the kamoi overhead. The farther recess is called the
tokonoma, which means literally, “bed-space.” This recess, or at least
its raised platform, is supposed to have been anciently used for the
bed-place.15

Let us pause for a moment to consider the peculiar features of this


room. The partition separating the two recesses has for its post a
stick of timber, from which the bark only has been removed; and this
post, or toko-bashira as it is called, is almost invariably a stick of
wood in its natural state, or with the bark only removed; and if it is
gnarled, or tortuous in grain, or if it presents knots or burls, it is all
the more desirable. Sometimes the post may be hewn in such a way
that in section it has an octagonal form,—the cutting being done in
broad scarfs, giving it a peculiar appearance as shown in fig. 113.
Sometimes the post may have one or two branches above, which are
worked into the structure as an ornamental feature. The ceiling of
the tokonoma is usually, if not always, [pg 134] flush, with the ceiling
of the room, while that of the chigai-dana is much lower. The floor of
the tokonoma is higher than that of the chigai-dana, and its sill may
be rough or finished; and even when finished squarely, some natural
surface may be left through the curvature of the stick from which it
has been hewn, and which had been selected for this very peculiarity,
—a feature, by the way, that our carpenters would regard as a
blemish. The floor of the tokonoma is in nearly every case a polished
plank; the floor of the chigai-dana is also of polished wood. A large
and deep tokonoma may have a mat, or tatami, fitted into the floor;
and this is generally bordered with a white strip, and not with black
as in the floor tatami. The tatami in this place is found in the houses
of the Daimios.
Fig. 113.—Portion of Toko-Bashira.

Figs. 114, 115, 116, and 117. Ornamental-headed nails.

Spanning the tokonoma above is a finished beam a foot or more


below the ceiling, the interspace above being plastered, as are the
walls of both recesses. A similar beam spans the chigai-dana at a
somewhat lower level. When the cross-beam of the chigai-dana
connects with the toko-bashira, as well as in the joining of other
horizontal beams with the uprights, ornamental-headed nails are
used. These are often of elaborately-wrought metal, representing a
variety of natural or [pg 135] conventional forms. Figs. 114, 115,
116, and 117 present a few of the cheaper forms used; these being
of cast metal, the finer lines only having been cut by hand. These
nails, or kazari-kugi, are strictly ornamental, having only a spur
behind to hold them into the wood.

The partition dividing these two recesses often has an ornamental


opening, either in the form of a small window barred with bamboo, or
left open; or this opening may be near the floor, with its border made
of a curved stick of wood, as in the figure we are now describing.

In the chigai-dana there are always one or more shelves ranged in an


alternating manner, with usually a continuous shelf above closed by
sliding doors. A little closet on the floor in the corner of the recess is
also closed by screens, as shown in the figure. The wood-work of this
may be quaintly-shaped sticks or highly-polished wood.

This room illustrates very clearly a peculiar feature in Japanese


decoration,—that of avoiding, as far as possible, bi-lateral symmetry.
Here are two rooms of the same size and shape, the only difference
consisting in the farther room having two recesses, while the room
nearer has a large closet closed by sliding screens. It will be
observed, however, that in the farther room the narrow strips of
wood, upon which the boards of the ceiling rest, run parallel to the
tokonoma, while in the nearer room the strips run at right angles.
The mats in the two rooms, while arranged in the usual manner for
an eight-mat room, are placed in opposite ways; that is to say, as the
mats in front of the tokonoma and chigai-dana are always parallel to
these recesses, the other mats are arranged in accordance with
these. In the room coming next, the arrangement of mats, while
being the same, have the two mats running parallel to the line
dividing the rooms, and of course the other mats in accordance with
these. This asymmetry is carried out, of course, in the two [pg 136]
recesses, which are unlike in every detail,—their floors as well as the
lower borders of their hanging partitions being at different levels. And
in the details of the chigai-dana symmetrical arrangement is almost
invariably avoided, the little closet on the floor being at one side,
while a shelf supported on a single prop runs from the corner of this
closet to the other side of the recess; and if another shelf is added,
this is arranged in an equally unsymmetrical manner. In fact
everywhere, in mats, ceiling, and other details, a two-sided symmetry
is carefully avoided.

How different has been the treatment of similar features in the finish
of American rooms! Everywhere in our apartments, halls, school-
houses, inside and out, a monotonous bi-lateral symmetry is
elaborated to the minutest particular, even to bracket and notch in
pairs. The fireplace is in the middle of the room, the mantel, and all
the work about this opening, duplicated with painful accuracy on
each side of a median line; every ornament on the mantel-shelf is in
pairs, and these are arranged in the same way; a single object, like a
French clock, is adjusted in the dead centre of this shelf, so that each
half of the mantel shall get its half of a clock; a pair of andirons
below, and portraits of ancestral progenitors on each side above keep
up this intolerable monotony; and opposite, two windows with draped
curtains parted right and left, and a symmetrical table or cabinet
between the two, are in rigid adherence to this senseless scheme.
And outside the monotony is still more dreadful, even to the fences,
carriage-way and flower-beds; indeed, false windows are introduced
in adherence to this inane persistency in traditional methods. Within
ten years some progress has been made among the better class of
American houses in breaking away from this false and tiresome idea,
and our houses look all the prettier for these changes. In decoration,
as well, we have made great strides in the same direction, thanks to
the influence of Japanese methods.

[pg 137]
While the general description just given of the tokonoma and chigai-
dana may be regarded as typical of the prevailing features of these
recesses, nevertheless their forms and peculiarities are infinitely
varied. It is indeed rare to find the arrangement of the shelves and
cupboards in the chigai-dana alike in any two houses, as will be seen
by a study of the figures which are to follow. Usually these two
recesses are side by side, and run at right angles with the verandah,
the tokonoma almost invariably coming next to the verandah.
Sometimes, however, these two recesses may stand at right angles to
one another, coming in a corner of the room away from the
verandah. The tokonoma may be seen also without its companion
recess, and sometimes it may occupy an entire side of the room, in
which case it not infrequently accommodates a set of two or three
pictures. When these recesses come side by side, it is usual to have
an entire mat in front of each recess. The guest of honor is seated on
the mat in front of the tokonoma, while the guest next in honor
occupies a mat in front of the chigai-dana.

Fig. 118.—Shelves contrasted with conventional drawing of mist, or


clouds.

This recess has a variety of names, according to the form and


arrangement of the shelves. It is usually called chigai-dana,— the
word chigai meaning “different,” and dana, “shelf,” as the shelves are
arranged alternately. It is also called usukasumi-dana, which means
“thin mist-shelf,”—the shelves in this case being arranged in a way in
which they often conventionally represent mist or clouds, as shown in
their formal designs of these objects (fig. 118), in which the upper
outline shows the form of shelf, and the lower outline the
conventional drawing of cloud. When only one shelf is seen it may be
called ichi-yo-dana; the form of the shelf [pg 138] suggests such
names as willow-leaf shelf, fish-shelf, etc. In this recess, as we have
seen, are usually shelves and a cupboard; and the arrangements of
these are almost as numberless as the houses containing them,—at
least it is rare to see two alike. A shelf in the chigai-dana, having a rib
or raised portion on its free end, is called a maki-mono-dana. On this
shelf the long picture-scrolls called maki-mono are placed; the
ceremonial hat was also placed on one of the shelves. It was
customary to place on top of the cupboard a lacquer-box, in which
was contained an ink-stone, brushes, and paper. This box was usually
very rich in its gold lacquer and design. In the houses of the nobles
the top of the cupboard was also used to hold a wooden tablet called
a shaku,—an object carried by the nobles in former times, when in
the presence of the Emperor. It was anciently used to make
memoranda upon, but in later days is carried only as a form of court
etiquette. The sword-rack might also be placed on the cupboard. In
honor of distinguished guests the sword-rack was placed in the [pg
139] tokonoma in the place of honor; that is, in the middle of its
floor, or toko, in front of the hanging picture,—though if an incense-
burner occupied this position, then the sword-rack was placed at one
side. While these recesses were usually finished with wood in its
natural state or simply planed, in the houses of the nobles this finish
was often richly lacquered.
Fig. 119.—Guest-room.

Resuming our description of interiors, a peculiar form of room is


shown in the house of a gentleman of high rank (fig. 119). Here the
tokonoma was much larger than its companion recess, which in this
case was next to the verandah. The chigai-dana was small and low,
and the spaces beneath the shelves were enclosed by sliding screens
forming cupboards. The tokonoma was large and deep, and its floor
was covered by a mat or tatami; the flower-vase was at one side.
Fig. 120.—Guest-room, with recesses in corners.

The depth of the tokonoma is generally governed by the size of the


room. The appointments of this recess are also always in [pg 140]
proportion,—the pictures and flower-vase being of large size in the
one just described.
Fig. 121.—Guest-room showing circular window.

In a spacious hall in Tokio is a tokonoma six feet in depth, and very


wide. The flower-vases and pictures in this recess were colossal. In
an adjoining room to the one last figured the tokonoma came in one
corner of the room, and the chigai-dana was at right angles with it.
To the right of the tokonoma was a permanent partition, in the centre
of which was a circular window closed by shōji which parted right and
left. The shōji may have run within the partition, or rested in a
grooved frame on the other side of the wall. Above this circular
window and near the ceiling was a long rectangular window, also
having shōji, which could be open for ventilation. To the left of the
chigai-dana was a row of deep cupboards enclosed by a set of [pg
141] sliding screens; above was a broad shelf, upon the upper
surface of which ran shōji, which when opened revealed another
room beyond. The frieze of this recess had a perforated design of
waves (fig. 120).

Severe and simple as a Japanese room appears to be, it may be seen


by this figure how many features for decorative display come in. The
ornamental openings or windows with their varied lattices, the sliding
screens and the cupboards with their rich sketches of landscapes and
trees, the natural woods, indeed many of these features might plainly
be adopted without modification for our rooms.

Fig. 122.—Guest-room showing writing-place.


Fig. 123.—Guest-room with wide tokonoma.

In another room (fig. 121) of a gentleman famous for his invention of


silk-reeling machinery the tokonoma, instead of being open to the
verandah, was protected by a permanent [pg 142] partition filling
half the side of the room bordering the verandah. In this partition
was a large circular window, having a graceful bamboo frame-work.
This opening was closed on the outside by a shōji, which hung on
hooks and could be removed when required. In this case the honored
guest, when seated in front of the tokonoma, is protected from the
wind and sun while the rest of the room may be open. In the place of
this partition there is often seen, in houses of the better class, a
recess having a low shelf, with cupboards beneath and an ornamental
window above. This is the writing-place (fig. 122); and upon the shelf
are placed the ink-stone, water-bottle, brush-rest and brushes, paper-
weight, and other conveniences of a literary man. Above are often
suspended a bell and wooden hammer, to call the servants when
required. A hanging vase of flowers is often suspended from the
partition above. For [pg 143] want of an original sketch showing this
recess I have adapted one from a Japanese book, entitled “Daiku
Tana Hinagata,” Vol. II. Those who have chanced to see the club
rooms of the Koyokuan will recall the elaborate and beautiful panel of
geometric work that fills the window of a recess of this nature.

Fig. 124.—Small guest-room.

In Fig. 123 the tokonoma occupies almost the entire side of the
room, the chigai-dana being reduced to an angular cupboard placed
in the corner and a small hooded partition hanging down from above;
the small window near by, with bamboo lattice, opened into another
room beyond. A tokonoma of this kind is available for the display of
sets of three or four pictures. This room was in the house of a former
Daimio.

[pg 144]
In the next figure (fig. 124) we have the sketch of a small room with
the tokonoma facing the verandah, and with no companion recess.
The little window near the floor opened into the tokonoma, which
extended behind the partition as far as the upright beam. The post
which formed one side of the tokonoma was a rough and irregular-
shaped stick. The treatment of cutting away a larger portion of it,
though hardly constructive, yet added a quaint effect to the room;
while the cross-beam of the tokonoma. usually a square and finished
[pg 145] beam, in this case was in a natural state, the bark only
being removed.

Fig. 125.—Guest-room of dwelling in Tokio.

In fig. 125 is shown a room of the plainest description; it was severe


in its simplicity. Here the tokonoma, though on that side of the room
running at right angles with the verandah, was in the corner of the
room, while the chigai-dana was next to the verandah. The recesses
were quite deep,—the chigai-dana having a single broad shelf, as
broad as the depth of the recess, this forming the top of a spacious
closet beneath. In the partition dividing these two recesses was a
long narrow rectangular opening. The little bamboo flower-holder
hanging to the post of the toko-bashira had, besides a few flowers,
two long twigs of willow, which were made to bend gracefully in front
of the tokonoma. The character of this room indicated that its owner
was a lover of the tea-ceremonies.

Fig. 126.—Guest-koom in Kiyomidzu, Kioto.

The next figure (fig. 126) is that of a room in the second story of the
house of a famous potter in Kioto. This room [pg 146] was
remarkable for the purity of its finish. The toko-bashira consisted of
an unusually twisted stick of some kind of hard wood, the bark
having been removed, exposing a surface of singular smoothness.
The hooded partition over the chigai-dana had for its lower border a
rich dark-brown bamboo; the vertical piece forming the other side of
the chigai-dana was a black post hewn in an octagonal shape, with
curious irregular crosscuts on the faces. The sliding doors closing the
shelf in this recess were covered with gold paper. The hikite consisted
of sections of bamboo let in to the surface. The plaster of both
recesses was a rich, warm, umber color. The ceiling consisted [pg
147] of large square panels of old cedar richly grained. This room
was comparatively modern, having been built in 1868.

Fig. 127.—Guest-room of dwelling in Tokio.

Fig. 127 represents a room in the second story of a house in Tokio.


The recesses were remarkably rich and effective. The entire end of
the room formed a recess, having a plaited ceiling; and within this
recess were the tokonoma and chigai-dana, each having its own
hooded partition at a different level and depth,—the vertical partition
usually dividing these recesses being represented only by a square
beam against the wall. A reference, however, to the figure will convey
a clearer idea of these features than any description. The ceiling,
which was quite remarkable in its way, will be described later.
Fig. 128.—Guest-room of a country house.

The next interior (fig. 128) represents a room in a country house of


the poorer class. The recesses were of the plainest description. The
tokonoma was modified in a curious way by a break in the partition
above, and beneath, this modification was a shelf wrought out of a
black, worm-eaten plank from [pg 148] some old shipwreck. The
chigai-dana had an angular-shaped shelf in one of its corners, and in
the other corner two little shelves supported by a post. The floor of
this recess was on a level with the mats, while the floor of the
tokonoma was only slightly raised above this level.

The figures of interiors thus far given present some idea of the
infinite variety of design seen in the two recesses which characterize
the best room in the house. The typical form having been shown in
fig. 96, it will be seen how far these bays may vary in form and
structure while still possessing the distinguishing features of the
tokonoma and chigai-dana. In the first recess hangs the ever present
scroll, upon which may be a picture; or it may present a number of
Chinese characters which convey some moral precept, or lines from
some classical poem. On its floor rests the vase for flowers, a figure
in pottery, an incense burner, a fragment of quartz, or other object,
these being often supported by a lacquer stand. In the chigai-dana
convenient shelves and closets are arranged in a variety of ways, to
be used for a variety of purposes.

Fig. 129.—Corner of guest-room.

The arrangement of the cross-ties in relation to the tokonoma and


shōji is illustrated in fig. 129, which shows the corner of a room with
the upper portion of the tokonoma and shōji showing. The use made
of the ornamental-headed nail is seen where the kamoi joins the
corner post.

[pg 149]
In houses of two stories greater latitude is shown in the arrangement
of these recesses. They may come opposite the balcony, and the
chigai-dana may have in its back wall an opening either circular,
crescent-shaped, or of some other form, from which a pleasing view
is obtained either of the garden below or some distant range beyond.

Thus far we have examined the room which would parallel our
drawing-room or parlor; the other rooms vary from this in being
smaller, and having, of course, no recesses such as have been
described. By an examination of the plans given in the first part of
this chapter, it will be seen how very simple many of the rooms are,—
sometimes having a recess for a case of drawers or shelves; a closet,
possibly, but nothing else to break the rectangular outline, which may
be bounded on all sides by the sliding fusuma, or have one or more
permanent partitions.

Another class of rooms may here be considered, the details of which


are more severely simple even than those of the rooms just
described. These apartments are constructed expressly for
ceremonial tea-parties. A volume might be filled with a description of
the various forms of buildings connected with these observances; and
indeed another volume might be filled with the minor details
associated with their different schools.

In brief, the party comes about by the host inviting a company of four
to attend the tea-ceremony, and in their presence making the tea in a
bowl after certain prescribed forms, and offering it to the guests. To
be more explicit as to the mode of conducting this ceremony,—the
tea is first prepared by grinding it to a fine, almost impalpable,
powder. This may be done by a servant before the assemblage of the
guests, or may be ordered ground from a tea shop; indeed, the host
may grind it himself. This material, always freshly ground for each
party, is usually kept in a little earthen jar, having an ivory cover,—the
[pg 150] well-known cha-ire of the collector. Lacquer-boxes may also
be used for this purpose. The principal utensils used in the ceremony
consist of a furo, or fire-pot, made of pottery (or use may be made of
a depression in the floor partially filled with ashes, in which the
charcoal may be placed); an iron kettle to boil the water in; a
bamboo dipper of the most delicate construction, to dip out the
water; a wide-mouthed jar, from which to replenish the water in the
kettle; a bowl, in which the tea is made; a bamboo spoon, to dip out
the powdered tea; a bamboo stirrer, not unlike certain forms of egg-
beaters, by which the tea is briskly stirred after the hot water has
been added; a square silk cloth, with which to wipe the jar and spoon
properly; a little rest for the tea-kettle cover, made of pottery or
bronze or section of bamboo; a shallow vessel, in which the rinsings
of the tea-bowl are poured after washing; a brush, consisting of three
feathers of the eagle or some other large bird, to dust the edge of
the fire-vessel; and finally a shallow basket, in which is not only
charcoal to replenish the fire, but a pair of metal rods or hibashi to
handle the coal, two interrupted metal rings by which the kettle is
lifted off the fire, a circular mat upon which the kettle is placed, and a
small box containing incense, or bits of wood that give out a peculiar
fragrance when burned. With the exception of the fire-vessel and an
iron kettle, all these utensils have to be brought in by the host with
great formality and in a certain sequence, and placed with great
precision upon the mats after the prescribed rules of certain schools.
In the making of the tea, the utensils are used in a most exact and
formal manner.

The making of the tea, watched by one knowing nothing about the
ceremony, seems as grotesque a performance as one can well
imagine. Many of the forms connected with it seem uselessly absurd;
and yet having taken many lessons in the art of tea-making, I found
that with few exceptions it was natural [pg 151] and easy; and the
guests assembled on such an occasion, though at first sight
appearing stiff, are always perfectly at their ease. The proper placing
of the utensils, and the sequence in handling them and making the
tea are all natural and easy movements, as I have said. The light
wiping of the tea-jar, and the washing of the bowl and its wiping with
so many peripheral jerks, the dropping of the stirrer against the side
of the bowl with a click in rinsing, and a few of the other usual
movements are certainly grotesquely formal enough; but I question
whether the etiquette of a ceremonious dinner-party at home, with
the decorum observed in the proper use of each utensil, does not
strike a Japanese as equally odd and incomprehensible when
experienced by him for the first time.

This very brief and imperfect allusion has been made in order to
explain, that so highly do the Japanese regard this ceremony that
little isolated houses are specially constructed for the express
purpose of entertaining tea-parties. If no house is allotted for the
purpose, then a special room is fitted for it. Many books are devoted
to the exposition of the different schools of tea-ceremonies,
illustrated with diagrams showing the various ways of placing the
utensils, plans of the tea-rooms, and all the details involved in the
observances.

The tea-ceremonies have had a profound influence on many


Japanese arts. Particularly have they affected the pottery of Japan;
for the rigid simplicity, approaching an affected roughness and
poverty, which characterizes the tea-room and many of the utensils
used in the ceremony, has left its impress upon many forms of
pottery. It has also had an influence on even the few rustic and
simple adornments allowed in the room, and has held its sway over
the gardens, gateways, and fences surrounding the house. Indeed, it
has had an effect on the Japanese almost equal to that of Calvinistic
doctrines on the early Puritans. The one suppressed the exuberance
of an [pg 152] art-loving people, and brought many of their
decorative impulses down to a restful purity and simplicity; but in the
case of the Puritans and their immediate descendants, who had but
little of the art-spirit to spare, their sombre dogmas crushed the little
love for art that might have dawned, and rendered intolerably woful
and sepulchral the lives and homes of our ancestors; and when some
faint groping for art and adornment here and there appeared, it
manifested itself only in wretched samplers and hideous tomb-stones,
with tearful willow or death-bed scenes done in cold steel. Whittier
gives a good picture of such a home, in his poem “Among the Hills”:

bookless, pictureless,
Save the inevitable sampler hung
Over the fireplace; or a mourning-piece,—
A green-haired woman, peony-cheeked, beneath
Impossible willows; the wide-throated hearth
Bristling with faded pine-boughs, half concealing
The piled-up rubbish at the chimney's back.

[pg 153]
Fig. 130.—Tea-room in Nan-en-ji temple, Kioto.

Fig. 131.—Tea-room in Fujimi pottery, Nagoya.

But we are digressing. Having given some idea of the formal


character of the tea-ceremonies, it is not to be wondered at that
special rooms, and even special buildings, should be designed and
built expressly for those observances. We give a few illustrations of
the interiors of rooms used for this purpose.

Fig. 130 is that of a room in Nan-en-ji temple, in Kioto, said to have


been specially designed, in the early part of the seventeenth century,
by Kobori Yenshiu,—a famous master of tea-ceremonies, and a
founder of one of its schools. The room was exceedingly small, a four
and a half mat room I believe, which is the usual size. The drawing,
from necessity of perspective, makes it appear much larger. The
ceiling was of rush and bamboo; the walls were roughly plastered
with bluish-gray clay; the cross-ties and uprights were of pine, with
the bark retained. The room had eight small windows of various
sizes, placed at various [pg 154] heights in different parts of the
room; and this was in accordance with Yenshiu's taste. Only one
recess, the tokonoma, is seen in the room,—in which may hang at
the time of a party a picture, to be replaced, at a certain period of
the ceremony, by a hanging basket of flowers. The ro, or fireplace, is
a depressed area in the floor, deep enough to hold a considerable
amount of ashes, as well as a tripod upon which the kettle rests.

Fig. 131 represents an odd-looking tearoom, at the Fujimi pottery, in


Nagoya, where tea was made and served to us by the potter's
daughter. The room was simple enough, yet quite ornate compared
with the one first described. The ceiling consisted of a matting of thin
wood-strips, bamboo and red pine being used for the cross-ties and
uprights. The tokonoma, having a bamboo post, is seen at the left of
the figure. The ro, in this case, was triangular.
Fig. 132.—Tea-room in Miyajima.

In fig. 132 is represented a view of a small tea-room at Miyajima; the


chasteness of its finish is but feebly conveyed in the figure. Here the
ro was circular, and was placed in a wide plank of polished wood. The
room was connected with other apartments of the house, and did not
constitute a house by itself.

[pg 155]
In some houses there is a special place or room adjoining the tea-
room, in which the tea-utensils are kept properly arranged, and from
which they are brought when tea is made, and to which they are
afterwards returned with great formality. Fig. 133 represents one of
these rooms in a house in Imado, Tokio. In this room the same
simplicity of finish was seen. It was furnished [pg 156] with shelves,
a little closet to contain the utensils, and a depressed area in the
floor, having for its bottom a bamboo grating through which the
water ran when emptied into it. Resting upon this bamboo grating
were a huge pottery-vessel for water and a common hand-basin of
copper. The floor was of polished wood. At the farther end was the
entrance, by means of a low door, closed by fusuma.
Fig. 133.—Kitchen for tea-utensils.
Fig. 134.—Tea-room in Imado, Tokio.

In fig. 134 is given the view of a room in a Tokio house that was
extremely ornate in its finish. The owner of the house had built it
some thirty years before, and had intended carrying out Chinese
ideas of design and furnishing. Whether he had got his ideas from
books, or had evolved them from his inner consciousness, I do not
know; certain it is, that although he had worked into its structure a
number of features actually [pg 157] brought from China, I must say
that in my limited observations in that country I saw nothing
approaching such an interior or building. The effect of the room was
certainly charming, and the most elaborate finish with expensive
woods had been employed in its construction. It seemed altogether
too ornamental for the tea-ceremonies to suit the Japanese taste.
The ceiling was particularly unique; for running diagonally across it
from one corner to the other was a stout bamboo in two curves, and
upon this bamboo was engraved a Chinese poem. The ceiling on one
side of the bamboo was finished in large square panels of an
elaborately-grained wood; on the other side were small panels of
cedar. Exotic woods, palms, bamboo, and red-pine were used for

You might also like