SELECT - Remove several rows from a table or view

SYNOPSIS

 

SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
    * | expression [ AS output_name ] [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY expression [, ...] ]
    [ HAVING condition [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
    [ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
    [ LIMIT { count | ALL } ]
    [ OFFSET start ]
    [ FOR UPDATE [ OF table_name [, ...] ] ]

where from_item can be one of:

    [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    ( select ) [ AS ] alias [ ( column_alias [, ...] ) ]
    function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ]
    function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
    from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ]

[Comment: FIXME: This last syntax is incorrect if the join type is an INNER or OUTER join (in which case one of NATURAL, ON ..., or USING ... is mandatory, not optional). What's the best way to fix this?]

DESCRIPTION Description

SELECT from one or more tables to return rows. SELECT usual treatment as follows:

1.

Calculate all the elements listed in FROM. (FROM Each element is a real or virtual table.) If you declare more than one element in the FROM list, then they cross together. (See below Clause the FROM [ SELECT (. 7)]).
2.

If you declare a WHERE clause, does not meet the conditions to eliminate all rows in the output. (See below Clause the WHERE [ SELECT (. 7)]).
3.

If the GROUP BY clause is declared, the output is divided into one or more different sets of matching values in. If the HAVING clause appears, then it eliminates those groups does not meet the given conditions. (See below BY Clause the GROUP [ SELECT (. 7)] Clause and the HAVING [ SELECT (. 7)]).
4.

Using UNION, INTERSECT, and EXCEPT, we can output multiple SELECT statements combined into one result set. UNION operator returns the result set or one of the two rows, INTERSECT operator returns exactly two rows in the result set have. EXCEPT operator returns a result set in the first, but not in the second row of the result set. In either case, the duplicate rows are deleted, unless declared ALL. (See below Clause the UNION [ SELECT (. 7)], INTERSECT Clause [ SELECT (L)], and Clause the EXCEPT [ SELECT (. 7)]).
5.

When the actual output rows, SELECT is the first to calculate the output expression for each row selected (see below List the SELECT [ the SELECT (7)]).
6.

If you declare an ORDER BY clause, the rows returned are sorted in the specified order. If no ORDER BY, then the data line according to the system that produced the fastest method of analysis. (See below BY Clause the ORDER [ SELECT (. 7)]).
7.

If you are given LIMIT or OFFSET clause, the SELECT statement returns only a subset of the result rows. (See below Clause the LIMIT [ SELECT (. 7)]).
8.
DISTINCT remove those duplicate rows from the result. DISTINCT ON delete all those rows that match the specified expression. ALL (default) will return all candidate rows, including duplicates. (See below Clause the DISTINCT [ SELECT (. 7)]).
9.
FOR UPDATE clause causes the SELECT statement to update the concurrent lock selected rows. (See below the UPDATE Clause the FOR [ SELECT (. 7)]).

 


You must have SELECT privilege to read values ​​from the table. Use UPDATE FOR UPDATE also requires permission.

PARAMETERS Parameters

FROM clause

SELECT FROM clause specifies one or more source tables. If a plurality of source tables declaration, result is the Cartesian product of all the sources (cross-connect). But usually we will add some conditions restrict the returned rows into the result set Cartesian product of a small.

FROM- clause can include:

table_name

A name of an existing table or view (schema-qualified). If you declare ONLY, only scans the table. If there is no statement ONLY, the table and all its derived tables (if any) are scanned. It may be behind the table name with a * to represent all subsequent sweep representatives, but in the current version, this is the default behavior. (In previous versions of PostgreSQL 7.1 years, ONLY characteristic is the default.) The default properties can be changed by modifying the configuration options sql_interitance.
alias

Take FROM alias for those items that contains aliases. Abbreviations used alias or eliminate ambiguity from the connection (connection from the inside, the same table is scanned a plurality of times). When an alias, then it will be completely hides the actual name of the table or function; for example, if given FROM foo AS f, then it must be something the rest of the SELECT FROM this item to f not foo references. If you write an alias, we can also provide a column alias list, so you can replace the name of the table one or more fields.
select

A sub-SELECT in the FROM clause that appears. Its output role seems to be to create a temporary table in their lifetime is in this SELECT command. Please note that this sub-SELECT must be surrounded by parentheses. And it must add to the alias.
function_name

Function calls can appear in the FROM clause. (Especially useful for those functions return result sets, but any function can be used.) To do so as if during the life of the SELECT command, the output of the function is created as a temporary table. We can also use aliases. If you write an alias, we can also write a column alias list, provide the name replaced by a complex type of function returns one or more attributes. If the function is defined to record data type, AS must appear a keyword or alias, followed by a list of field definitions, shaped like :( column_name data_type [, ...]). This field defines the list must match the actual number and type of function returns the field.
join_type
*
[ INNER ] JOIN
*
LEFT [ OUTER ] JOIN
*
RIGHT [ OUTER ] JOIN
*
FULL [ OUTER ] JOIN
*
CROSS JOIN


one. It INNER and OUTER join types, we must declare a join condition, that is a NATURAL, ON join_condition, or USING (join_column [, ...]). See below for their meanings, for CROSS JOIN, none of these clauses can not appear.


A JOIN clause combines two FROM items. When necessary to use parentheses to determine the order of nesting. Without parentheses, JOIN nested from left to right. In any case, JOIN than the comma-separated items FROM bind tighter.

CROSS JOIN and INNER JOIN produce a simple Cartesian product, and you list the results of both items at the top level of FROM. CROSS JOIN equivalent INNER JOIN ON (true), that is, no rows are deleted conditions. This type of connection is just a notational convenience, since they are simple and you use the FROM and WHERE do things the same.

LEFT OUTER JOIN returns a Cartesian product conditions (that is, out of all combinations of the row by a connection condition) of the row, with no left table row corresponding to the right hand side of the table may be matched together by those line connection conditions. Such a full length extended to the left-hand row are connected to generate the table, that is the right hand side in the table fill over the corresponding field position. Please note that only those rows in the decision it is time to match, JOIN clause of computing on their own terms. With the proviso that the outer layer is applied after this.


Corresponds, RIGHT OUTER JOIN returns all the joined rows, with each row unmatched right-hand side (left extended with nulls). It's just a symbol of convenience, because we can always convert it to a LEFT OUTER JOIN, as long as the input to the left and right out what you can.

FULL OUTER JOIN returns all the joined rows, with each row does not match the left hand side (right side extended with nulls), plus the row (left extended with nulls) for each unmatched right-hand side.

ON join_condition
join_condition is an expression, generating results of boolean type (similar to the WHERE clause), those represented by the connection line is considered a match.
USING ( join_column [, ...])

As a form USING (a, b, ...) of clause is ON left_table.a = right_table.a AND left_table.b = right_table.b ... abbreviation. Similarly, the USING implies: a field equivalent of each pair included in the connection only one output instead of outputs of both means.
NATURAL
NATURAL is an acronym for a USING list, this list is to say the two tables with the same name in the field.

 

WHERE clause


The optional WHERE condition has common forms are as follows:

 

WHERE condition


This condition may be generated in any type of boolean expressions. This condition does not meet any of the rows are deleted from the output. If the value of a row replacement references to conditions calculated conditions are true, then the conditions are satisfied, even if the row.

GROUP BY clause


The general form of the optional GROUP BY clause

 

GROUP BY expression [, ...]

GROUP BY will all lines share the same values ​​on a combination of expressions compressed into one line. expression can be an input field name, or an input field (SELECT list) number, or may be formed in any arbitrary expression value from the input field. In ambiguous situations, a GROUP BY name will be interpreted as the name of the input field, rather than the name of the output field.


If the aggregate functions, it will form a set of all rows is calculated, to generate a single value (and if no GROUP BY, then the aggregate of all lines chosen a calculated value) for each group. If the emergence of GROUP BY, then again cited the SELECT list expressions grouping those fields it is not illegal, unless within aggregate functions, because for fields that are not grouped, may return multiple values.

HAVING clause


The optional HAVING clause has the form:

 

HAVING condition


Here condition and the same for the WHERE clause of the statement.

HAVING row to set a number of conditions are not satisfied in addition. HAVING with different WHERE: WHERE filtered prior to use separate rows GROUP BY, HAVING filtered and the line created by the GROUP BY. Each field is referenced in the condition must be quoted in a row grouping without ambiguity, unless the reference appears within an aggregate function inside.

UNION clause

UNION clause is a general form:

 

select_statement UNION [ ALL ] select_statement


Here select_statement is not any ORDER BY, LIMIT, or FOR UPDATE clause of the SELECT statement. (If surrounded by parentheses, ORDER BY and LIMIT can be attached to the sub-expressions. If no parentheses, these clauses to the result of using the UNION, instead of to the right hand side of the input expression thereof.)

UNION operator the calculation results of those rows involving SELECT statement returns any combination. If there is a line at least two inside a result set, it will result in a set union of these two sets. Two immediate operands as UNION SELECT must produce the same number of columns, and corresponding columns must have compatible data types.


By default, UNION the result does not contain any duplicate rows unless the ALL clause. ALL stopped eliminate repetitive motions.


A plurality of the same SELECT statement UNION operator is evaluated left to right unless parentheses were identified with.


Currently, FOR UPDATE can not be declared in the UNION result or input.

INTERSECT clause

The general form of INTERSECT clause is:

 

select_statement INTERSECT [ ALL ] select_statement

select_statement any, LIMIT, or FOR UPDATE clause of the SELECT statement with no ORDER BY.


SELECT statement INTERSECT set intersection calculations involving the rows returned. If a row of two result sets appear, then it is at the intersection of two result sets.


NTERSECT result does not contain any duplicate rows unless you declare ALL option. ALL after use, the left hand side of a table with m repetition list in the right hand side there are n rows repeats appear min (m, n) times.


Unless parentheses dictate, a plurality of the same INTERSECT operator SELECT statement is calculated from left to right. INTERSECT bind more tightly than UNION --- That A UNION B INTERSECT C will read as A UNION (B INTERSECT C), the statement unless you use parentheses.

EXCEPT clause

EXCEPT clause has the following general form:

 

select_statement EXCEPT [ ALL ] select_statement


Here fIselect_statement is not any ORDER BY, LIMIT, or FOR UPDATE clause of the SELECT expression.

EXCEPT operator computes a SELECT statement is present on the left of the right output line not in the output statement.

EXCEPT results do not contain any duplicate rows unless the ALL option. When using ALL, m duplicates in a table and left with n rows repeats appear max (mn, 0) views the right hand side of the table.


Unless indicated with parentheses sequentially, a plurality of operators EXCEPT same SELECT statement are evaluated left to right. EXCEPT and UNION bind the same level.

SELECT list

SELECT list of things (in the keywords SELECT and FROM) between a) declare an expression, the expression form of the SELECT statement output lines. This expression can be (and indeed usually is) those referenced in the FROM clause in the field of computing. By using AS output_name, we can declare a different name to the line output. The name of the label main lines do appear. It can also be used as the ORDER BY and GROUP BY clause references a field value, but can not be so used in the WHERE or HAVING clause; there, you have to write expressions.


In addition to the expression, we can write to the output a list of all the fields * denotes an abbreviation of selected rows. Similarly, we can write table_name. * As an abbreviation for the fields from a particular table.

ORDER BY clause


The optional ORDER BY clause has the following general form:

 

ORDER BY expression [ ASC | DESC | USING operator ] [, ...]

expression can be an output field (SELECT list) the name or number, or may be any numerical expression input fields thereof.

ORDER BY clause causes the result rows to be sorted according to the specified expression. If according to the leftmost expression, the same result as two lines, then it is compared according to the next expression, and so on. If they are the same for all the declarations of expression, then returned in random order.


It refers to the ordinal number column / field in order (left to right) position. This feature allows us to sort the column / field does not have a unique name. It is never necessary, because it is always possible to give a calculated column / field is given a name using the AS clause.


In the ORDER BY where you can also use any expression, including those that field does not appear in the SELECT list of results inside. Therefore, the following statement is now legal:

 

SELECT name FROM distributors ORDER BY code;


A limitation of this feature is used in UNION, INTERSECT, or EXCEPT query ORDER BY clause can only be declared in a field name or digital output, and can not be declared in an expression.


Note that if an ORDER BY expression is a simple name, while the match result fields and input fields, ORDER BY will interpret it as the result of field names. This GROUP BY and do in the same circumstances choose the opposite. Such inconsistency is mandatory by the SQL standard.


We can add a keyword DESC (descending) or ASC (ascending) ORDER BY clause to each column / field. If you do not declare, ASC is the default. We can also declare a sort operator to implement sorting in the USING clause. ASC is equivalent to using USING <DESC be equivalent to using USING>. (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)


In one domain, null values ​​are sorted in front of the other row a value. In other words, in ascending order, at the end null row, and row values ​​in descending order at the beginning of time and space.


Character-type data is sorted in order of the character set associated with the region, this area is established when the database cluster initialized.

LIMIT clause

LIMIT clause consists of two independent clauses:

 

LIMIT { count | ALL }
OFFSET start


Here count declare the maximum number of rows returned, and start statement returns the number of rows to ignore before the line.
.PP
LIMIT allows you to retrieve a portion of the line generated by other parts of the query. If a limit count is given, then the number of rows returned which does not exceed the limit. If an offset is given, it will ignore the number of rows before beginning to return rows.


When using LIMIT, a good practice is to use an ORDER BY clause to limit the result rows into a unique order. Otherwise, you'll get a subset of the query returns unforeseen --- you might want to tenth row to the twentieth row, but in what order? Unless you specify ORDER BY, or you do not know what order.


When the query optimizer generates a query plan to LIMIT into account, so you are likely to vary LIMIT and OFFSET values ​​given and get different plans (to generate different line sequence). So choose a different query results using different LIMIT / OFFSET subset of values ​​will not produce consistent results, unless you are forced to generate a predictable sequence of results with ORDER BY. This is not wrong; it is born SQL features, because unless you use ORDER BY restraint order, SQL does not guarantee the results generated by the query in any particular order.

DISTINCT clause


If you declare DISTINCT, then concentrated to remove all duplicate rows from the result (for each duplicate group retains a row). ALL declared contrary effect: all rows are reserved; this is the default.

The ON the DISTINCT ( expression The [, ...]) retaining only those rows of the first set of lines calculated in the same result in the expression given. DISTINCT ON expressions are used ORDER BY (see above) the same interpretation rules. Please note that, unless we use the ORDER BY line we need to ensure that first appeared Otherwise, each of the "first line" is unpredictable. such as,

 

SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;


Retrieves the most recent weather report for each location. But if we do not use ORDER BY to force descending order of time values ​​for each location, then we'll get when we do not know what the report for each location.


DISTINCT ON expressions must match the leftmost ORDER BY expression. ORDER BY clause will typically contain additional expression can determine the priority of each group which need DISTINCT ON rows.

FOR UPDATE clause

FOR UPDATE clause has the following form

 

FOR UPDATE [ OF table_name [, ...] ]

FOR UPDATE so that those lines are retrieved in a SELECT statement to be locked, just to update the same. This will prevent them from being modified or deleted by other transactions before the end of the current transaction; that is, other views UPDATE, DELETE, or SELECT FOR UPDATE affairs of these rows will be blocked until the current transaction ends. Similarly, if a UPDATE from another transaction, DELETE, or SELECT FOR UPDATE has been locked up one or some selected lines, SELECT FOR UPDATE will wait until the end of those transactions, and will then lock and return the updated row ( or does not return rows if the row has been deleted). For more discussion see Chapter 12 `` Concurrency Control ''.


If a particular table was only locked in FOR UPDATE, then only those rows from the table; any other tables used in the SELECT are simply read as usual.

FOR UPDATE can not return to the environment in line at those who can not use a separate table data rows clearly marked; for example, it can not be used with aggregation.

LIMIT FOR UPDATE may appear in the front, mainly for PostgreSQL before and 7.3 compatible. However, it performs more efficiently at the back LIMIT, so we recommend on the back LIMIT.

EXAMPLES Examples


The films are connected together in Table and Table distributors:

 

SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did

       title       | did |     name     | date_prod  |   kind
-------------------+-----+--------------+------------+----------
 The Third Man     | 101 | British Lion | 1949-12-23 | Drama
 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
 ...


Statistical len packet with all the movies and the kind of column groups / field (the length) and:

 

SELECT kind, sum(len) AS total FROM films GROUP BY kind;

   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38


Statistics All films (Films), the column / len field group (the length) and a packet with the kind and the display is less than the sum total of 5 hours:

 

SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) < interval '5 hours';

   kind   | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38


The following two examples are the individual sort the results based on the contents of the second column (name) of the classical methods:

 

SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;

 did |       name
-----+------------------
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean-Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | that
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros.
 108 | Westward


The following example demonstrates how to obtain a connection table distributors and the actors, each table will only start with the letter W are taken out. Because only took the line is not relevant, so the ALL keyword is omitted:

 

distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...

SELECT distributors.name
    FROM distributors
    WHERE distributors.name LIKE 'W%'
UNION
SELECT actors.name
    FROM actors
    WHERE actors.name LIKE 'W%';

      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen


This example shows how to use a function in the FROM clause, including with and without field definitions list.

 

CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors(111);
 did |    name
-----+-------------
 111 | Walt Disney

CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney

COMPATIBILITY The


Of course, SELECT statements and SQL compliant. But there are some extensions and some of the missing features.

Omit the FROM clause

PostgreSQL allows us to omit the FROM clause in a query. Its most immediate purpose is to calculate simple result of constant expressions:

 

SELECT 2+2;

 ?column?
----------
        4


Some other SQL databases can not do this unless the introduction of a single-line pseudo-table do SELECT data source.


Another characteristic of this use is less obvious to an ordinary SELECT from one or more tables abbreviations:

 

SELECT distributors.* WHERE distributors.name = 'Westward';

 did |   name
-----+----------
 108 | Westward

This is because we can run in the SELECT reference to each table but not mentioned in FROM are added in an implicit FROM item.


Although this is a very convenient wording, but it is easy to misuse. For example, the following query

 

SELECT distributors.* FROM distributors d;

Probably a mistake; most likely mean

 

SELECT d.* FROM distributors d;

Instead of following him actually get unconstrained connection

 

SELECT distributors.* FROM distributors d, distributors distributors;

To help detect this error, PostgreSQL and future versions will be a time that is implicit FROM characteristics have explicit FROM clause of a query you use to give a warning. Also, it is possible to disable the implicit-FROM feature by setting the ADD_MISSING_FROM parameter to false.

AS keyword


In the SQL standard, the optional keyword AS is redundant and can be omitted without affecting the meaning. PostgreSQL parser requires this keyword when renaming columns / fields, because the type extensibility features lead to ambiguity in this environment is. However, AS in FROM items in it is optional.

GROUP BY and ORDER BY name in the space available


In the SQL92 standard where, ORDER BY clause may only use result column names or numbers, while a GROUP BY clause can only use expressions based on input column names. PostgreSQL these two clause is extended to allow alternatively (if there is ambiguity, however, the standard interpretation). PostgreSQL also allows two clauses specify arbitrary expressions. Please note that the name appears in the expression of strong always used as input field names, field names rather than the result.

SQL99 uses a slightly different definition which is not upward compatible with SQL92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL99 does. 

Guess you like

Origin www.cnblogs.com/fanweisheng/p/11098303.html