Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
P
Postgres FD Implementation
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Abuhujair Javed
Postgres FD Implementation
Commits
f0c66e53
Commit
f0c66e53
authored
Feb 15, 2000
by
Thomas G. Lockhart
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Fix extraneous ending tag on libpq.sgml.
Renormalize query.sgml and fix indenting.
parent
a344a6e7
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
187 additions
and
185 deletions
+187
-185
doc/src/sgml/libpq.sgml
doc/src/sgml/libpq.sgml
+0
-1
doc/src/sgml/query.sgml
doc/src/sgml/query.sgml
+187
-184
No files found.
doc/src/sgml/libpq.sgml
View file @
f0c66e53
...
@@ -1068,7 +1068,6 @@ function is no longer actively supported.
...
@@ -1068,7 +1068,6 @@ function is no longer actively supported.
</para>
</para>
</listitem>
</listitem>
</listitem>
<listitem>
<listitem>
<para>
<para>
<function>PQclear</function>
<function>PQclear</function>
...
...
doc/src/sgml/query.sgml
View file @
f0c66e53
<
Chapter ID
="query">
<
chapter id
="query">
<
TITLE>The Query Language</TITLE
>
<
title>The Query Language</title
>
<
P
ara>
<
p
ara>
The <
ProductName>Postgres</ProductN
ame> query language is a variant of
The <
productname>Postgres</productn
ame> query language is a variant of
the <
Acronym>SQL3</A
cronym> draft next-generation standard. It
the <
acronym>SQL3</a
cronym> draft next-generation standard. It
has many extensions such as an extensible type system,
has many extensions such as an extensible type system,
inheritance, functions and production rules. These are
inheritance, functions and production rules. These are
features carried over from the original <
ProductName>Postgres</ProductN
ame> query
features carried over from the original <
productname>Postgres</productn
ame> query
language, <
ProductName>PostQuel</ProductN
ame>. This section provides an overview
language, <
productname>PostQuel</productn
ame>. This section provides an overview
of how to use <
ProductName>Postgres</ProductN
ame>
of how to use <
productname>Postgres</productn
ame>
<
Acronym>SQL</A
cronym> to perform simple operations.
<
acronym>SQL</a
cronym> to perform simple operations.
This manual is only intended to give you an idea of our
This manual is only intended to give you an idea of our
flavor of <
Acronym>SQL</A
cronym> and is in no way a complete tutorial on
flavor of <
acronym>SQL</a
cronym> and is in no way a complete tutorial on
<
Acronym>SQL</A
cronym>. Numerous books have been written on
<
acronym>SQL</a
cronym>. Numerous books have been written on
<
Acronym>SQL</A
cronym>, including
<
acronym>SQL</a
cronym>, including
<!--
<!--
<XRef LinkEnd="MELT93"> and <XRef LinkEnd="DATE97">.
<XRef LinkEnd="MELT93"> and <XRef LinkEnd="DATE97">.
-->
-->
[MELT93] and [DATE97].
[MELT93] and [DATE97].
You should be aware that some language features
You should be aware that some language features
are extensions to the <
Acronym>ANSI</A
cronym> standard.
are extensions to the <
acronym>ANSI</a
cronym> standard.
</
P
ara>
</
p
ara>
<
S
ect1>
<
s
ect1>
<
Title>Interactive Monitor</T
itle>
<
title>Interactive Monitor</t
itle>
<
P
ara>
<
p
ara>
In the examples that follow, we assume that you have
In the examples that follow, we assume that you have
created the mydb database as described in the previous
created the mydb database as described in the previous
subsection and have started <
Application>psql</A
pplication>.
subsection and have started <
application>psql</a
pplication>.
Examples in this manual can also be found in
Examples in this manual can also be found in
<
FileName>/usr/local/pgsql/src/tutorial/</FileN
ame>. Refer to the
<
filename>/usr/local/pgsql/src/tutorial/</filen
ame>. Refer to the
<
FileName>README</FileN
ame> file in that directory for how to use them. To
<
filename>README</filen
ame> file in that directory for how to use them. To
start the tutorial, do the following:
start the tutorial, do the following:
<
ProgramL
isting>
<
programl
isting>
% cd /usr/local/pgsql/src/tutorial
% cd /usr/local/pgsql/src/tutorial
% psql -s mydb
% psql -s mydb
Welcome to the POSTGRESQL interactive sql monitor:
Welcome to the POSTGRESQL interactive sql monitor:
...
@@ -46,55 +46,56 @@ Welcome to the POSTGRESQL interactive sql monitor:
...
@@ -46,55 +46,56 @@ Welcome to the POSTGRESQL interactive sql monitor:
You are currently connected to the database: postgres
You are currently connected to the database: postgres
mydb=> \i basics.sql
mydb=> \i basics.sql
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
The <
Literal>\i</L
iteral> command read in queries from the specified
The <
literal>\i</l
iteral> command read in queries from the specified
files. The <
Literal>-s</L
iteral> option puts you in single step mode which
files. The <
literal>-s</l
iteral> option puts you in single step mode which
pauses before sending a query to the backend. Queries
pauses before sending a query to the backend. Queries
in this section are in the file <
FileName>basics.sql</FileN
ame>.
in this section are in the file <
filename>basics.sql</filen
ame>.
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
<
Application>psql</A
pplication>
<
application>psql</a
pplication>
has a variety of <
Literal>\d</L
iteral> commands for showing system information.
has a variety of <
literal>\d</l
iteral> commands for showing system information.
Consult these commands for more details;
Consult these commands for more details;
for a listing, type <
Literal>\?</Literal> at the <Application>psql</A
pplication> prompt.
for a listing, type <
literal>\?</literal> at the <application>psql</a
pplication> prompt.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Concepts</T
itle>
<
title>Concepts</t
itle>
<
P
ara>
<
p
ara>
The fundamental notion in <
ProductName>Postgres</ProductN
ame> is that of a class,
The fundamental notion in <
productname>Postgres</productn
ame> is that of a class,
which is a named collection of object instances. Each
which is a named collection of object instances. Each
instance has the same collection of named attributes,
instance has the same collection of named attributes,
and each attribute is of a specific type. Furthermore,
and each attribute is of a specific type. Furthermore,
each instance has a permanent <
FirstTerm>object identifier</FirstT
erm>
each instance has a permanent <
firstterm>object identifier</firstt
erm>
(<
Acronym>OID</A
cronym>)
(<
acronym>OID</a
cronym>)
that is unique throughout the installation. Because
that is unique throughout the installation. Because
<Acronym>SQL</Acronym> syntax refers to tables, we will use the terms
<acronym>SQL</acronym> syntax refers to tables, we will use the terms
<FirstTerm>table</FirstTerm> and <FirstTerm>class</FirstTerm> interchangeably.
<firstterm>table</firstterm> and <firstterm>class</firstterm> interchangeably.
Likewise, an <Acronym>SQL</Acronym> <FirstTerm>row</FirstTerm> is an
Likewise, an <acronym>SQL</acronym> <firstterm>row</firstterm> is an
<FirstTerm>instance</FirstTerm> and <Acronym>SQL</Acronym> <FirstTerm>columns</FirstTerm>
<firstterm>instance</firstterm> and <acronym>SQL</acronym>
are <FirstTerm>attributes</FirstTerm>.
<firstterm>columns</firstterm>
are <firstterm>attributes</firstterm>.
As previously discussed, classes are grouped into
As previously discussed, classes are grouped into
databases, and a collection of databases managed by a
databases, and a collection of databases managed by a
single <
Application>postmaster</A
pplication> process constitutes an installation
single <
application>postmaster</a
pplication> process constitutes an installation
or site.
or site.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Creating a New Class</T
itle>
<
title>Creating a New Class</t
itle>
<
P
ara>
<
p
ara>
You can create a new class by specifying the class
You can create a new class by specifying the class
name, along with all attribute names and their types:
name, along with all attribute names and their types:
<
ProgramL
isting>
<
programl
isting>
CREATE TABLE weather (
CREATE TABLE weather (
city varchar(80),
city varchar(80),
temp_lo int, -- low temperature
temp_lo int, -- low temperature
...
@@ -102,79 +103,81 @@ CREATE TABLE weather (
...
@@ -102,79 +103,81 @@ CREATE TABLE weather (
prcp real, -- precipitation
prcp real, -- precipitation
date date
date date
);
);
</
ProgramL
isting>
</
programl
isting>
</para>
</para>
<
P
ara>
<
p
ara>
Note that both keywords and identifiers are case-insensitive; identifiers can become
Note that both keywords and identifiers are case-insensitive; identifiers can become
case-sensitive by surrounding them with double-quotes as allowed
case-sensitive by surrounding them with double-quotes as allowed
by <Acronym>SQL92</Acronym>.
by <acronym>SQL92</acronym>.
<ProductName>Postgres</ProductName> <Acronym>SQL</Acronym> supports the usual
<productname>Postgres</productname> <acronym>SQL</acronym> supports the usual
<Acronym>SQL</Acronym> types <Type>int</Type>,
<acronym>SQL</acronym> types <type>int</type>,
<Type>float</Type>, <Type>real</Type>, <Type>smallint</Type>, <Type>char(N)</Type>,
<type>float</type>, <type>real</type>, <type>smallint</type>,
<Type>varchar(N)</Type>, <Type>date</Type>, <Type>time</Type>,
<type>char(N)</type>,
and <Type>timestamp</Type>, as well as other types of general utility and
<type>varchar(N)</type>, <type>date</type>, <type>time</type>,
and <type>timestamp</type>, as well as other types of general utility and
a rich set of geometric types. As we will
a rich set of geometric types. As we will
see later, <
ProductName>Postgres</ProductN
ame> can be customized with an
see later, <
productname>Postgres</productn
ame> can be customized with an
arbitrary number of
arbitrary number of
user-defined data types. Consequently, type names are
user-defined data types. Consequently, type names are
not syntactical keywords, except where required to support special
not syntactical keywords, except where required to support special
cases in the <
Acronym>SQL92</A
cronym> standard.
cases in the <
acronym>SQL92</a
cronym> standard.
So far, the <
ProductName>Postgres</ProductName> create
command
So far, the <
productname>Postgres</productname> <command>CREATE</command>
command
looks exactly like
looks exactly like
the command used to create a table in a traditional
the command used to create a table in a traditional
relational system. However, we will presently see that
relational system. However, we will presently see that
classes have properties that are extensions of the
classes have properties that are extensions of the
relational model.
relational model.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Populating a Class with Instances</T
itle>
<
title>Populating a Class with Instances</t
itle>
<
P
ara>
<
p
ara>
The <
Command>insert</C
ommand> statement is used to populate a class with
The <
command>insert</c
ommand> statement is used to populate a class with
instances:
instances:
<
ProgramL
isting>
<
programl
isting>
INSERT INTO weather
INSERT INTO weather
VALUES ('San Francisco', 46, 50, 0.25, '11/27/1994');
VALUES ('San Francisco', 46, 50, 0.25, '11/27/1994');
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
You can also use the <
Command>copy</C
ommand> command to perform load large
You can also use the <
command>copy</c
ommand> command to perform load large
amounts of data from flat (<
Acronym>ASCII</A
cronym>) files.
amounts of data from flat (<
acronym>ASCII</a
cronym>) files.
This is usually faster because the data is read (or written) as a single atomic
This is usually faster because the data is read (or written) as a single atomic
transaction directly to or from the target table. An example would be:
transaction directly to or from the target table. An example would be:
<
ProgramL
isting>
<
programl
isting>
COPY
INTO
weather FROM '/home/user/weather.txt'
COPY weather FROM '/home/user/weather.txt'
USING DELIMITERS '|';
USING DELIMITERS '|';
</
ProgramL
isting>
</
programl
isting>
where the path name for the source file must be available to the backend server
where the path name for the source file must be available to the backend server
machine, not the client, since the backend server reads the file directly.
machine, not the client, since the backend server reads the file directly.
</para>
</para>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Querying a Class</T
itle>
<
title>Querying a Class</t
itle>
<
P
ara>
<
p
ara>
The weather class can be queried with normal relational
The weather class can be queried with normal relational
selection and projection queries. A <Acronym>SQL</Acronym> <Command>select</Command>
selection and projection queries. A <acronym>SQL</acronym>
<command>select</command>
statement is used to do this. The statement is divided into
statement is used to do this. The statement is divided into
a target list (the part that lists the attributes to be
a target list (the part that lists the attributes to be
returned) and a qualification (the part that specifies
returned) and a qualification (the part that specifies
any restrictions). For example, to retrieve all the
any restrictions). For example, to retrieve all the
rows of weather, type:
rows of weather, type:
<
ProgramL
isting>
<
programl
isting>
SELECT * FROM
WEATHER
;
SELECT * FROM
weather
;
</
ProgramL
isting>
</
programl
isting>
and the output should be:
and the output should be:
<
ProgramL
isting>
<
programl
isting>
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
|city | temp_lo | temp_hi | prcp | date |
|city | temp_lo | temp_hi | prcp | date |
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
...
@@ -184,19 +187,19 @@ SELECT * FROM WEATHER;
...
@@ -184,19 +187,19 @@ SELECT * FROM WEATHER;
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
|Hayward | 37 | 54 | | 11-29-1994 |
|Hayward | 37 | 54 | | 11-29-1994 |
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
</
ProgramL
isting>
</
programl
isting>
You may specify any arbitrary expressions in the target list. For example, you can do:
You may specify any arbitrary expressions in the target list. For example, you can do:
<
ProgramL
isting>
<
programl
isting>
SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;
SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
Arbitrary Boolean operators
Arbitrary Boolean operators
(<
Command>and</Command>, <Command>or</Command> and <Command>not</C
ommand>) are
(<
command>and</command>, <command>or</command> and <command>not</c
ommand>) are
allowed in the qualification of any query. For example,
allowed in the qualification of any query. For example,
<
ProgramL
isting>
<
programl
isting>
SELECT * FROM weather
SELECT * FROM weather
WHERE city = 'San Francisco'
WHERE city = 'San Francisco'
AND prcp > 0.0;
AND prcp > 0.0;
...
@@ -208,45 +211,45 @@ results in:
...
@@ -208,45 +211,45 @@ results in:
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
|San Francisco | 46 | 50 | 0.25 | 11-27-1994 |
|San Francisco | 46 | 50 | 0.25 | 11-27-1994 |
+--------------+---------+---------+------+------------+
+--------------+---------+---------+------+------------+
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
As a final note, you can specify that the results of a
As a final note, you can specify that the results of a
select can be returned in a <
FirstTerm>sorted order</FirstT
erm>
select can be returned in a <
firstterm>sorted order</firstt
erm>
or with <
FirstTerm>duplicate instances</FirstT
erm> removed.
or with <
firstterm>duplicate instances</firstt
erm> removed.
<
ProgramL
isting>
<
programl
isting>
SELECT DISTINCT city
SELECT DISTINCT city
FROM weather
FROM weather
ORDER BY city;
ORDER BY city;
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Redirecting SELECT Queries</T
itle>
<
title>Redirecting SELECT Queries</t
itle>
<
P
ara>
<
p
ara>
Any select query can be redirected to a new class
Any select query can be redirected to a new class
<
ProgramL
isting>
<
programl
isting>
SELECT * INTO TABLE temp FROM weather;
SELECT * INTO TABLE temp FROM weather;
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
This forms an implicit <
Command>create</C
ommand> command, creating a new
This forms an implicit <
command>create</c
ommand> command, creating a new
class temp with the attribute names and types specified
class temp with the attribute names and types specified
in the target list of the <
Command>select into</C
ommand> command. We can
in the target list of the <
command>select into</c
ommand> command. We can
then, of course, perform any operations on the resulting
then, of course, perform any operations on the resulting
class that we can perform on other classes.
class that we can perform on other classes.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Joins Between Classes</T
itle>
<
title>Joins Between Classes</t
itle>
<
P
ara>
<
p
ara>
Thus far, our queries have only accessed one class at a
Thus far, our queries have only accessed one class at a
time. Queries can access multiple classes at once, or
time. Queries can access multiple classes at once, or
access the same class in such a way that multiple
access the same class in such a way that multiple
...
@@ -259,16 +262,16 @@ SELECT * INTO TABLE temp FROM weather;
...
@@ -259,16 +262,16 @@ SELECT * INTO TABLE temp FROM weather;
effect, we need to compare the temp_lo and temp_hi
effect, we need to compare the temp_lo and temp_hi
attributes of each EMP instance to the temp_lo and
attributes of each EMP instance to the temp_lo and
temp_hi attributes of all other EMP instances.
temp_hi attributes of all other EMP instances.
<
N
ote>
<
n
ote>
<
P
ara>
<
p
ara>
This is only a conceptual model. The actual join may
This is only a conceptual model. The actual join may
be performed in a more efficient manner, but this is invisible to the user.
be performed in a more efficient manner, but this is invisible to the user.
</
P
ara>
</
p
ara>
</
N
ote>
</
n
ote>
We can do this with the following query:
We can do this with the following query:
<
ProgramL
isting>
<
programl
isting>
SELECT W1.city, W1.temp_lo AS low, W1.temp_hi AS high,
SELECT W1.city, W1.temp_lo AS low, W1.temp_hi AS high,
W2.city, W2.temp_lo AS low, W2.temp_hi AS high
W2.city, W2.temp_lo AS low, W2.temp_hi AS high
FROM weather W1, weather W2
FROM weather W1, weather W2
...
@@ -282,172 +285,172 @@ SELECT W1.city, W1.temp_lo AS low, W1.temp_hi AS high,
...
@@ -282,172 +285,172 @@ SELECT W1.city, W1.temp_lo AS low, W1.temp_hi AS high,
+--------------+-----+------+---------------+-----+------+
+--------------+-----+------+---------------+-----+------+
|San Francisco | 37 | 54 | San Francisco | 46 | 50 |
|San Francisco | 37 | 54 | San Francisco | 46 | 50 |
+--------------+-----+------+---------------+-----+------+
+--------------+-----+------+---------------+-----+------+
</
ProgramL
isting>
</
programl
isting>
<
N
ote>
<
n
ote>
<
P
ara>
<
p
ara>
The semantics of such a join are
The semantics of such a join are
that the qualification
that the qualification
is a truth expression defined for the Cartesian product of
is a truth expression defined for the Cartesian product of
the classes indicated in the query. For those instances in
the classes indicated in the query. For those instances in
the Cartesian product for which the qualification is true,
the Cartesian product for which the qualification is true,
<
ProductName>Postgres</ProductN
ame> computes and returns the
<
productname>Postgres</productn
ame> computes and returns the
values specified in the target list.
values specified in the target list.
<
ProductName>Postgres</ProductName> <Acronym>SQL</A
cronym>
<
productname>Postgres</productname> <acronym>SQL</a
cronym>
does not assign any meaning to
does not assign any meaning to
duplicate values in such expressions.
duplicate values in such expressions.
This means that <
ProductName>Postgres</ProductN
ame>
This means that <
productname>Postgres</productn
ame>
sometimes recomputes the same target list several times;
sometimes recomputes the same target list several times;
this frequently happens when Boolean expressions are connected
this frequently happens when Boolean expressions are connected
with an "or". To remove such duplicates, you must use
with an "or". To remove such duplicates, you must use
the <
Command>select distinct</C
ommand> statement.
the <
command>select distinct</c
ommand> statement.
</
P
ara>
</
p
ara>
</
N
ote>
</
n
ote>
</para>
</para>
<
P
ara>
<
p
ara>
In this case, both W1 and W2 are surrogates for an
In this case, both W1 and W2 are surrogates for an
instance of the class weather, and both range over all
instance of the class weather, and both range over all
instances of the class. (In the terminology of most
instances of the class. (In the terminology of most
database systems, W1 and W2 are known as <
FirstTerm>range variables</FirstT
erm>.)
database systems, W1 and W2 are known as <
firstterm>range variables</firstt
erm>.)
A query can contain an arbitrary number of
A query can contain an arbitrary number of
class names and surrogates.
class names and surrogates.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Updates</T
itle>
<
title>Updates</t
itle>
<
P
ara>
<
p
ara>
You can update existing instances using the update command.
You can update existing instances using the update command.
Suppose you discover the temperature readings are
Suppose you discover the temperature readings are
all off by 2 degrees as of Nov 28, you may update the
all off by 2 degrees as of Nov 28, you may update the
data as follow:
data as follow:
<
ProgramL
isting>
<
programl
isting>
UPDATE weather
UPDATE weather
SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2
SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2
WHERE date > '11/28/1994';
WHERE date > '11/28/1994';
</
ProgramL
isting>
</
programl
isting>
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Deletions</T
itle>
<
title>Deletions</t
itle>
<
P
ara>
<
p
ara>
Deletions are performed using the <
Command>delete</C
ommand> command:
Deletions are performed using the <
command>delete</c
ommand> command:
<
ProgramL
isting>
<
programl
isting>
DELETE FROM weather WHERE city = 'Hayward';
DELETE FROM weather WHERE city = 'Hayward';
</
ProgramL
isting>
</
programl
isting>
All weather recording belongs to Hayward is removed.
All weather recording belongs to Hayward is removed.
One should be wary of queries of the form
One should be wary of queries of the form
<
ProgramL
isting>
<
programl
isting>
DELETE FROM classname;
DELETE FROM classname;
</
ProgramL
isting>
</
programl
isting>
Without a qualification, <
Command>delete</C
ommand> will simply
Without a qualification, <
command>delete</c
ommand> will simply
remove all instances of the given class, leaving it
remove all instances of the given class, leaving it
empty. The system will not request confirmation before
empty. The system will not request confirmation before
doing this.
doing this.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
<
S
ect1>
<
s
ect1>
<
Title>Using Aggregate Functions</T
itle>
<
title>Using Aggregate Functions</t
itle>
<
P
ara>
<
p
ara>
Like most other query languages,
Like most other query languages,
<
ProductName>PostgreSQL</ProductN
ame> supports
<
productname>PostgreSQL</productn
ame> supports
aggregate functions.
aggregate functions.
An aggregate function computes a single result from multiple input rows.
An aggregate function computes a single result from multiple input rows.
For example, there are aggregates to compute the
For example, there are aggregates to compute the
<
Function>count</Function>, <Function>sum</F
unction>,
<
function>count</function>, <function>sum</f
unction>,
<
Function>avg</Function> (average), <Function>max</F
unction> (maximum) and
<
function>avg</function> (average), <function>max</f
unction> (maximum) and
<
Function>min</F
unction> (minimum) over a set of instances.
<
function>min</f
unction> (minimum) over a set of instances.
</para>
</para>
<
P
ara>
<
p
ara>
It is important to understand the interaction between aggregates and
It is important to understand the interaction between aggregates and
SQL's <
Command>where</Command> and <Command>having</C
ommand> clauses.
SQL's <
command>where</command> and <command>having</c
ommand> clauses.
The fundamental difference between <
Command>where</C
ommand> and
The fundamental difference between <
command>where</c
ommand> and
<
Command>having</Command> is this: <Command>where</C
ommand> selects
<
command>having</command> is this: <command>where</c
ommand> selects
input rows before groups and aggregates are computed (thus, it controls
input rows before groups and aggregates are computed (thus, it controls
which rows go into the aggregate computation), whereas
which rows go into the aggregate computation), whereas
<
Command>having</C
ommand> selects group rows after groups and
<
command>having</c
ommand> selects group rows after groups and
aggregates are computed. Thus, the
aggregates are computed. Thus, the
<
Command>where</C
ommand> clause may not contain aggregate functions;
<
command>where</c
ommand> clause may not contain aggregate functions;
it makes no sense to try to use an aggregate to determine which rows
it makes no sense to try to use an aggregate to determine which rows
will be inputs to the aggregates. On the other hand,
will be inputs to the aggregates. On the other hand,
<
Command>having</C
ommand> clauses always contain aggregate functions.
<
command>having</c
ommand> clauses always contain aggregate functions.
(Strictly speaking, you are allowed to write a <
Command>having</C
ommand>
(Strictly speaking, you are allowed to write a <
command>having</c
ommand>
clause that doesn't use aggregates, but it's wasteful; the same condition
clause that doesn't use aggregates, but it's wasteful; the same condition
could be used more efficiently at the <
Command>where</C
ommand> stage.)
could be used more efficiently at the <
command>where</c
ommand> stage.)
</para>
</para>
<
P
ara>
<
p
ara>
As an example, we can find the highest low-temperature reading anywhere
As an example, we can find the highest low-temperature reading anywhere
with
with
<
ProgramL
isting>
<
programl
isting>
SELECT max(temp_lo) FROM weather;
SELECT max(temp_lo) FROM weather;
</
ProgramL
isting>
</
programl
isting>
If we want to know which city (or cities) that reading occurred in,
If we want to know which city (or cities) that reading occurred in,
we might try
we might try
<
ProgramL
isting>
<
programl
isting>
SELECT city FROM weather WHERE temp_lo = max(temp_lo);
SELECT city FROM weather WHERE temp_lo = max(temp_lo);
</
ProgramL
isting>
</
programl
isting>
but this will not work since the aggregate max() can't be used in
but this will not work since the aggregate max() can't be used in
<
Command>where</C
ommand>. However, as is often the case the query can be
<
command>where</c
ommand>. However, as is often the case the query can be
restated to accomplish the intended result; here by using a
restated to accomplish the intended result; here by using a
<
FirstTerm>subselect</FirstT
erm>:
<
firstterm>subselect</firstt
erm>:
<
ProgramL
isting>
<
programl
isting>
SELECT city FROM weather WHERE temp_lo = (SELECT max(temp_lo) FROM weather);
SELECT city FROM weather WHERE temp_lo = (SELECT max(temp_lo) FROM weather);
</
ProgramL
isting>
</
programl
isting>
This is OK because the sub-select is an independent computation that
This is OK because the sub-select is an independent computation that
computes its own aggregate separately from what's happening in the outer
computes its own aggregate separately from what's happening in the outer
select.
select.
</
P
ara>
</
p
ara>
<
P
ara>
<
p
ara>
Aggregates are also very useful in combination with
Aggregates are also very useful in combination with
<
FirstTerm>group by</FirstT
erm> clauses. For example, we can get the
<
firstterm>group by</firstt
erm> clauses. For example, we can get the
maximum low temperature observed in each city with
maximum low temperature observed in each city with
<
ProgramL
isting>
<
programl
isting>
SELECT city, max(temp_lo)
SELECT city, max(temp_lo)
FROM weather
FROM weather
GROUP BY city;
GROUP BY city;
</
ProgramL
isting>
</
programl
isting>
which gives us one output row per city. We can filter these grouped
which gives us one output row per city. We can filter these grouped
rows using <
Command>having</C
ommand>:
rows using <
command>having</c
ommand>:
<
ProgramL
isting>
<
programl
isting>
SELECT city, max(temp_lo)
SELECT city, max(temp_lo)
FROM weather
FROM weather
GROUP BY city
GROUP BY city
HAVING min(temp_lo) < 0;
HAVING min(temp_lo) < 0;
</
ProgramL
isting>
</
programl
isting>
which gives us the same results for only the cities that have some
which gives us the same results for only the cities that have some
below-zero readings. Finally, if we only care about cities whose
below-zero readings. Finally, if we only care about cities whose
names begin with 'P', we might do
names begin with 'P', we might do
<
ProgramL
isting>
<
programl
isting>
SELECT city, max(temp_lo)
SELECT city, max(temp_lo)
FROM weather
FROM weather
WHERE city like 'P%'
WHERE city like 'P%'
GROUP BY city
GROUP BY city
HAVING min(temp_lo) < 0;
HAVING min(temp_lo) < 0;
</
ProgramL
isting>
</
programl
isting>
Note that we can apply the city-name restriction in
Note that we can apply the city-name restriction in
<
Command>where</C
ommand>, since it needs no aggregate. This is
<
command>where</c
ommand>, since it needs no aggregate. This is
more efficient than adding the restriction to <
Command>having</C
ommand>,
more efficient than adding the restriction to <
command>having</c
ommand>,
because we avoid doing the grouping and aggregate calculations
because we avoid doing the grouping and aggregate calculations
for all rows that fail the <
Command>where</C
ommand> check.
for all rows that fail the <
command>where</c
ommand> check.
</
P
ara>
</
p
ara>
</sect1>
</sect1>
</
C
hapter>
</
c
hapter>
<!-- Keep this comment at the end of the file
<!-- Keep this comment at the end of the file
Local variables:
Local variables:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment