Commit e1900b2b authored by Thomas G. Lockhart's avatar Thomas G. Lockhart

First version of markup which can run through jade for html.

Probably not acceptable yet. Need to check some math symbols and markup.
parent d8a3a8c0
...@@ -4,119 +4,132 @@ ...@@ -4,119 +4,132 @@
<abstract> <abstract>
<para> <para>
This chapter originally appeared as a part of This chapter originally appeared as a part of
Stefan Simkovics' Master's Thesis. Stefan Simkovics' Master's Thesis
(<xref linkend="SIM98" endterm="SIM98">).
<!-- Move this info to the bibliography
\title{{\Large Master's Thesis}\\
\vspace{1cm}
Enhancement of the ANSI SQL Implementation of PostgreSQL\\[1em]
{\normalsize written by\\[1em]}
{\large Stefan Simkovics\\
Paul Petersgasse 36\\
2384 Breitenfurt\\
AUSTRIA \\
ssimkovi@ag.or.at\\[1em]}
{\normalsize at \\[1em]}
{\large Department of Information Systems\\
Vienna University of Technology\\[1em]}
{\normalsize with support by\\[1em]}
{\large O.Univ.Prof.Dr. Georg Gottlob\\}
{\normalsize and\\}
{\large Univ.Ass. Mag. Katrin Seyr\\}}
-->
</para> </para>
</abstract> </abstract>
<para> <para>
SQL has become one of the most popular relational query languages all <acronym>SQL</acronym> has become the most popular relational query language.
over the world. The name <quote><acronym>SQL</acronym></quote> is an abbreviation for
The name "<literal>SQL</literal>" is an abbreviation for
<firstterm>Structured Query Language</firstterm>. <firstterm>Structured Query Language</firstterm>.
In 1974 Donald Chamberlin and others defined the In 1974 Donald Chamberlin and others defined the
language SEQUEL (<firstterm>Structured English Query Language</firstterm>) at IBM language SEQUEL (<firstterm>Structured English Query Language</firstterm>) at IBM
Research. This language was first implemented in an IBM Research. This language was first implemented in an IBM
prototype called SEQUEL-XRM in 1974-75. In 1976-77 a revised version prototype called SEQUEL-XRM in 1974-75. In 1976-77 a revised version
of SEQUEL called SEQUEL/2 was defined and the name was changed to SQL of SEQUEL called SEQUEL/2 was defined and the name was changed to
<acronym>SQL</acronym>
subsequently. subsequently.
</para> </para>
<para> <para>
A new prototype called System R was developed by IBM in 1977. System R A new prototype called System R was developed by IBM in 1977. System R
implemented a large subset of SEQUEL/2 (now SQL) and a number of implemented a large subset of SEQUEL/2 (now <acronym>SQL</acronym>) and a number of
changes were made to SQL during the project. System R was installed in changes were made to <acronym>SQL</acronym> during the project.
a number of user sites, both internal IBM sites and also some selected System R was installed in
customer sites. Thanks to the success and acceptance of System R at a number of user sites, both internal IBM sites and also some selected
those user sites IBM started to develop commercial products that customer sites. Thanks to the success and acceptance of System R at
implemented the SQL language based on the System R technology. those user sites IBM started to develop commercial products that
implemented the <acronym>SQL</acronym> language based on the System R technology.
</para> </para>
<para> <para>
Over the next years IBM and also a number of other vendors announced Over the next years IBM and also a number of other vendors announced
SQL products such as SQL/DS (IBM), DB2 (IBM) ORACLE (Oracle Corp.) <acronym>SQL</acronym> products such as
DG/SQL (Data General Corp.) SYBASE (Sybase Inc.). <productname>SQL/DS</productname> (IBM),
<productname>DB2</productname> (IBM),
<productname>ORACLE</productname> (Oracle Corp.),
<productname>DG/SQL</productname> (Data General Corp.),
and <productname>SYBASE</productname> (Sybase Inc.).
</para> </para>
<para> <para>
SQL is also an official standard now. In 1982 the American National <acronym>SQL</acronym> is also an official standard now. In 1982 the American National
Standards Institute (ANSI) chartered its Database Committee X3H2 to Standards Institute (<acronym>ANSI</acronym>) chartered its Database Committee X3H2 to
develop a proposal for a standard relational language. This proposal develop a proposal for a standard relational language. This proposal
was ratified in 1986 and consisted essentially of the IBM dialect of was ratified in 1986 and consisted essentially of the IBM dialect of
SQL. In 1987 this ANSI standard was also accepted as an international <acronym>SQL</acronym>. In 1987 this <acronym>ANSI</acronym>
standard by the International Organization for Standardization standard was also accepted as an international
(ISO). This original standard version of SQL is often referred to, standard by the International Organization for Standardization
informally, as "SQL/86". In 1989 the original standard was extended (<acronym>ISO</acronym>).
and this new standard is often, again informally, referred to as This original standard version of <acronym>SQL</acronym> is often referred to,
"SQL/89". Also in 1989, a related standard called {\it Database informally, as "<abbrev>SQL/86</abbrev>". In 1989 the original standard was extended
Language Embedded SQL} was developed. and this new standard is often, again informally, referred to as
"<abbrev>SQL/89</abbrev>". Also in 1989, a related standard called
<firstterm>Database Language Embedded <acronym>SQL</acronym></firstterm>
(<acronym>ESQL</acronym>) was developed.
</para> </para>
<para> <para>
The ISO and ANSI committees have been working for many years on the The <acronym>ISO</acronym> and <acronym>ANSI</acronym> committees
have been working for many years on the
definition of a greatly expanded version of the original standard, definition of a greatly expanded version of the original standard,
referred to informally as "SQL2" or "SQL/92". This version became a referred to informally as <firstterm><acronym>SQL2</acronym></firstterm>
ratified standard - "International Standard \mbox{ISO/IEC 9075:1992}, {\it or <firstterm><acronym>SQL/92</acronym></firstterm>. This version became a
Database Language SQL}" - in late 1992. "SQL/92" is the version ratified standard - "International Standard ISO/IEC 9075:1992,
normally meant when people refer to "the SQL standard". A detailed Database Language <acronym>SQL</acronym>" - in late 1992.
description of "SQL/92" is given in \cite{date}. At the time of <acronym>SQL/92</acronym> is the version
writing this document a new standard informally referred to as "SQL3" normally meant when people refer to "the <acronym>SQL</acronym> standard". A detailed
is under development. It is planned to make SQL a turing-complete description of <acronym>SQL/92</acronym> is given in
language, i.e.\ all computable queries (e.g. recursive queries) will be <xref linkend="DATE97" endterm="DATE97">. At the time of
writing this document a new standard informally referred to
as <firstterm><acronym>SQL3</acronym></firstterm>
is under development. It is planned to make <acronym>SQL</acronym> a Turing-complete
language, i.e. all computable queries (e.g. recursive queries) will be
possible. This is a very complex task and therefore the completion of possible. This is a very complex task and therefore the completion of
the new standard can not be expected before 1999. the new standard can not be expected before 1999.
</para> </para>
<sect1 id="rel-model"> <sect1 id="rel-model">
<title>The Relational Data Model}</title> <title>The Relational Data Model</title>
<para> <para>
As mentioned before, SQL is a relational language. That means it is As mentioned before, <acronym>SQL</acronym> is a relational
based on the "relational data model" first published by E.F. Codd in language. That means it is
based on the <firstterm>relational data model</firstterm>
first published by E.F. Codd in
1970. We will give a formal description of the relational model in 1970. We will give a formal description of the relational model in
section <xref id="formal-notion"> section <xref linkend="formal-notion" endterm="formal-notion">
<!--{\it Formal Notion of the Relational Data Model}--> <!--{\it Formal Notion of the Relational Data Model}-->
but first we want to have a look at it from a more intuitive but first we want to have a look at it from a more intuitive
point of view. point of view.
</para> </para>
<para> <para>
A {\it relational database} is a database that is perceived by its A <firstterm>relational database</firstterm> is a database that is perceived by its
users as a {\it collection of tables} (and nothing else but tables). users as a <firstterm>collection of tables</firstterm> (and nothing else but tables).
A table consists of rows and columns where each row represents a A table consists of rows and columns where each row represents a
record and each column represents an attribute of the records record and each column represents an attribute of the records
contained in the table. Figure \ref{supplier} shows an example of a contained in the table.
database consisting of three tables: Figure <xref linkend="supplier-fig" endterm="supplier-fig">
\begin{itemize} shows an example of a database consisting of three tables:
\item SUPPLIER is a table storing the number
(SNO), the name (SNAME) and the city (CITY) of a supplier. <itemizedlist>
\item PART is a table storing the number (PNO) the name (PNAME) and <listitem>
the price (PRICE) of a part. <para>
\item SELLS stores information about which part (PNO) is sold by which SUPPLIER is a table storing the number
supplier (SNO). It serves in a sense to connect the other two tables (SNO), the name (SNAME) and the city (CITY) of a supplier.
together. </para>
\end{itemize} </listitem>
%
\begin{figure}[h] <listitem>
\begin{verbatim} <para>
PART is a table storing the number (PNO) the name (PNAME) and
the price (PRICE) of a part.
</para>
</listitem>
<listitem>
<para>
SELLS stores information about which part (PNO) is sold by which
supplier (SNO).
It serves in a sense to connect the other two tables together.
</para>
</listitem>
</itemizedlist>
<example>
<title id="supplier-fig">The Suppliers and Parts Database</title>
<programlisting>
SUPPLIER SNO | SNAME | CITY SELLS SNO | PNO SUPPLIER SNO | SNAME | CITY SELLS SNO | PNO
-----+---------+-------- -----+----- -----+---------+-------- -----+-----
1 | Smith | London 1 | 1 1 | Smith | London 1 | 1
...@@ -131,56 +144,132 @@ together. ...@@ -131,56 +144,132 @@ together.
2 | Nut | 8 2 | Nut | 8
3 | Bolt | 15 3 | Bolt | 15
4 | Cam | 25 4 | Cam | 25
\end{verbatim} </programlisting>
\caption{The suppliers and parts database} </example>
\label{supplier} </para>
\end{figure}
% <para>
The tables PART and SUPPLIER may be regarded as {\it entities} and The tables PART and SUPPLIER may be regarded as <firstterm>entities</firstterm> and
SELLS may be regarded as a {\it relationship} between a particular SELLS may be regarded as a <firstterm>relationship</firstterm> between a particular
part and a particular supplier. part and a particular supplier.
</para>
As we will see later, SQL operates on tables like the ones just
defined but before that we will study the theory of the relational <para>
model. As we will see later, <acronym>SQL</acronym> operates on tables like the ones just
defined but before that we will study the theory of the relational
\subsection{Formal Notion of the Relational Data Model} model.
\label{formal_notion} </para>
The mathematical concept underlying the relational model is the </sect1>
set-theoretic {\it relation} which is a subset of the Cartesian
product of a list of domains. This set-theoretic {\it relation} gives <sect1>
the model its name (do not confuse it with the relationship from the {\it <title id="formal-notion">Formal Notion of the Relational Data Model</title>
Entity-Relationship model}). Formally a domain is simply a set of
values. For example the set of integers is a domain. Also the set of <para>
character strings of length 20 and the real numbers are examples of The mathematical concept underlying the relational model is the
domains. set-theoretic <firstterm>relation</firstterm> which is a subset of the Cartesian
product of a list of domains. This set-theoretic relation gives
the model its name (do not confuse it with the relationship from the
<firstterm>Entity-Relationship model</firstterm>).
Formally a domain is simply a set of
values. For example the set of integers is a domain. Also the set of
character strings of length 20 and the real numbers are examples of
domains.
</para>
<para>
<!--
\begin{definition} \begin{definition}
The {\it Cartesian} product of domains $D_{1}, D_{2},\ldots, D_{k}$ written The <firstterm>Cartesian product</firstterm> of domains $D_{1}, D_{2},\ldots, D_{k}$ written
\mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$} is the set of \mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$} is the set of
all $k$-tuples $(v_{1},v_{2},\ldots,v_{k})$ such that \mbox{$v_{1} \in all $k$-tuples $(v_{1},v_{2},\ldots,v_{k})$ such that \mbox{$v_{1} \in
D_{1}, v_{2} \in D_{2}, \ldots, v_{k} \in D_{k}$}. D_{1}, v_{2} \in D_{2}, \ldots, v_{k} \in D_{k}$}.
\end{definition} \end{definition}
For example, when we have $k=2$, $D_{1}=\{0,1\}$ and -->
The <firstterm>Cartesian product</firstterm> of domains
<parameter>D<subscript>1</subscript></parameter>,
<parameter>D<subscript>2</subscript></parameter>,
...
<parameter>D<subscript>k</subscript></parameter>,
written
<parameter>D<subscript>1</subscript></parameter> &times;
<parameter>D<subscript>2</subscript></parameter> &times;
... &times;
<parameter>D<subscript>k</subscript></parameter>
is the set of all k-tuples
<parameter>v<subscript>1</subscript></parameter>,
<parameter>v<subscript>2</subscript></parameter>,
...
<parameter>v<subscript>k</subscript></parameter>,
such that
<parameter>v<subscript>1</subscript></parameter> &isin;
<parameter>D<subscript>1</subscript></parameter>,
<parameter>v<subscript>1</subscript></parameter> &isin;
<parameter>D<subscript>1</subscript></parameter>,
...
<parameter>v<subscript>k</subscript></parameter> &isin;
<parameter>D<subscript>k</subscript></parameter>.
</para>
<para>
For example, when we have
<!--
$k=2$, $D_{1}=\{0,1\}$ and
$D_{2}=\{a,b,c\}$, then $D_{1} \times D_{2}$ is $D_{2}=\{a,b,c\}$, then $D_{1} \times D_{2}$ is
$\{(0,a),(0,b),(0,c),(1,a),(1,b),(1,c)\}$. $\{(0,a),(0,b),(0,c),(1,a),(1,b),(1,c)\}$.
% -->
<parameter>k</parameter>=2,
<parameter>D<subscript>1</subscript></parameter>=<literal>{0,1}</literal> and
<parameter>D<subscript>2</subscript></parameter>=<literal>{a,b,c}</literal> then
<parameter>D<subscript>1</subscript></parameter> &times;
<parameter>D<subscript>2</subscript></parameter> is
<literal>{(0,a),(0,b),(0,c),(1,a),(1,b),(1,c)}</literal>.
</para>
<para>
<!--
\begin{definition} \begin{definition}
A Relation is any subset of the Cartesian product of one or more A Relation is any subset of the Cartesian product of one or more
domains: $R \subseteq$ \mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$} domains: $R \subseteq$ \mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$}
\end{definition} \end{definition}
% -->
For example $\{(0,a),(0,b),(1,a)\}$ is a relation, it is in fact a A Relation is any subset of the Cartesian product of one or more
subset of $D_{1} \times D_{2}$ mentioned above. domains: <parameter>R</parameter> &sube;
The members of a relation are called tuples. Each relation of some <parameter>D<subscript>1</subscript></parameter> &times;
Cartesian product \mbox{$D_{1} \times D_{2} \times \ldots \times <parameter>D<subscript>2</subscript></parameter> &times;
D_{k}$} is said to have arity $k$ and is therefore a set of $k$-tuples. ... &times;
<parameter>D<subscript>k</subscript></parameter>.
A relation can be viewed as a table (as we already did, remember </para>
figure \ref{supplier} {\it The suppliers and parts database}) where
every tuple is represented by a row and every column corresponds to <para>
one component of a tuple. Giving names (called attributes) to the For example <literal>{(0,a),(0,b),(1,a)}</literal> is a relation;
columns leads to the definition of a {\it relation scheme}. it is in fact a subset of
% <parameter>D<subscript>1</subscript></parameter> &times;
<parameter>D<subscript>2</subscript></parameter>
mentioned above.
</para>
<para>
The members of a relation are called tuples. Each relation of some
Cartesian product
<parameter>D<subscript>1</subscript></parameter> &times;
<parameter>D<subscript>2</subscript></parameter> &times;
... &times;
<parameter>D<subscript>k</subscript></parameter>
is said to have arity <literal>k</literal> and is therefore a set
of <literal>k</literal>-tuples.
</para>
<para>
A relation can be viewed as a table (as we already did, remember
<xref linkend="supplier-fig" endterm="supplier-fig"> where
every tuple is represented by a row and every column corresponds to
one component of a tuple. Giving names (called attributes) to the
columns leads to the definition of a
<firstterm>relation scheme</firstterm>.
</para>
<para>
<!--
\begin{definition} \begin{definition}
A {\it relation scheme} $R$ is a finite set of attributes A {\it relation scheme} $R$ is a finite set of attributes
\mbox{$\{A_{1},A_{2},\ldots,A_{k}\}$}. There is a domain $D_{i}$ for \mbox{$\{A_{1},A_{2},\ldots,A_{k}\}$}. There is a domain $D_{i}$ for
...@@ -188,101 +277,230 @@ each attribute $A_{i}, 1 \le i \le k$ where the values of the ...@@ -188,101 +277,230 @@ each attribute $A_{i}, 1 \le i \le k$ where the values of the
attributes are taken from. We often write a relation scheme as attributes are taken from. We often write a relation scheme as
\mbox{$R(A_{1},A_{2},\ldots,A_{k})$}. \mbox{$R(A_{1},A_{2},\ldots,A_{k})$}.
\end{definition} \end{definition}
{\bf Note:} A {\it relation scheme} is just a kind of template -->
whereas a {\it relation} is an instance of a {\it relation A <firstterm>relation scheme</firstterm> <literal>R</literal> is a
scheme}. The {\it relation} consists of tuples (and can therefore be finite set of attributes
viewed as a table) not so the {\it relation scheme}. <parameter>A<subscript>1</subscript></parameter>,
<parameter>A<subscript>2</subscript></parameter>,
\subsubsection{Domains vs. Data Types} ...
\label{domains} <parameter>A<subscript>k</subscript></parameter>.
We often talked about {\it domains} in the last section. Recall that a There is a domain
domain is, formally, just a set of values (e.g., the set of integers or <parameter>D<subscript>i</subscript></parameter>,
the real numbers). In terms of database systems we often talk of {\it for each attribute
data types} instead of domains. When we define a table we have to make <parameter>A<subscript>i</subscript></parameter>,
a decision about which attributes to include. Additionally we 1 &le; <literal>i</literal> &le; <literal>k</literal>,
have to decide which kind of data is going to be stored as where the values of the attributes are taken from. We often write
attribute values. For example the values of SNAME from the table a relation scheme as
SUPPLIER will be character strings, whereas SNO will store <literal>R(<parameter>A<subscript>1</subscript></parameter>,
integers. We define this by assigning a {\it data type} to each <parameter>A<subscript>2</subscript></parameter>,
attribute. The type of SNAME will be VARCHAR(20) (this is the SQL type ...
for character strings of length $\le$ 20), the type of SNO will be <parameter>A<subscript>k</subscript></parameter>)</literal>.
INTEGER. With the assignment of a {\it data type} we also have selected
a domain for an attribute. The domain of SNAME is the set of all <note>
character strings of length $\le$ 20, the domain of SNO is the set of <para>
all integer numbers. A <firstterm>relation scheme</firstterm> is just a kind of template
whereas a <firstterm>relation</firstterm> is an instance of a <firstterm>relation
\section{Operations in the Relational Data Model} scheme</firstterm>. The relation consists of tuples (and can therefore be
\label{operations} viewed as a table); not so the relation scheme.
In section \ref{formal_notion} we defined the mathematical notion of </para>
the relational model. Now we know how the data can be stored using a </note>
relational data model but we do not know what to do with all these </para>
tables to retrieve something from the database yet. For example somebody
could ask for the names of all suppliers that sell the part <sect2>
'Screw'. Therefore two rather different kinds of notations for <title id="domains">Domains vs. Data Types</title>
expressing operations on relations have been defined:
% <para>
\begin{itemize} We often talked about <firstterm>domains</firstterm>
\item The {\it Relational Algebra} which is an algebraic notation, in the last section. Recall that a
where queries are expressed by applying specialized operators to the domain is, formally, just a set of values (e.g., the set of integers or
relations. the real numbers). In terms of database systems we often talk of
\item The {\it Relational Calculus} which is a logical notation, <firstterm>data types</firstterm> instead of domains.
where queries are expressed by formulating some logical restrictions When we define a table we have to make
that the tuples in the answer must satisfy. a decision about which attributes to include. Additionally we
\end{itemize} have to decide which kind of data is going to be stored as
% attribute values. For example the values of
\subsection{Relational Algebra} <classname>SNAME</classname> from the table
\label{rel_alg} <classname>SUPPLIER</classname> will be character strings,
The {\it Relational Algebra} was introduced by E.~F.~Codd in 1972. It whereas <classname>SNO</classname> will store
consists of a set of operations on relations: integers. We define this by assigning a data type to each
\begin{itemize} attribute. The type of <classname>SNAME</classname> will be
\item SELECT ($\sigma$): extracts {\it tuples} from a relation that <type>VARCHAR(20)</type> (this is the <acronym>SQL</acronym> type
satisfy a given restriction. Let $R$ be a table that contains an attribute for character strings of length &le; 20), the type of <classname>SNO</classname> will be
$A$. $\sigma_{A=a}(R) = \{t \in R \mid t(A) = a\}$ where $t$ denotes a <type>INTEGER</type>. With the assignment of a data type we also have selected
tuple of $R$ and $t(A)$ denotes the value of attribute $A$ of tuple $t$. a domain for an attribute. The domain of <classname>SNAME</classname> is the set of all
\item PROJECT ($\pi$): extracts specified {\it attributes} (columns) from a character strings of length &le; 20, the domain of <classname>SNO</classname> is the set of
relation. Let $R$ be a relation that contains an attribute $X$. $\pi_{X}(R) = all integer numbers.
\{t(X) \mid t \in R\}$, where $t(X)$ denotes the value of attribute $X$ of </para>
tuple $t$. </sect2>
\item PRODUCT ($\times$): builds the Cartesian product of two </sect1>
relations. Let $R$ be a table with arity $k_{1}$ and let $S$ be a table with
arity $k_{2}$. $R\times S$ is the set of all $(k_{1}+k_{2})$-tuples <sect1>
whose first $k_{1}$ components form a tuple in $R$ and whose last <title id="operations">Operations in the Relational Data
$k_{2}$ components form a tuple in $S$. Model</title>
\item UNION ($\cup$): builds the set-theoretic union of two
tables. Given the tables $R$ and $S$ (both must have the same arity), <para>
the union $R \cup S$ is the set of tuples that are in $R$ or $S$ or In section <xref linkend="formal-notion" endterm="formal-notion">
both. we defined the mathematical notion of
\item INTERSECT ($\cap$): builds the set-theoretic intersection of two the relational model. Now we know how the data can be stored using a
tables. Given the tables $R$ and $S$, $R \cup S$ is the set of tuples relational data model but we do not know what to do with all these
that are in $R$ and in $S$. We again require that $R$ and $S$ have the tables to retrieve something from the database yet. For example somebody
same arity. could ask for the names of all suppliers that sell the part
\item DIFFERENCE ($-$ or $\setminus$): builds the set difference of 'Screw'. Therefore two rather different kinds of notations for
two tables. Let $R$ and $S$ again be two tables with the same expressing operations on relations have been defined:
arity. $R-S$ is the set of tuples in $R$ but not in $S$.
\item JOIN ($\Join$): connects two tables by their common <itemizedlist>
attributes. Let $R$ be a table with the attributes $A,B$ and $C$ and <listitem>
let $S$ a table with the attributes $C,D$ and $E$. There is one <para>
attribute common to both relations, the attribute $C$. $R \Join S = The <firstterm>Relational Algebra</firstterm> which is an algebraic notation,
\pi_{R.A,R.B,R.C,S.D,S.E}(\sigma_{R.C=S.C}(R \times S))$. What are we where queries are expressed by applying specialized operators to the
doing here? We first calculate the Cartesian product $R \times relations.
S$. Then we select those tuples whose values for the common </para>
attribute $C$ are equal ($\sigma_{R.C = S.C}$). Now we got a table </listitem>
that contains the attribute $C$ two times and we correct this by
projecting out the duplicate column. <listitem>
\begin{example} <para>
\label{join_example} The <firstterm>Relational Calculus</firstterm> which is a logical notation,
Let's have a look at the tables that are produced by evaluating the steps where queries are expressed by formulating some logical restrictions
necessary for a join. \\ that the tuples in the answer must satisfy.
Let the following two tables be given: </para>
\begin{verbatim} </listitem>
</itemizedlist>
</para>
<sect2>
<title id="rel-alg">Relational Algebra</title>
<para>
The <firstterm>Relational Algebra</firstterm> was introduced by
E. F. Codd in 1972. It consists of a set of operations on relations:
<itemizedlist>
<listitem>
<para>
SELECT (&sigma;): extracts <firstterm>tuples</firstterm> from a relation that
satisfy a given restriction. Let <parameter>R</parameter> be a
table that contains an attribute
<parameter>A</parameter>.
&sigma;<subscript>A=a</subscript>(R) = {t &isin; R &mid; t(A) = a}
where <literal>t</literal> denotes a
tuple of <parameter>R</parameter> and <literal>t(A)</literal>
denotes the value of attribute <parameter>A</parameter> of
tuple <literal>t</literal>.
</para>
</listitem>
<listitem>
<para>
PROJECT (&pi;): extracts specified
<firstterm>attributes</firstterm> (columns) from a
relation. Let <classname>R</classname> be a relation
that contains an attribute <classname>X</classname>.
&pi;<subscript>X</subscript>(<classname>R</classname>) = {t(X) &mid; t &isin; <classname>R</classname>},
where <literal>t</literal>(<classname>X</classname>) denotes the value of
attribute <classname>X</classname> of tuple <literal>t</literal>.
</para>
</listitem>
<listitem>
<para>
PRODUCT (&times;): builds the Cartesian product of two
relations. Let <classname>R</classname> be a table with arity
<literal>k</literal><subscript>1</subscript> and let
<classname>S</classname> be a table with
arity <literal>k</literal><subscript>2</subscript>.
<classname>R</classname> &times; <classname>S</classname>
is the set of all
<literal>k</literal><subscript>1</subscript>
+ <literal>k</literal><subscript>2</subscript>-tuples
whose first <literal>k</literal><subscript>1</subscript>
components form a tuple in <classname>R</classname> and whose last
<literal>k</literal><subscript>2</subscript> components form a
tuple in <classname>S</classname>.
</para>
</listitem>
<listitem>
<para>
UNION (&cup;): builds the set-theoretic union of two
tables. Given the tables <classname>R</classname> and
<classname>S</classname> (both must have the same arity),
the union <classname>R</classname> &cup; <classname>S</classname>
is the set of tuples that are in <classname>R</classname>
or <classname>S</classname> or both.
</para>
</listitem>
<listitem>
<para>
INTERSECT (&cap;): builds the set-theoretic intersection of two
tables. Given the tables <classname>R</classname> and
<classname>S</classname>,
<classname>R</classname> &cup; <classname>S</classname> is the set of tuples
that are in <classname>R</classname> and in
<classname>S</classname>.
We again require that <classname>R</classname> and <classname>S</classname> have the
same arity.
</para>
</listitem>
<listitem>
<para>
DIFFERENCE (&minus; or &setmn;): builds the set difference of
two tables. Let <classname>R</classname> and <classname>S</classname>
again be two tables with the same
arity. <classname>R</classname> - <classname>S</classname>
is the set of tuples in <classname>R</classname> but not in <classname>S</classname>.
</para>
</listitem>
<listitem>
<para>
JOIN (&prod;): connects two tables by their common
attributes. Let <classname>R</classname> be a table with the
attributes <classname>A</classname>,<classname>B</classname>
and <classname>C</classname> and
let <classname>S</classname> be a table with the attributes
<classname>C</classname>,<classname>D</classname>
and <classname>E</classname>. There is one
attribute common to both relations,
the attribute <classname>C</classname>.
<!--
<classname>R</classname> &prod; <classname>S</classname> =
&pi;<subscript><classname>R</classname>.<classname>A</classname>,<classname>R</classname>.<classname>B</classname>,<classname>R</classname>.<classname>C</classname>,<classname>S</classname>.<classname>D</classname>,<classname>S</classname>.<classname>E</classname></subscript>(&sigma;<subscript><classname>R</classname>.<classname>C</classname>=<classname>S</classname>.<classname>C</classname></subscript>(<classname>R</classname> &times; <classname>S</classname>)).
-->
R &prod; S = &pi;<subscript>R.A,R.B,R.C,S.D,S.E</subscript>(&sigma;<subscript>R.C=S.C</subscript>(R &times; S)).
What are we doing here? We first calculate the Cartesian
product
<classname>R</classname> &times; <classname>S</classname>.
Then we select those tuples whose values for the common
attribute <classname>C</classname> are equal
(&sigma;<subscript>R.C = S.C</subscript>).
Now we have a table
that contains the attribute <classname>C</classname>
two times and we correct this by
projecting out the duplicate column.
</para>
<para id="join-example">
Let's have a look at the tables that are produced by evaluating the steps
necessary for a join.
Let the following two tables be given:
<programlisting>
R A | B | C S C | D | E R A | B | C S C | D | E
---+---+--- ---+---+--- ---+---+--- ---+---+---
1 | 2 | 3 3 | a | b 1 | 2 | 3 3 | a | b
4 | 5 | 6 6 | c | d 4 | 5 | 6 6 | c | d
7 | 8 | 9 7 | 8 | 9
\end{verbatim} </programlisting>
First we calculate the Cartesian product $R \times S$ and get: </para>
\begin{verbatim}
<para>
First we calculate the Cartesian product
<classname>R</classname> &times; <classname>S</classname> and
get:
<programlisting>
R x S A | B | R.C | S.C | D | E R x S A | B | R.C | S.C | D | E
---+---+-----+-----+---+--- ---+---+-----+-----+---+---
1 | 2 | 3 | 3 | a | b 1 | 2 | 3 | 3 | a | b
...@@ -291,36 +509,65 @@ First we calculate the Cartesian product $R \times S$ and get: ...@@ -291,36 +509,65 @@ First we calculate the Cartesian product $R \times S$ and get:
4 | 5 | 6 | 6 | c | d 4 | 5 | 6 | 6 | c | d
7 | 8 | 9 | 3 | a | b 7 | 8 | 9 | 3 | a | b
7 | 8 | 9 | 6 | c | d 7 | 8 | 9 | 6 | c | d
\end{verbatim} </programlisting>
\pagebreak </para>
After the selection $\sigma_{R.C=S.C}(R \times S)$ we get:
\begin{verbatim} <para>
After the selection
&sigma;<subscript>R.C=S.C</subscript>(R &times; S)
we get:
<programlisting>
A | B | R.C | S.C | D | E A | B | R.C | S.C | D | E
---+---+-----+-----+---+--- ---+---+-----+-----+---+---
1 | 2 | 3 | 3 | a | b 1 | 2 | 3 | 3 | a | b
4 | 5 | 6 | 6 | c | d 4 | 5 | 6 | 6 | c | d
\end{verbatim} </programlisting>
To remove the duplicate column $S.C$ we project it out by the </para>
following operation: $\pi_{R.A,R.B,R.C,S.D,S.E}(\sigma_{R.C=S.C}(R
\times S))$ and get: <para>
\begin{verbatim} To remove the duplicate column
<classname>S</classname>.<classname>C</classname>
we project it out by the following operation:
&pi;<subscript>R.A,R.B,R.C,S.D,S.E</subscript>(&sigma;<subscript>R.C=S.C</subscript>(R &times; S))
and get:
<programlisting>
A | B | C | D | E A | B | C | D | E
---+---+---+---+--- ---+---+---+---+---
1 | 2 | 3 | a | b 1 | 2 | 3 | a | b
4 | 5 | 6 | c | d 4 | 5 | 6 | c | d
\end{verbatim} </programlisting>
\end{example} </para>
\item DIVIDE ($\div$): Let $R$ be a table with the attributes $A,B,C$ </listitem>
and $D$ and let $S$ be a table with the attributes $C$ and $D$. Then
we define the division as: $R \div S = \{t \mid \forall t_{s} \in S~ <listitem>
\exists t_{r} \in R$ such that <para>
$t_{r}(A,B)=t~\wedge~t_{r}(C,D)=t_{s}\}$ where $t_{r}(x,y)$ denotes a DIVIDE (&divide;): Let <classname>R</classname> be a table
tuple of table $R$ that consists only of the components $x$ and with the attributes A, B, C, and D and let
$y$. Note that the tuple $t$ only consists of the components $A$ and <classname>S</classname> be a table with the attributes
$B$ of relation $R$. C and D.
\begin{example} Then we define the division as:
Given the following tables
\begin{verbatim} R &divide; S = {t &mid; &forall; t<subscript>s</subscript> &isin; S
&exist; t<subscript>r</subscript> &isin; R
such that
t<subscript>r</subscript>(A,B)=t&and;t<subscript>r</subscript>(C,D)=t<subscript>s</subscript>}
where
t<subscript>r</subscript>(x,y)
denotes a
tuple of table <classname>R</classname> that consists only of
the components <literal>x</literal> and <literal>y</literal>.
Note that the tuple <literal>t</literal> only consists of the
components <classname>A</classname> and
<classname>B</classname> of relation <classname>R</classname>.
</para>
<para id="divide-example">
Given the following tables
<programlisting>
R A | B | C | D S C | D R A | B | C | D S C | D
---+---+---+--- ---+--- ---+---+---+--- ---+---
a | b | c | d c | d a | b | c | d c | d
...@@ -329,238 +576,359 @@ Given the following tables ...@@ -329,238 +576,359 @@ Given the following tables
e | d | c | d e | d | c | d
e | d | e | f e | d | e | f
a | b | d | e a | b | d | e
\end{verbatim} </programlisting>
$R \div S$ is derived as
\begin{verbatim} R &divide; S
is derived as
<programlisting>
A | B A | B
---+--- ---+---
a | b a | b
e | d e | d
\end{verbatim} </programlisting>
\end{example} </para>
\end{itemize} </listitem>
% </itemizedlist>
For a more detailed description and definition of the relational </para>
algebra refer to \cite{ullman} or \cite{date86}.
<para>
\begin{example} For a more detailed description and definition of the relational
\label{suppl_rel_alg} algebra refer to <citetitle>ullman</citetitle> or
Recall that we formulated all those relational operators to be able to <citetitle>date86</citetitle>.
retrieve data from the database. Let's return to our example of </para>
section \ref{operations} where someone wanted to know the names of all
suppliers that sell the part 'Screw'. This question can be answered <para id="suppl-rel-alg">
using relational algebra by the following operation: Recall that we formulated all those relational operators to be able to
\begin{displaymath} retrieve data from the database. Let's return to our example of
\pi_{SUPPLIER.SNAME}(\sigma_{PART.PNAME='Screw'}(SUPPLIER \Join SELLS section <xref linkend="operations" endterm="operations">
\Join PART)) where someone wanted to know the names of all
\end{displaymath} suppliers that sell the part <literal>Screw</literal>.
We call such an operation a query. If we evaluate the above query This question can be answered
against the tables form figure \ref{supplier} {\it The suppliers and using relational algebra by the following operation:
parts database} we will obtain the following result:
\begin{verbatim} &pi;<subscript>SUPPLIER.SNAME</subscript>(&sigma;<subscript>PART.PNAME='Screw'</subscript>(SUPPLIER &prod; SELLS &prod; PART))
</para>
<para>
We call such an operation a query. If we evaluate the above query
against the tables from figure
<xref linkend="supplier-fig" endterm="supplier-fig"> (The suppliers and
parts database) we will obtain the following result:
<programlisting>
SNAME SNAME
------- -------
Smith Smith
Adams Adams
\end{verbatim} </programlisting>
\end{example} </para>
\subsection{Relational Calculus} </sect2>
\label{rel_calc}
The relational calculus is based on the {first order logic}. There are <sect2 id="rel-calc">
two variants of the relational calculus: <title>Relational Calculus</title>
%
\begin{itemize} <para>
\item The {\it Domain Relational Calculus} (DRC), where variables The relational calculus is based on the
stand for components (attributes) of the tuples. <firstterm>first order logic</firstterm>. There are
\item The {\it Tuple Relational Calculus} (TRC), where variables stand two variants of the relational calculus:
for tuples.
\end{itemize} <itemizedlist>
% <listitem>
We want to discuss the tuple relational calculus only because it is <para>
the one underlying the most relational languages. For a detailed The <firstterm>Domain Relational Calculus</firstterm>
discussion on DRC (and also TRC) see \cite{date86} or \cite{ullman}. (<acronym>DRC</acronym>), where variables
stand for components (attributes) of the tuples.
\subsubsection{Tuple Relational Calculus} </para>
The queries used in TRC are of the following form: </listitem>
\begin{displaymath}
\{x(A) \mid F(x)\} <listitem>
\end{displaymath} <para>
where $x$ is a tuple variable $A$ is a set of attributes and $F$ is a The <firstterm>Tuple Relational Calculus</firstterm>
formula. The resulting relation consists of all tuples $t(A)$ that satisfy (<acronym>TRC</acronym>), where variables stand for tuples.
$F(t)$. </para>
\begin{example} </listitem>
If we want to answer the question from example \ref{suppl_rel_alg} </itemizedlist>
using TRC we formulate the following query: </para>
\begin{displaymath}
\begin{array}{lcll} <para>
\{x(SNAME) & \mid & x \in SUPPLIER~\wedge & \nonumber\\ We want to discuss the tuple relational calculus only because it is
& & \exists y \in SELLS\ \exists z \in PART & (y(SNO)=x(SNO)~\wedge \nonumber\\ the one underlying the most relational languages. For a detailed
& & &~ z(PNO)=y(PNO)~\wedge \nonumber\\ discussion on <acronym>DRC</acronym> (and also
& & &~ z(PNAME)='Screw')\} \nonumber <acronym>TRC</acronym>) see <citetitle>date86</citetitle> or
\end{array} <citetitle>ullman</citetitle>.
\end{displaymath} </para>
Evaluating the query against the tables from figure \ref{supplier} </sect2>
{\it The suppliers and parts database} again leads to the same result
as in example \ref{suppl_rel_alg}. <sect2>
\end{example} <title>Tuple Relational Calculus</title>
\subsection{Relational Algebra vs. Relational Calculus} <para>
\label{alg_vs_calc} The queries used in <acronym>TRC</acronym> are of the following
The relational algebra and the relational calculus have the same {\it form:
expressive power} i.e.\ all queries that can be formulated using x(A) &mid; F(x)
relational algebra can also be formulated using the relational
calculus and vice versa. This was first proved by E.~F.~Codd in where <literal>x</literal> is a tuple variable
1972. This proof is based on an algorithm -"Codd's reduction <classname>A</classname> is a set of attributes and <literal>F</literal> is a
algorithm"- by which an arbitrary expression of the relational formula. The resulting relation consists of all tuples
calculus can be reduced to a semantically equivalent expression of <literal>t(A)</literal> that satisfy <literal>F(t)</literal>.
relational algebra. For a more detailed discussion on that refer to </para>
\cite{date86} and
\cite{ullman}. <para>
If we want to answer the question from example
It is sometimes said that languages based on the relational calculus <xref linkend="suppl-rel-alg" endterm="suppl-rel-alg">
are "higher level" or "more declarative" than languages based on using <acronym>TRC</acronym> we formulate the following query:
relational algebra because the algebra (partially) specifies the order
of operations while the calculus leaves it to a compiler or {x(SNAME) &mid; x &isin; SUPPLIER &and; \nonumber
interpreter to determine the most efficient order of evaluation. &exist; y &isin; SELLS &exist; z &isin; PART (y(SNO)=x(SNO) &and; \nonumber
z(PNO)=y(PNO) &and; \nonumber
z(PNAME)='Screw')} \nonumber
\section{The SQL Language} </para>
\label{sqllanguage}
% <para>
As most modern relational languages SQL is based on the tuple Evaluating the query against the tables from figure
relational calculus. As a result every query that can be formulated <xref linkend="supplier-fig" endterm="supplier-fig">
using the tuple relational calculus (or equivalently, relational (The suppliers and parts database)
algebra) can also be formulated using SQL. There are, however, again leads to the same result
capabilities beyond the scope of relational algebra or calculus. Here as in example
is a list of some additional features provided by SQL that are not <xref linkend="suppl-rel-alg" endterm="suppl-rel-alg">.
part of relational algebra or calculus: </para>
\pagebreak </sect2>
%
\begin{itemize} <sect2 id="alg-vs-calc">
\item Commands for insertion, deletion or modification of data. <title>Relational Algebra vs. Relational Calculus</title>
\item Arithmetic capability: In SQL it is possible to involve
arithmetic operations as well as comparisons, e.g. $A < B + 3$. Note <para>
that $+$ or other arithmetic operators appear neither in relational The relational algebra and the relational calculus have the same
algebra nor in relational calculus. <firstterm>expressive power</firstterm>; i.e. all queries that
\item Assignment and Print Commands: It is possible to print a can be formulated using relational algebra can also be formulated
relation constructed by a query and to assign a computed relation to a using the relational calculus and vice versa.
relation name. This was first proved by E. F. Codd in
\item Aggregate Functions: Operations such as {\it average}, {\it 1972. This proof is based on an algorithm (<quote>Codd's reduction
sum}, {\it max}, \ldots can be applied to columns of a relation to algorithm</quote>) by which an arbitrary expression of the relational
obtain a single quantity. calculus can be reduced to a semantically equivalent expression of
\end{itemize} relational algebra. For a more detailed discussion on that refer to
% <citetitle>date86</citetitle> and
\subsection{Select} <citetitle>ullman</citetitle>.
\label{select} </para>
The most often used command in SQL is the SELECT statement that is
used to retrieve data. The syntax is: <para>
\begin{verbatim} It is sometimes said that languages based on the relational calculus
are "higher level" or "more declarative" than languages based on
relational algebra because the algebra (partially) specifies the order
of operations while the calculus leaves it to a compiler or
interpreter to determine the most efficient order of evaluation.
</para>
</sect2>
</sect1>
<sect1 id="sql-language">
<title>The <acronym>SQL</acronym> Language</title>
<para>
As most modern relational languages <acronym>SQL</acronym> is based on the tuple
relational calculus. As a result every query that can be formulated
using the tuple relational calculus (or equivalently, relational
algebra) can also be formulated using <acronym>SQL</acronym>. There are, however,
capabilities beyond the scope of relational algebra or calculus. Here
is a list of some additional features provided by <acronym>SQL</acronym> that are not
part of relational algebra or calculus:
<itemizedlist>
<listitem>
<para>
Commands for insertion, deletion or modification of data.
</para>
</listitem>
<listitem>
<para>
Arithmetic capability: In <acronym>SQL</acronym> it is possible to involve
arithmetic operations as well as comparisons, e.g.
A &lt; B + 3.
Note
that + or other arithmetic operators appear neither in relational
algebra nor in relational calculus.
</para>
</listitem>
<listitem>
<para>
Assignment and Print Commands: It is possible to print a
relation constructed by a query and to assign a computed relation to a
relation name.
</para>
</listitem>
<listitem>
<para>
Aggregate Functions: Operations such as
<firstterm>average</firstterm>, <firstterm>sum</firstterm>,
<firstterm>max</firstterm>, etc. can be applied to columns of a relation to
obtain a single quantity.
</para>
</listitem>
</itemizedlist>
</para>
<sect2 id="select">
<title>Select</title>
<para>
The most often used command in <acronym>SQL</acronym> is the
SELECT statement,
used to retrieve data. The syntax is:
<synopsis>
SELECT [ALL|DISTINCT] SELECT [ALL|DISTINCT]
{ * | <expr_1> [AS <c_alias_1>] [, ... { * | <replaceable class="parameter">expr_1</replaceable> [AS <replaceable class="parameter">c_alias_1</replaceable>] [, ...
[, <expr_k> [AS <c_alias_k>]]]} [, <replaceable class="parameter">expr_k</replaceable> [AS <replaceable class="parameter">c_alias_k</replaceable>]]]}
FROM <table_name_1> [t_alias_1] FROM <replaceable class="parameter">table_name_1</replaceable> [<replaceable class="parameter">t_alias_1</replaceable>]
[, ... [, <table_name_n> [t_alias_n]]] [, ... [, <replaceable class="parameter">table_name_n</replaceable> [<replaceable class="parameter">t_alias_n</replaceable>]]]
[WHERE condition] [WHERE <replaceable class="parameter">condition</replaceable>]
[GROUP BY <name_of_attr_i> [GROUP BY <replaceable class="parameter">name_of_attr_i</replaceable>
[,... [, <name_of_attr_j>]] [HAVING condition]] [,... [, <replaceable class="parameter">name_of_attr_j</replaceable>]] [HAVING <replaceable class="parameter">condition</replaceable>]]
[{UNION [ALL] | INTERSECT | EXCEPT} SELECT ...] [{UNION [ALL] | INTERSECT | EXCEPT} SELECT ...]
[ORDER BY <name_of_attr_i> [ASC|DESC] [ORDER BY <replaceable class="parameter">name_of_attr_i</replaceable> [ASC|DESC]
[, ... [, <name_of_attr_j> [ASC|DESC]]]]; [, ... [, <replaceable class="parameter">name_of_attr_j</replaceable> [ASC|DESC]]]];
\end{verbatim} </synopsis>
Now we will illustrate the complex syntax of the SELECT statement </para>
with various examples. The tables used for the examples are defined in
figure \ref{supplier} {\it The suppliers and parts database}. <para>
% Now we will illustrate the complex syntax of the SELECT statement
\subsubsection{Simple Selects} with various examples. The tables used for the examples are defined in
\begin{example} figure <xref linkend="supplier-fig" endterm="supplier-fig"> (The suppliers and parts database).
Here are some simple examples using a SELECT statement: \\ </para>
\\
To retrieve all tuples from table PART where the attribute PRICE is <sect3>
greater than 10 we formulate the following query <title>Simple Selects</title>
\begin{verbatim}
SELECT * <para>
FROM PART Here are some simple examples using a SELECT statement:
<example>
<title>Simple Query with Qualification</title>
<para>
To retrieve all tuples from table PART where the attribute PRICE is
greater than 10 we formulate the following query:
<programlisting>
SELECT * FROM PART
WHERE PRICE > 10; WHERE PRICE > 10;
\end{verbatim} </programlisting>
and get the table:
\begin{verbatim} and get the table:
<programlisting>
PNO | PNAME | PRICE PNO | PNAME | PRICE
-----+---------+-------- -----+---------+--------
3 | Bolt | 15 3 | Bolt | 15
4 | Cam | 25 4 | Cam | 25
\end{verbatim} </programlisting>
% </para>
Using "$*$" in the SELECT statement will deliver all attributes from
the table. If we want to retrieve only the attributes PNAME and PRICE <para>
from table PART we use the statement: Using "*" in the SELECT statement will deliver all attributes from
\begin{verbatim} the table. If we want to retrieve only the attributes PNAME and PRICE
from table PART we use the statement:
<programlisting>
SELECT PNAME, PRICE SELECT PNAME, PRICE
FROM PART FROM PART
WHERE PRICE > 10; WHERE PRICE > 10;
\end{verbatim} </programlisting>
\pagebreak
\noindent In this case the result is: In this case the result is:
\begin{verbatim}
<programlisting>
PNAME | PRICE PNAME | PRICE
--------+-------- --------+--------
Bolt | 15 Bolt | 15
Cam | 25 Cam | 25
\end{verbatim} </programlisting>
Note that the SQL SELECT corresponds to the "projection" in relational
algebra not to the "selection" (see section \ref{rel_alg} {\it Note that the <acronym>SQL</acronym> SELECT corresponds to the
Relational Algebra}). "projection" in relational algebra not to the "selection"
\\ \\ (see section <xref linkend="rel-alg" endterm="rel-alg">
The qualifications in the WHERE clause can also be logically connected (Relational Algebra).
using the keywords OR, AND and NOT: </para>
\begin{verbatim}
<para>
The qualifications in the WHERE clause can also be logically connected
using the keywords OR, AND, and NOT:
<programlisting>
SELECT PNAME, PRICE SELECT PNAME, PRICE
FROM PART FROM PART
WHERE PNAME = 'Bolt' AND WHERE PNAME = 'Bolt' AND
(PRICE = 0 OR PRICE < 15); (PRICE = 0 OR PRICE < 15);
\end{verbatim} </programlisting>
will lead to the result:
\begin{verbatim} will lead to the result:
<programlisting>
PNAME | PRICE PNAME | PRICE
--------+-------- --------+--------
Bolt | 15 Bolt | 15
\end{verbatim} </programlisting>
Arithmetic operations may be used in the {\it selectlist} and in the WHERE </para>
clause. For example if we want to know how much it would cost if we
take two pieces of a part we could use the following query: <para>
\begin{verbatim} Arithmetic operations may be used in the target list and in the WHERE
clause. For example if we want to know how much it would cost if we
take two pieces of a part we could use the following query:
<programlisting>
SELECT PNAME, PRICE * 2 AS DOUBLE SELECT PNAME, PRICE * 2 AS DOUBLE
FROM PART FROM PART
WHERE PRICE * 2 < 50; WHERE PRICE * 2 < 50;
\end{verbatim} </programlisting>
and we get:
\begin{verbatim} and we get:
<programlisting>
PNAME | DOUBLE PNAME | DOUBLE
--------+--------- --------+---------
Screw | 20 Screw | 20
Nut | 16 Nut | 16
Bolt | 30 Bolt | 30
\end{verbatim} </programlisting>
Note that the word DOUBLE after the keyword AS is the new title of the
second column. This technique can be used for every element of the Note that the word DOUBLE after the keyword AS is the new title of the
{\it selectlist} to assign a new title to the resulting column. This new title second column. This technique can be used for every element of the
is often referred to as alias. The alias cannot be used throughout the target list to assign a new title to the resulting column. This new title
rest of the query. is often referred to as alias. The alias cannot be used throughout the
\end{example} rest of the query.
</para>
\subsubsection{Joins} </example>
\begin{example} The following example shows how {\it joins} are </para>
realized in SQL: \\ \\ </sect3>
To join the three tables SUPPLIER, PART and SELLS over their common
attributes we formulate the following statement: <sect3>
\begin{verbatim} <title>Joins</title>
<para id="simple-join">
The following example shows how <firstterm>joins</firstterm> are
realized in <acronym>SQL</acronym>.
</para>
<para>
To join the three tables SUPPLIER, PART and SELLS over their common
attributes we formulate the following statement:
<programlisting>
SELECT S.SNAME, P.PNAME SELECT S.SNAME, P.PNAME
FROM SUPPLIER S, PART P, SELLS SE FROM SUPPLIER S, PART P, SELLS SE
WHERE S.SNO = SE.SNO AND WHERE S.SNO = SE.SNO AND
P.PNO = SE.PNO; P.PNO = SE.PNO;
\end{verbatim} </programlisting>
\pagebreak
\noindent and get the following table as a result: and get the following table as a result:
\begin{verbatim}
<programlisting>
SNAME | PNAME SNAME | PNAME
-------+------- -------+-------
Smith | Screw Smith | Screw
...@@ -571,90 +939,139 @@ attributes we formulate the following statement: ...@@ -571,90 +939,139 @@ attributes we formulate the following statement:
Blake | Nut Blake | Nut
Blake | Bolt Blake | Bolt
Blake | Cam Blake | Cam
\end{verbatim} </programlisting>
In the FROM clause we introduced an alias name for every relation </para>
because there are common named attributes (SNO and PNO) among the
relations. Now we can distinguish between the common named attributes <para>
by simply prefixing the attribute name with the alias name followed by In the FROM clause we introduced an alias name for every relation
a dot. The join is calculated in the same way as shown in example because there are common named attributes (SNO and PNO) among the
\ref{join_example}. First the Cartesian product $SUPPLIER\times PART relations. Now we can distinguish between the common named attributes
\times SELLS$ is derived. Now only those tuples satisfying the by simply prefixing the attribute name with the alias name followed by
conditions given in the WHERE clause are selected (i.e.\ the common a dot. The join is calculated in the same way as shown in example
named attributes have to be equal). Finally we project out all <xref linkend="join-example" endterm="join-example">.
columns but S.SNAME and P.PNAME. First the Cartesian product
\end{example}
% SUPPLIER &times; PART &times; SELLS
\subsubsection{Aggregate Operators}
SQL provides aggregate operators (e.g. AVG, COUNT, SUM, MIN, MAX) that is derived. Now only those tuples satisfying the
take the name of an attribute as an argument. The value of the conditions given in the WHERE clause are selected (i.e. the common
aggregate operator is calculated over all values of the specified named attributes have to be equal). Finally we project out all
attribute (column) of the whole table. If groups are specified in the columns but S.SNAME and P.PNAME.
query the calculation is done only over the values of a group (see next </para>
section). </sect3>
\begin{example} <sect3>
If we want to know the average cost of all parts in table PART we use <title>Aggregate Operators</title>
the following query:
\begin{verbatim} <para>
<acronym>SQL</acronym> provides aggregate operators
(e.g. AVG, COUNT, SUM, MIN, MAX) that
take the name of an attribute as an argument. The value of the
aggregate operator is calculated over all values of the specified
attribute (column) of the whole table. If groups are specified in the
query the calculation is done only over the values of a group (see next
section).
<example>
<title>Aggregates</title>
<para>
If we want to know the average cost of all parts in table PART we use
the following query:
<programlisting>
SELECT AVG(PRICE) AS AVG_PRICE SELECT AVG(PRICE) AS AVG_PRICE
FROM PART; FROM PART;
\end{verbatim} </programlisting>
The result is: </para>
\begin{verbatim}
<para>
The result is:
<programlisting>
AVG_PRICE AVG_PRICE
----------- -----------
14.5 14.5
\end{verbatim} </programlisting>
If we want to know how many parts are stored in table PART we use </para>
the statement:
\begin{verbatim} <para>
If we want to know how many parts are stored in table PART we use
the statement:
<programlisting>
SELECT COUNT(PNO) SELECT COUNT(PNO)
FROM PART; FROM PART;
\end{verbatim} </programlisting>
and get:
\begin{verbatim} and get:
<programlisting>
COUNT COUNT
------- -------
4 4
\end{verbatim} </programlisting>
\end{example}
</para>
\subsubsection{Aggregation by Groups} </example>
SQL allows to partition the tuples of a table into groups. Then the </para>
aggregate operators described above can be applied to the groups </sect3>
(i.e. the value of the aggregate operator is no longer calculated over
all the values of the specified column but over all values of a <sect3>
group. Thus the aggregate operator is evaluated individually for every <title>Aggregation by Groups</title>
group.)
\\ \\ <para>
The partitioning of the tuples into groups is done by using the <acronym>SQL</acronym> allows one to partition the tuples of a table
keywords \mbox{GROUP BY} followed by a list of attributes that define the into groups. Then the
groups. If we have {\tt GROUP BY $A_{1}, \ldots, A_{k}$} we partition aggregate operators described above can be applied to the groups
the relation into groups, such that two tuples are in the same group (i.e. the value of the aggregate operator is no longer calculated over
if and only if they agree on all the attributes $A_{1}, \ldots, all the values of the specified column but over all values of a
A_{k}$. group. Thus the aggregate operator is evaluated individually for every
\begin{example} group.)
If we want to know how many parts are sold by every supplier we </para>
formulate the query:
\begin{verbatim} <para>
The partitioning of the tuples into groups is done by using the
keywords <command>GROUP BY</command> followed by a list of
attributes that define the
groups. If we have
<command>GROUP BY A<subscript>1</subscript>, &tdot;, A<subscript>k</subscript></command>
we partition
the relation into groups, such that two tuples are in the same group
if and only if they agree on all the attributes
A<subscript>1</subscript>, &tdot;, A<subscript>k</subscript>.
<example>
<title>Aggregates</title>
<para>
If we want to know how many parts are sold by every supplier we
formulate the query:
<programlisting>
SELECT S.SNO, S.SNAME, COUNT(SE.PNO) SELECT S.SNO, S.SNAME, COUNT(SE.PNO)
FROM SUPPLIER S, SELLS SE FROM SUPPLIER S, SELLS SE
WHERE S.SNO = SE.SNO WHERE S.SNO = SE.SNO
GROUP BY S.SNO, S.SNAME; GROUP BY S.SNO, S.SNAME;
\end{verbatim} </programlisting>
and get:
\begin{verbatim} and get:
<programlisting>
SNO | SNAME | COUNT SNO | SNAME | COUNT
-----+-------+------- -----+-------+-------
1 | Smith | 2 1 | Smith | 2
2 | Jones | 1 2 | Jones | 1
3 | Adams | 2 3 | Adams | 2
4 | Blake | 3 4 | Blake | 3
\end{verbatim} </programlisting>
Now let's have a look of what is happening here: \\ </para>
First the join of the
tables SUPPLIER and SELLS is derived: <para>
\begin{verbatim} Now let's have a look of what is happening here.
First the join of the
tables SUPPLIER and SELLS is derived:
<programlisting>
S.SNO | S.SNAME | SE.PNO S.SNO | S.SNAME | SE.PNO
-------+---------+-------- -------+---------+--------
1 | Smith | 1 1 | Smith | 1
...@@ -665,10 +1082,14 @@ tables SUPPLIER and SELLS is derived: ...@@ -665,10 +1082,14 @@ tables SUPPLIER and SELLS is derived:
4 | Blake | 2 4 | Blake | 2
4 | Blake | 3 4 | Blake | 3
4 | Blake | 4 4 | Blake | 4
\end{verbatim} </programlisting>
Next we partition the tuples into groups by putting all tuples </para>
together that agree on both attributes S.SNO and S.SNAME:
\begin{verbatim} <para>
Next we partition the tuples into groups by putting all tuples
together that agree on both attributes S.SNO and S.SNAME:
<programlisting>
S.SNO | S.SNAME | SE.PNO S.SNO | S.SNAME | SE.PNO
-------+---------+-------- -------+---------+--------
1 | Smith | 1 1 | Smith | 1
...@@ -682,101 +1103,153 @@ together that agree on both attributes S.SNO and S.SNAME: ...@@ -682,101 +1103,153 @@ together that agree on both attributes S.SNO and S.SNAME:
4 | Blake | 2 4 | Blake | 2
| 3 | 3
| 4 | 4
\end{verbatim} </programlisting>
In our example we got four groups and now we can apply the aggregate </para>
operator COUNT to every group leading to the total result of the query
given above. <para>
\end{example} In our example we got four groups and now we can apply the aggregate
% operator COUNT to every group leading to the total result of the query
given above.
</para>
</example>
</para>
<para>
Note that for the result of a query using GROUP BY and aggregate Note that for the result of a query using GROUP BY and aggregate
operators to make sense the attributes grouped by must also appear in operators to make sense the attributes grouped by must also appear in
the {\it selectlist}. All further attributes not appearing in the GROUP the target list. All further attributes not appearing in the GROUP
BY clause can only be selected by using an aggregate function. On BY clause can only be selected by using an aggregate function. On
the other hand you can not use aggregate functions on attributes the other hand you can not use aggregate functions on attributes
appearing in the GROUP BY clause. appearing in the GROUP BY clause.
</para>
\subsubsection{Having} </sect3>
The HAVING clause works much like the WHERE clause and is used to <sect3>
consider only those groups satisfying the qualification given in the <title>Having</title>
HAVING clause. The expressions allowed in the HAVING clause must
involve aggregate functions. Every expression using only plain <para>
attributes belongs to the WHERE clause. On the other hand every The HAVING clause works much like the WHERE clause and is used to
expression involving an aggregate function must be put to the HAVING consider only those groups satisfying the qualification given in the
clause. HAVING clause. The expressions allowed in the HAVING clause must
\begin{example} involve aggregate functions. Every expression using only plain
If we want only those suppliers selling more than one part we use the attributes belongs to the WHERE clause. On the other hand every
query: expression involving an aggregate function must be put to the HAVING
\begin{verbatim} clause.
<example>
<title>Having</title>
<para>
If we want only those suppliers selling more than one part we use the
query:
<programlisting>
SELECT S.SNO, S.SNAME, COUNT(SE.PNO) SELECT S.SNO, S.SNAME, COUNT(SE.PNO)
FROM SUPPLIER S, SELLS SE FROM SUPPLIER S, SELLS SE
WHERE S.SNO = SE.SNO WHERE S.SNO = SE.SNO
GROUP BY S.SNO, S.SNAME GROUP BY S.SNO, S.SNAME
HAVING COUNT(SE.PNO) > 1; HAVING COUNT(SE.PNO) > 1;
\end{verbatim} </programlisting>
and get:
\begin{verbatim} and get:
<programlisting>
SNO | SNAME | COUNT SNO | SNAME | COUNT
-----+-------+------- -----+-------+-------
1 | Smith | 2 1 | Smith | 2
3 | Adams | 2 3 | Adams | 2
4 | Blake | 3 4 | Blake | 3
\end{verbatim} </programlisting>
\end{example} </para>
</example>
\subsubsection{Subqueries} </para>
In the WHERE and HAVING clauses the use of subqueries (subselects) is </sect3>
allowed in every place where a value is expected. In this case the
value must be derived by evaluating the subquery first. The usage of <sect3>
subqueries extends the expressive power of SQL. <title>Subqueries</title>
\begin{example}
If we want to know all parts having a greater price than the part <para>
named 'Screw' we use the query: In the WHERE and HAVING clauses the use of subqueries (subselects) is
\begin{verbatim} allowed in every place where a value is expected. In this case the
value must be derived by evaluating the subquery first. The usage of
subqueries extends the expressive power of
<acronym>SQL</acronym>.
<example>
<title>Subselect</title>
<para>
If we want to know all parts having a greater price than the part
named 'Screw' we use the query:
<programlisting>
SELECT * SELECT *
FROM PART FROM PART
WHERE PRICE > (SELECT PRICE FROM PART WHERE PRICE > (SELECT PRICE FROM PART
WHERE PNAME='Screw'); WHERE PNAME='Screw');
\end{verbatim} </programlisting>
The result is: </para>
\begin{verbatim}
<para>
The result is:
<programlisting>
PNO | PNAME | PRICE PNO | PNAME | PRICE
-----+---------+-------- -----+---------+--------
3 | Bolt | 15 3 | Bolt | 15
4 | Cam | 25 4 | Cam | 25
\end{verbatim} </programlisting>
When we look at the above query we can see </para>
the keyword SELECT two times. The first one at the beginning of the
query - we will refer to it as outer SELECT - and the one in the WHERE <para>
clause which begins a nested query - we will refer to it as inner When we look at the above query we can see
SELECT. For every tuple of the outer SELECT the inner SELECT has to be the keyword SELECT two times. The first one at the beginning of the
evaluated. After every evaluation we know the price of the tuple named query - we will refer to it as outer SELECT - and the one in the WHERE
'Screw' and we can check if the price of the actual tuple is clause which begins a nested query - we will refer to it as inner
greater. SELECT. For every tuple of the outer SELECT the inner SELECT has to be
\\ \\ evaluated. After every evaluation we know the price of the tuple named
\noindent If we want to know all suppliers that do not sell any part 'Screw' and we can check if the price of the actual tuple is
(e.g. to be able to remove these suppliers from the database) we use: greater.
\begin{verbatim} </para>
<para>
If we want to know all suppliers that do not sell any part
(e.g. to be able to remove these suppliers from the database) we use:
<programlisting>
SELECT * SELECT *
FROM SUPPLIER S FROM SUPPLIER S
WHERE NOT EXISTS WHERE NOT EXISTS
(SELECT * FROM SELLS SE (SELECT * FROM SELLS SE
WHERE SE.SNO = S.SNO); WHERE SE.SNO = S.SNO);
\end{verbatim} </programlisting>
In our example the result will be empty because every supplier sells </para>
at least one part. Note that we use S.SNO from the outer SELECT within
the WHERE clause of the inner SELECT. As described above the subquery <para>
is evaluated for every tuple from the outer query i.e. the value for In our example the result will be empty because every supplier sells
S.SNO is always taken from the actual tuple of the outer SELECT. at least one part. Note that we use S.SNO from the outer SELECT within
\end{example} the WHERE clause of the inner SELECT. As described above the subquery
is evaluated for every tuple from the outer query i.e. the value for
\subsubsection{Union, Intersect, Except} S.SNO is always taken from the actual tuple of the outer SELECT.
</para>
These operations calculate the union, intersect and set theoretic </example>
difference of the tuples derived by two subqueries: </para>
\begin{example} </sect3>
The following query is an example for UNION:
\begin{verbatim} <sect3>
<title>Union, Intersect, Except</title>
<para>
These operations calculate the union, intersect and set theoretic
difference of the tuples derived by two subqueries.
<example>
<title>Union, Intersect, Except</title>
<para>
The following query is an example for UNION:
<programlisting>
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNAME = 'Jones' WHERE S.SNAME = 'Jones'
...@@ -784,16 +1257,22 @@ The following query is an example for UNION: ...@@ -784,16 +1257,22 @@ The following query is an example for UNION:
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNAME = 'Adams'; WHERE S.SNAME = 'Adams';
\end{verbatim} </programlisting>
gives the result: gives the result:
\begin{verbatim}
<programlisting>
SNO | SNAME | CITY SNO | SNAME | CITY
-----+-------+-------- -----+-------+--------
2 | Jones | Paris 2 | Jones | Paris
3 | Adams | Vienna 3 | Adams | Vienna
\end{verbatim} </programlisting>
Here an example for INTERSECT: </para>
\begin{verbatim}
<para>
Here an example for INTERSECT:
<programlisting>
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNO > 1 WHERE S.SNO > 1
...@@ -801,18 +1280,22 @@ Here an example for INTERSECT: ...@@ -801,18 +1280,22 @@ Here an example for INTERSECT:
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNO > 2; WHERE S.SNO > 2;
\end{verbatim} </programlisting>
gives the result:
\begin{verbatim} gives the result:
<programlisting>
SNO | SNAME | CITY SNO | SNAME | CITY
-----+-------+-------- -----+-------+--------
2 | Jones | Paris 2 | Jones | Paris
\end{verbatim}
The only tuple returned by both parts of the query is the one having $SNO=2$. The only tuple returned by both parts of the query is the one having $SNO=2$.
\pagebreak </programlisting>
</para>
<para>
Finally an example for EXCEPT:
\noindent Finally an example for EXCEPT: <programlisting>
\begin{verbatim}
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNO > 1 WHERE S.SNO > 1
...@@ -820,298 +1303,503 @@ The only tuple returned by both parts of the query is the one having $SNO=2$. ...@@ -820,298 +1303,503 @@ The only tuple returned by both parts of the query is the one having $SNO=2$.
SELECT S.SNO, S.SNAME, S.CITY SELECT S.SNO, S.SNAME, S.CITY
FROM SUPPLIER S FROM SUPPLIER S
WHERE S.SNO > 3; WHERE S.SNO > 3;
\end{verbatim} </programlisting>
gives the result:
\begin{verbatim} gives the result:
<programlisting>
SNO | SNAME | CITY SNO | SNAME | CITY
-----+-------+-------- -----+-------+--------
2 | Jones | Paris 2 | Jones | Paris
3 | Adams | Vienna 3 | Adams | Vienna
\end{verbatim} </programlisting>
\end{example} </para>
% </example>
\subsection{Data Definition} </para>
\label{datadef} </sect3>
% </sect2>
There is a set of commands used for data definition included in the
SQL language. <sect2 id="datadef">
<title>Data Definition</title>
\subsubsection{Create Table}
\label{create} <para>
The most fundamental command for data definition is the There is a set of commands used for data definition included in the
one that creates a new relation (a new table). The syntax of the <acronym>SQL</acronym> language.
CREATE TABLE command is: </para>
%
\begin{verbatim} <sect3 id="create">
CREATE TABLE <table_name> <title>Create Table</title>
(<name_of_attr_1> <type_of_attr_1>
[, <name_of_attr_2> <type_of_attr_2> <para>
The most fundamental command for data definition is the
one that creates a new relation (a new table). The syntax of the
CREATE TABLE command is:
<synopsis>
CREATE TABLE <replaceable class="parameter">table_name</replaceable>
(<replaceable class="parameter">name_of_attr_1</replaceable> <replaceable class="parameter">type_of_attr_1</replaceable>
[, <replaceable class="parameter">name_of_attr_2</replaceable> <replaceable class="parameter">type_of_attr_2</replaceable>
[, ...]]); [, ...]]);
\end{verbatim} </synopsis>
%
\begin{example} <example>
To create the tables defined in figure \ref{supplier} the <title>Table Creation</title>
following SQL statements are used:
\begin{verbatim} <para>
To create the tables defined in figure
<xref linkend="supplier-fig" endterm="supplier-fig"> the
following <acronym>SQL</acronym> statements are used:
<programlisting>
CREATE TABLE SUPPLIER CREATE TABLE SUPPLIER
(SNO INTEGER, (SNO INTEGER,
SNAME VARCHAR(20), SNAME VARCHAR(20),
CITY VARCHAR(20)); CITY VARCHAR(20));
</programlisting>
<programlisting>
CREATE TABLE PART CREATE TABLE PART
(PNO INTEGER, (PNO INTEGER,
PNAME VARCHAR(20), PNAME VARCHAR(20),
PRICE DECIMAL(4 , 2)); PRICE DECIMAL(4 , 2));
\end{verbatim} </programlisting>
\begin{verbatim}
<programlisting>
CREATE TABLE SELLS CREATE TABLE SELLS
(SNO INTEGER, (SNO INTEGER,
PNO INTEGER); PNO INTEGER);
\end{verbatim} </programlisting>
\end{example} </para>
</example>
% </para>
\subsubsection{Data Types in SQL} </sect3>
The following is a list of some data types that are supported by SQL:
\begin{itemize} <sect3>
\item INTEGER: signed fullword binary integer (31 bits precision). <title>Data Types in <acronym>SQL</acronym></title>
\item SMALLINT: signed halfword binary integer (15 bits precision).
\item DECIMAL ($p \lbrack,q\rbrack $): signed packed decimal number of $p$ <para>
digits precision with assumed $q$ of them right to the decimal The following is a list of some data types that are supported by
point. $(15\ge p \ge q \ge 0)$. If $q$ is omitted it is assumed to be 0. <acronym>SQL</acronym>:
\item FLOAT: signed doubleword floating point number.
\item CHAR($n$): fixed length character string of length $n$. <itemizedlist>
\item VARCHAR($n$): varying length character string of maximum length <listitem>
$n$. <para>
\end{itemize} INTEGER: signed fullword binary integer (31 bits precision).
</para>
\subsubsection{Create Index} </listitem>
Indices are used to speed up access to a relation. If a relation $R$
has an index on attribute $A$ then we can retrieve all tuples $t$ <listitem>
having $t(A) = a$ in time roughly proportional to the number of such <para>
tuples $t$ rather than in time proportional to the size of $R$. SMALLINT: signed halfword binary integer (15 bits precision).
</para>
To create an index in SQL the CREATE INDEX command is used. The syntax </listitem>
is:
\begin{verbatim} <listitem>
CREATE INDEX <index_name> <para>
ON <table_name> ( <name_of_attribute> ); DECIMAL (<replaceable class="parameter">p</replaceable>[,<replaceable class="parameter">q</replaceable>]):
\end{verbatim} signed packed decimal number of
% <replaceable class="parameter">p</replaceable>
\begin{example} digits precision with assumed
To create an index named I on attribute SNAME of relation SUPPLIER <replaceable class="parameter">q</replaceable>
we use the following statement: of them right to the decimal point.
\begin{verbatim}
(15 &ge; <replaceable class="parameter">p</replaceable> &ge; <replaceable class="parameter">q</replaceable>q &ge; 0).
If <replaceable class="parameter">q</replaceable>
is omitted it is assumed to be 0.
</para>
</listitem>
<listitem>
<para>
FLOAT: signed doubleword floating point number.
</para>
</listitem>
<listitem>
<para>
CHAR(<replaceable class="parameter">n</replaceable>):
fixed length character string of length
<replaceable class="parameter">n</replaceable>.
</para>
</listitem>
<listitem>
<para>
VARCHAR(<replaceable class="parameter">n</replaceable>):
varying length character string of maximum length
<replaceable class="parameter">n</replaceable>.
</para>
</listitem>
</itemizedlist>
</para>
</sect3>
<sect3>
<title>Create Index</title>
<para>
Indices are used to speed up access to a relation. If a relation <classname>R</classname>
has an index on attribute <classname>A</classname> then we can
retrieve all tuples <replaceable>t</replaceable>
having
<replaceable>t</replaceable>(<classname>A</classname>) = <replaceable>a</replaceable>
in time roughly proportional to the number of such
tuples <replaceable>t</replaceable>
rather than in time proportional to the size of <classname>R</classname>.
</para>
<para>
To create an index in <acronym>SQL</acronym>
the CREATE INDEX command is used. The syntax is:
<programlisting>
CREATE INDEX <replaceable class="parameter">index_name</replaceable>
ON <replaceable class="parameter">table_name</replaceable> ( <replaceable class="parameter">name_of_attribute</replaceable> );
</programlisting>
</para>
<para>
<example>
<title>Create Index</title>
<para>
To create an index named I on attribute SNAME of relation SUPPLIER
we use the following statement:
<programlisting>
CREATE INDEX I CREATE INDEX I
ON SUPPLIER (SNAME); ON SUPPLIER (SNAME);
\end{verbatim} </programlisting>
\end{example} </para>
%
The created index is maintained automatically, i.e.\ whenever a new tuple <para>
is inserted into the relation SUPPLIER the index I is adapted. Note The created index is maintained automatically, i.e. whenever a new tuple
that the only changes a user can percept when an index is present is inserted into the relation SUPPLIER the index I is adapted. Note
are an increased speed. that the only changes a user can percept when an index is present
are an increased speed.
\subsubsection{Create View} </para>
A view may be regarded as a {\it virtual table}, i.e.\ a table that </example>
does not {\it physically} exist in the database but looks to the user </para>
as if it did. By contrast, when we talk of a {\it base table} there is </sect3>
really a physically stored counterpart of each row of the table
somewhere in the physical storage. <sect3>
<title>Create View</title>
Views do not have their own, physically separate, distinguishable
stored data. Instead, the system stores the {\it definition} of the <para>
view (i.e.\ the rules about how to access physically stored {\it base A view may be regarded as a <firstterm>virtual table</firstterm>,
tables} in order to materialize the view) somewhere in the {\it system i.e. a table that
catalogs} (see section \ref{catalogs} {\it System Catalogs}). For a does not <emphasis>physically</emphasis> exist in the database but looks to the user
discussion on different techniques to implement views refer to section as if it does. By contrast, when we talk of a <firstterm>base table</firstterm> there is
\ref{view_impl} {\it Techniques To Implement Views}. really a physically stored counterpart of each row of the table
somewhere in the physical storage.
In SQL the CREATE VIEW command is used to define a view. The syntax </para>
is:
\begin{verbatim} <para>
CREATE VIEW <view_name> Views do not have their own, physically separate, distinguishable
AS <select_stmt> stored data. Instead, the system stores the definition of the
\end{verbatim} view (i.e. the rules about how to access physically stored base
where {\tt $<$select\_stmt$>$ } is a valid select statement as defined tables in order to materialize the view) somewhere in the system
in section \ref{select}. Note that the {\tt $<$select\_stmt$>$ } is catalogs (see section <xref linkend="catalogs" endterm="catalogs">). For a
not executed when the view is created. It is just stored in the {\it discussion on different techniques to implement views refer to
system catalogs} and is executed whenever a query against the view is <!--
made. section
\begin{example} Let the following view definition be given (we use <xref linkend="view-impl" endterm="view-impl">.
the tables from figure \ref{supplier} {\it The suppliers and parts -->
database} again): <citetitle>SIM98</citetitle>.
\begin{verbatim} </para>
<para>
In <acronym>SQL</acronym> the <command>CREATE VIEW</command>
command is used to define a view. The syntax
is:
<programlisting>
CREATE VIEW <replaceable class="parameter">view_name</replaceable>
AS <replaceable class="parameter">select_stmt</replaceable>
</programlisting>
where <replaceable class="parameter">select_stmt</replaceable>
is a valid select statement as defined
in section <xref linkend="select" endterm="select">.
Note that <replaceable class="parameter">select_stmt</replaceable> is
not executed when the view is created. It is just stored in the
<firstterm>system catalogs</firstterm>
and is executed whenever a query against the view is made.
</para>
<para>
Let the following view definition be given (we use
the tables from figure <xref linkend="supplier-fig" endterm="supplier-fig"> again):
<programlisting>
CREATE VIEW London_Suppliers CREATE VIEW London_Suppliers
AS SELECT S.SNAME, P.PNAME AS SELECT S.SNAME, P.PNAME
FROM SUPPLIER S, PART P, SELLS SE FROM SUPPLIER S, PART P, SELLS SE
WHERE S.SNO = SE.SNO AND WHERE S.SNO = SE.SNO AND
P.PNO = SE.PNO AND P.PNO = SE.PNO AND
S.CITY = 'London'; S.CITY = 'London';
\end{verbatim} </programlisting>
Now we can use this {\it virtual relation} {\tt London\_Suppliers} as </para>
if it were another base table:
\begin{verbatim} <para>
Now we can use this <firstterm>virtual relation</firstterm>
<classname>London_Suppliers</classname> as
if it were another base table:
<programlisting>
SELECT * SELECT *
FROM London_Suppliers FROM London_Suppliers
WHERE P.PNAME = 'Screw'; WHERE P.PNAME = 'Screw';
\end{verbatim} </programlisting>
will return the following table:
\begin{verbatim} which will return the following table:
<programlisting>
SNAME | PNAME SNAME | PNAME
-------+------- -------+-------
Smith | Screw Smith | Screw
\end{verbatim} </programlisting>
To calculate this result the database system has to do a {\it hidden} </para>
access to the base tables SUPPLIER, SELLS and PART first. It
does so by executing the query given in the view definition against <para>
those base tables. After that the additional qualifications (given in the To calculate this result the database system has to do a
query against the view) can be applied to obtain the resulting table. <emphasis>hidden</emphasis>
\end{example} access to the base tables SUPPLIER, SELLS and PART first. It
does so by executing the query given in the view definition against
\subsubsection{Drop Table, Drop Index, Drop View} those base tables. After that the additional qualifications (given in the
To destroy a table (including all tuples stored in that table) the query against the view) can be applied to obtain the resulting
DROP TABLE command is used: table.
\begin{verbatim} </para>
DROP TABLE <table_name>; </sect3>
\end{verbatim}
% <sect3>
\begin{example} <title>Drop Table, Drop Index, Drop View</title>
To destroy the SUPPLIER table use the following statement:
\begin{verbatim} <para>
To destroy a table (including all tuples stored in that table) the
DROP TABLE command is used:
<programlisting>
DROP TABLE <replaceable class="parameter">table_name</replaceable>;
</programlisting>
</para>
<para>
To destroy the SUPPLIER table use the following statement:
<programlisting>
DROP TABLE SUPPLIER; DROP TABLE SUPPLIER;
\end{verbatim} </programlisting>
\end{example} </para>
%
The DROP INDEX command is used to destroy an index: <para>
\begin{verbatim} The DROP INDEX command is used to destroy an index:
DROP INDEX <index_name>;
\end{verbatim} <programlisting>
% DROP INDEX <replaceable class="parameter">index_name</replaceable>;
Finally to destroy a given view use the command DROP VIEW: </programlisting>
\begin{verbatim} </para>
DROP VIEW <view_name>;
\end{verbatim} <para>
Finally to destroy a given view use the command DROP VIEW:
\subsection{Data Manipulation}
% <programlisting>
\subsubsection{Insert Into} DROP VIEW <replaceable class="parameter">view_name</replaceable>;
Once a table is created (see section \ref{create}), it can be filled </programlisting>
with tuples using the command INSERT INTO. The syntax is: </para>
\begin{verbatim} </sect3>
INSERT INTO <table_name> (<name_of_attr_1> </sect2>
[, <name_of_attr_2> [,...]])
VALUES (<val_attr_1> <sect2>
[, <val_attr_2> [, ...]]); <title>Data Manipulation</title>
\end{verbatim}
% <sect3>
\begin{example} <title>Insert Into</title>
To insert the first tuple into the relation SUPPLIER of figure
\ref{supplier} {\it The suppliers and parts database} we use the <para>
following statement: Once a table is created (see
\begin{verbatim} <xref linkend="create" endterm="create">), it can be filled
with tuples using the command <command>INSERT INTO</command>.
The syntax is:
<programlisting>
INSERT INTO <replaceable class="parameter">table_name</replaceable> (<replaceable class="parameter">name_of_attr_1</replaceable>
[, <replaceable class="parameter">name_of_attr_2</replaceable> [,...]])
VALUES (<replaceable class="parameter">val_attr_1</replaceable>
[, <replaceable class="parameter">val_attr_2</replaceable> [, ...]]);
</programlisting>
</para>
<para>
To insert the first tuple into the relation SUPPLIER of figure
<xref linkend="supplier-fig" endterm="supplier-fig"> we use the
following statement:
<programlisting>
INSERT INTO SUPPLIER (SNO, SNAME, CITY) INSERT INTO SUPPLIER (SNO, SNAME, CITY)
VALUES (1, 'Smith', 'London'); VALUES (1, 'Smith', 'London');
\end{verbatim} </programlisting>
% </para>
To insert the first tuple into the relation SELLS we use:
\begin{verbatim} <para>
To insert the first tuple into the relation SELLS we use:
<programlisting>
INSERT INTO SELLS (SNO, PNO) INSERT INTO SELLS (SNO, PNO)
VALUES (1, 1); VALUES (1, 1);
\end{verbatim} </programlisting>
\end{example} </para>
</sect3>
\subsubsection{Update}
To change one or more attribute values of tuples in a relation the <sect3>
UPDATE command is used. The syntax is: <title>Update</title>
\begin{verbatim}
UPDATE <table_name> <para>
SET <name_of_attr_1> = <value_1> To change one or more attribute values of tuples in a relation the
[, ... [, <name_of_attr_k> = <value_k>]] UPDATE command is used. The syntax is:
WHERE <condition>;
\end{verbatim} <programlisting>
% UPDATE <replaceable class="parameter">table_name</replaceable>
\begin{example} SET <replaceable class="parameter">name_of_attr_1</replaceable> = <replaceable class="parameter">value_1</replaceable>
To change the value of attribute PRICE of the part 'Screw' in the [, ... [, <replaceable class="parameter">name_of_attr_k</replaceable> = <replaceable class="parameter">value_k</replaceable>]]
relation PART we use: WHERE <replaceable class="parameter">condition</replaceable>;
\begin{verbatim} </programlisting>
</para>
<para>
To change the value of attribute PRICE of the part 'Screw' in the
relation PART we use:
<programlisting>
UPDATE PART UPDATE PART
SET PRICE = 15 SET PRICE = 15
WHERE PNAME = 'Screw'; WHERE PNAME = 'Screw';
\end{verbatim} </programlisting>
The new value of attribute PRICE of the tuple whose name is 'Screw' is </para>
now 15.
\end{example} <para>
The new value of attribute PRICE of the tuple whose name is 'Screw' is
\subsubsection{Delete} now 15.
To delete a tuple from a particular table use the command DELETE </para>
FROM. The syntax is: </sect3>
\begin{verbatim}
DELETE FROM <table_name> <sect3>
WHERE <condition>; <title>Delete</title>
\end{verbatim}
\begin{example} <para>
To delete the supplier called 'Smith' of the table SUPPLIER the To delete a tuple from a particular table use the command DELETE
following statement is used: FROM. The syntax is:
\begin{verbatim}
<programlisting>
DELETE FROM <replaceable class="parameter">table_name</replaceable>
WHERE <replaceable class="parameter">condition</replaceable>;
</programlisting>
</para>
<para>
To delete the supplier called 'Smith' of the table SUPPLIER the
following statement is used:
<programlisting>
DELETE FROM SUPPLIER DELETE FROM SUPPLIER
WHERE SNAME = 'Smith'; WHERE SNAME = 'Smith';
\end{verbatim} </programlisting>
\end{example} </para>
% </sect3>
\subsection{System Catalogs} </sect2>
\label{catalogs}
In every SQL database system {\it system catalogs} are used to keep <sect2 id="catalogs">
track of which tables, views indexes etc. are defined in the <title>System Catalogs</title>
database. These system catalogs can be queried as if they were normal
relations. For example there is one catalog used for the definition of <para>
views. This catalog stores the query from the view definition. Whenever In every <acronym>SQL</acronym> database system
a query against a view is made, the system first gets the {\it <firstterm>system catalogs</firstterm> are used to keep
view-definition-query} out of the catalog and materializes the view track of which tables, views indexes etc. are defined in the
before proceeding with the user query (see section \ref{view_impl} database. These system catalogs can be queried as if they were normal
{\it Techniques To Implement Views} for a more detailed relations. For example there is one catalog used for the definition of
description). For more information about {\it system catalogs} refer to views. This catalog stores the query from the view definition. Whenever
\cite{date}. a query against a view is made, the system first gets the
<firstterm>view definition query</firstterm> out of the catalog
\subsection{Embedded SQL} and materializes the view
before proceeding with the user query (see
In this section we will sketch how SQL can be embedded into a host <!--
language (e.g.\ C). There are two main reasons why we want to use SQL section
from a host language: <xref linkend="view-impl" endterm="view-impl">.
% -->
\begin{itemize} <citetitle>SIM98</citetitle>
\item There are queries that cannot be formulated using pure SQL for a more detailed
(i.e. recursive queries). To be able to perform such queries we need a description). For more information about system catalogs refer to
host language with a greater expressive power than SQL. <citetitle>DATE</citetitle>.
\item We simply want to access a database from some application that </para>
is written in the host language (e.g.\ a ticket reservation system </sect2>
with a graphical user interface is written in C and the information
about which tickets are still left is stored in a database that can be <sect2>
accessed using embedded SQL). <title>Embedded <acronym>SQL</acronym></title>
\end{itemize}
% <para>
A program using embedded SQL in a host language consists of statements In this section we will sketch how <acronym>SQL</acronym> can be
of the host language and of embedded SQL (ESQL) statements. Every ESQL embedded into a host language (e.g. <literal>C</literal>).
statement begins with the keywords EXEC SQL. The ESQL statements are There are two main reasons why we want to use <acronym>SQL</acronym>
transformed to statements of the host language by a {\it precompiler} from a host language:
(mostly calls to library routines that perform the various SQL
commands). <itemizedlist>
<listitem>
When we look at the examples throughout section \ref{select} we <para>
realize that the result of the queries is very often a set of There are queries that cannot be formulated using pure <acronym>SQL</acronym>
tuples. Most host languages are not designed to operate on sets so we (i.e. recursive queries). To be able to perform such queries we need a
need a mechanism to access every single tuple of the set of tuples host language with a greater expressive power than
returned by a SELECT statement. This mechanism can be provided by <acronym>SQL</acronym>.
declaring a {\it cursor}. After that we can use the FETCH command to </para>
retrieve a tuple and set the cursor to the next tuple. </listitem>
\\ \\
For a detailed discussion on embedded SQL refer to \cite{date}, <listitem>
\cite{date86} or \cite{ullman}. <para>
We simply want to access a database from some application that
is written in the host language (e.g. a ticket reservation system
with a graphical user interface is written in C and the information
about which tickets are still left is stored in a database that can be
accessed using embedded <acronym>SQL</acronym>).
</para>
</listitem>
</itemizedlist>
</para>
<para>
A program using embedded <acronym>SQL</acronym> in a host language consists of statements
of the host language and of embedded <acronym>SQL</acronym> (ESQL) statements. Every ESQL
statement begins with the keywords EXEC SQL. The ESQL statements are
transformed to statements of the host language by a <firstterm>precompiler</firstterm>
(which usually inserts
calls to library routines that perform the various <acronym>SQL</acronym>
commands).
</para>
<para>
When we look at the examples throughout section
<xref linkend="select" endterm="select"> we
realize that the result of the queries is very often a set of
tuples. Most host languages are not designed to operate on sets so we
need a mechanism to access every single tuple of the set of tuples
returned by a SELECT statement. This mechanism can be provided by
declaring a <firstterm>cursor</firstterm>.
After that we can use the FETCH command to
retrieve a tuple and set the cursor to the next tuple.
</para>
<para>
For a detailed discussion on embedded <acronym>SQL</acronym>
refer to <citetitle>date</citetitle>,
<citetitle>date86</citetitle> or <citetitle>ullman</citetitle>.
</para>
</sect2>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file <!-- Keep this comment at the end of the file
Local variables: Local variables:
mode: sgml mode: sgml
sgml-omittag:f sgml-omittag:nil
sgml-shorttag:t sgml-shorttag:t
sgml-minimize-attributes:nil sgml-minimize-attributes:nil
sgml-always-quote-attributes:t sgml-always-quote-attributes:t
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment