91
DECLARE
transaction that created it. If neither
WITHOUT HOLD
nor
WITH HOLD
is specified,
WITHOUT
HOLD
is the default.
query
ASELECT or VALUES command which will provide the rows to be returned bythe cursor.
The key words
BINARY
,
INSENSITIVE
,and
SCROLL
can appear in any order.
Notes
Normal cursors return data in text format, the same as a
SELECT
would produce. The
BINARY
option
specifies that the cursor should return data in binary format. This reduces conversion effort for both
the server and client, at the cost of more programmer effort to deal with platform-dependent binary
dataformats. Asan example, if aqueryreturns avalue of onefrom aninteger column, youwouldgeta
string of
1
with a default cursor, whereas witha binarycursor you would get a 4-byte field containing
the internal representation of the value (in big-endian byte order).
Binarycursors should beusedcarefully. Many applications, includingpsql, arenotprepared to handle
binary cursors and expect data to come back in the text format.
Note:When theclient applicationuses the “extended query” protocol to issuea
FETCH
command,
the Bind protocol message specifies whether data is to be retrieved in text or binary format. This
choice overrides the way that the cursor is defined. The concept of a binary cursor as such is
thus obsolete when using extended query protocol — any cursor can be treated as either text or
binary.
Unless
WITH HOLD
is specified, the cursor created by this command can only be used within the
current transaction. Thus,
DECLARE
without
WITH HOLD
is useless outside a transaction block: the
cursor would survive only to the completion of the statement. Therefore PostgreSQL reports an error
if such a command is used outside a transaction block. Use BEGIN and COMMIT (or ROLLBACK)
to define a transaction block.
If
WITH HOLD
is specified and the transaction that created the cursor successfully commits, the cur-
sor can continue to be accessed by subsequent transactions in the same session. (But if the creating
transaction is aborted, the cursor is removed.) A cursor created with
WITH HOLD
is closed when an
explicit
CLOSE
command is issued on it, or the session ends. In the current implementation, the rows
represented by a held cursor are copied into a temporary file or memory area so that they remain
available for subsequent transactions.
WITH HOLD
maynot be specified when the query includes
FOR UPDATE
or
FOR SHARE
.
The
SCROLL
option should be specified when defining a cursor that will be used to fetch backwards.
This is required by the SQL standard. However, for compatibility with earlier versions, PostgreSQL
will allowbackward fetches without
SCROLL
,if the cursor’s query planis simple enough that no extra
overhead is needed to support it. However, application developers are advised not to rely on using
backward fetches from a cursor that has not been created with
SCROLL
.If
NO SCROLL
is specified,
then backward fetches are disallowed in any case.
Backward fetches are also disallowedwhenthe query includes
FOR UPDATE
or
FOR SHARE
;therefore
SCROLL
may not be specified in this case.
1451
87
DECLARE
Caution
Scrollable and
WITH HOLD
cursors may give unexpected results if they invoke
any volatile functions (see Section 35.6). When a previously fetched row is re-
fetched, thefunctions might bere-executed, perhaps leading toresultsdifferent
from thefirst time. Oneworkaroundfor such cases is todeclarethecursor
WITH
HOLD
andcommit thetransaction beforereading any rows from it. This willforce
the entire output of the cursor to be materialized in temporary storage, so that
volatile functions are executed exactly once for each row.
If the cursor’s query includes
FOR UPDATE
or
FOR SHARE
,thenreturned rows are locked at the time
they are first fetched, in the same way as for a regular SELECT command with these options. In
addition, the returned rows will be the most up-to-date versions; therefore these options provide the
equivalent of what the SQL standard calls a “sensitive cursor”. (Specifying
INSENSITIVE
together
with
FOR UPDATE
or
FOR SHARE
is an error.)
Caution
It is generally recommended to use
FOR UPDATE
if the cursor is intended to
be usedwith
UPDATE ... WHERE CURRENT OF
or
DELETE ... WHERE CURRENT
OF
.Using
FOR UPDATE
prevents other sessions from changing the rows be-
tween the time they are fetched and the time they are updated. Without
FOR
UPDATE
,a subsequent
WHERE CURRENT OF
command will have no effect if the
row was changed since the cursor was created.
Another reason to use
FOR UPDATE
is that without it, a subsequent
WHERE
CURRENT OF
might fail if the cursor query does not meet the SQL standard’s
rules for being “simply updatable” (in particular, the cursor must reference just
one table and not use grouping or
ORDER BY
). Cursors that are not simply
updatable might work, or might not, depending on plan choice details; so in
the worst case, an application might work in testing and then fail in production.
Themainreason not touse
FOR UPDATE
with
WHERE CURRENT OF
is if you need
the cursor tobe scrollable, or to be insensitive to thesubsequent updates (that
is, continue to showthe old data). If this is arequirement, pay close heed to the
caveats shown above.
The SQL standardonly makes provisions for cursors in embedded SQL. The PostgreSQL server does
not implement an
OPEN
statement for cursors; a cursor is considered to be open when it is declared.
However, ECPG, theembedded SQL preprocessor for PostgreSQL, supports the standard SQL cursor
conventions, including those involving
DECLARE
and
OPEN
statements.
You can see all available cursors by querying the
pg_cursors
system view.
Examples
To declare a cursor:
DECLARE liahona CURSOR FOR SELECT
*
FROM films;
See FETCH for more examples of cursor usage.
1452
How to C#: Basic SDK Concept of XDoc.PDF for .NET In general, image extraction, editing, drawing, and You may add PDF document protection functionality into your C# PDF password and digital signature, and set
add photo to pdf online; how to add jpg to pdf file
13
DECLARE
Compatibility
The SQLstandardsays that it is implementation-dependentwhether cursors are sensitivetoconcurrent
updates of the underlying data by default. In PostgreSQL, cursors are insensitive by default, and can
be made sensitive by specifying
FOR UPDATE
.Other products may work differently.
The SQL standardallows cursors only in embeddedSQL and in modules. PostgreSQL permits cursors
to be used interactively.
Binary cursors are a PostgreSQL extension.
See Also
CLOSE, FETCH, MOVE
1453
86
DELETE
Name
DELETE — delete rows of a table
Synopsis
[ WITH [ RECURSIVE ]
with_query
[, ...] ]
DELETE FROM [ ONLY ]
table_name
[
*
] [ [ AS ]
alias
]
[ USING
using_list
]
[ WHERE
condition
| WHERE CURRENT OF
cursor_name
]
[ RETURNING
*
|
output_expression
[ [ AS ]
output_name
] [, ...] ]
Description
DELETE
deletes rows that satisfy the
WHERE
clause from the specified table. If the
WHERE
clause is
absent, the effect is to delete all rows in the table. The result is a valid, but empty table.
Tip: TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows
from a table.
There are two ways to delete rows in a table using information contained in other tables in the
database: using sub-selects, or specifying additional tables in the
USING
clause. Which technique
is more appropriate depends onthe specific circumstances.
The optional
RETURNING
clause causes
DELETE
to compute and return value(s) based on each row
actually deleted. Any expression using the table’s columns, and/or columns of other tables mentioned
in
USING
,can be computed. The syntax of the
RETURNING
list is identicalto that of the outputlist of
SELECT
.
You must have the
DELETE
privilege on the table to delete from it, as wellas the
SELECT
privilege for
any table in the
USING
clause or whose values are read in the
condition
.
Parameters
with_query
The
WITH
clause allows you to specify one or more subqueries that can be referenced by name
in the
DELETE
query. See Section 7.8 and SELECT for details.
table_name
The name (optionally schema-qualified) of the table to delete rows from. If
ONLY
is specified
before the table name, matchingrows are deletedfrom thenamed table only. If
ONLY
is not spec-
ified, matching rows are alsodeletedfrom anytables inheritingfrom the namedtable. Optionally,
*
can be specified after the table name to explicitly indicate that descendant tables are included.
1454
93
DELETE
alias
Asubstitute name for the target table. When an alias is provided, it completely hides the actual
name of the table. For example, given
DELETE FROM foo AS f
,the remainder of the
DELETE
statement must refer to this table as
f
not
foo
.
using_list
Alist of table expressions, allowing columns from other tables to appear in the
WHERE
condition.
This is similar to the list of tables that can be specified in the FROM Clause of a
SELECT
state-
ment; for example, an alias for the table name can be specified. Do not repeat the target table in
the
using_list
,unless you wish to set up a self-join.
condition
Anexpression that returns a value of type
boolean
.Only rows for whichthis expressionreturns
true
will be deleted.
cursor_name
The name of the cursor to use in a
WHERE CURRENT OF
condition. The row to be deleted is
the one most recently fetched from this cursor. The cursor must be a non-grouping query on
the
DELETE
’s target table. Note that
WHERE CURRENT OF
cannot be specified together with
aBoolean condition. See DECLARE for more information about using cursors with
WHERE
CURRENT OF
.
output_expression
An expression to be computed and returned by the
DELETE
command after each row is deleted.
The expression can use any column names of the table named by
table_name
or table(s) listed
in
USING
.Write
*
to return all columns.
output_name
Aname to use for a returned column.
Outputs
On successful completion, a
DELETE
command returns a command tag of the form
DELETE
count
The
count
is the number of rows deleted. Note that the number may be less than the number of rows
that matched the
condition
when deletes were suppressed by a
BEFORE DELETE
trigger. If
count
is 0, norows were deleted by the query (this is not considered an error).
If the
DELETE
command contains a
RETURNING
clause, the result will be similar to that of a
SELECT
statementcontainingthe columns and values defined inthe
RETURNING
list, computed over the row(s)
deleted by the command.
Notes
PostgreSQL lets youreference columns of other tables inthe
WHERE
conditionbyspecifying the other
tables in the
USING
clause. For example, to delete all films produced bya givenproducer, one can do:
DELETE FROM films USING producers
WHERE producer_id = producers.id AND producers.name = ’foo’;
1455
42
DELETE
What is essentially happening here is a join between
films
and
producers
,with all successfully
joined
films
rows being marked for deletion. This syntax is not standard. A more standard way to
do it is:
DELETE FROM films
WHERE producer_id IN (SELECT id FROM producers WHERE name = ’foo’);
In some cases the join style is easier to write or faster to execute than the sub-select style.
Examples
Delete all films but musicals:
DELETE FROM films WHERE kind <> ’Musical’;
Clear the table
films
:
DELETE FROM films;
Delete completed tasks, returning full details of the deleted rows:
DELETE FROM tasks WHERE status = ’DONE’ RETURNING
*
;
Delete the row of
tasks
on which the cursor
c_tasks
is currently positioned:
DELETE FROM tasks WHERE CURRENT OF c_tasks;
Compatibility
This command conforms to the SQL standard, except that the
USING
and
RETURNING
clauses are
PostgreSQL extensions, as is the ability to use
WITH
with
DELETE
.
1456
48
DISCARD
Name
DISCARD — discard sessionstate
Synopsis
DISCARD { ALL | PLANS | SEQUENCES | TEMPORARY | TEMP }
Description
DISCARD
releases internal resources associated with a database session. This command is useful for
partiallyor fullyresettingthesession’s state. Thereare several subcommandstorelease differenttypes
of resources; the
DISCARD ALL
variant subsumes all the others, and also resets additional state.
Parameters
PLANS
Releases all cached query plans, forcing re-planning to occur the next time the associated pre-
pared statement is used.
SEQUENCES
Discards all cached sequence-related state, including
currval()
/
lastval()
information and
any preallocated sequence values that have not yet beenreturned by
nextval()
.(See CREATE
SEQUENCE for a description of preallocated sequence values.)
TEMPORARY
or
TEMP
Drops all temporary tables created in the current session.
ALL
Releases all temporary resources associated with the current session and resets the session to its
initial state. Currently, this has thesameeffect asexecutingthefollowingsequence of statements:
SET SESSION AUTHORIZATION DEFAULT;
RESET ALL;
DEALLOCATE ALL;
CLOSE ALL;
UNLISTEN
*
;
SELECT pg_advisory_unlock_all();
DISCARD PLANS;
DISCARD SEQUENCES;
DISCARD TEMP;
Notes
DISCARD ALL
cannot be executed inside a transaction block.
1457
Documents you may be interested
Documents you may be interested