SELECT

Synopsis

Use the SELECT statement to retrieve rows of specified columns that meet a given condition from a table. It specifies the columns to be retrieved, the name of the table, and the condition each selected row must satisfy.

Syntax

  1. select ::= [ WITH [ RECURSIVE ] { with_query [ , ... ] } ] SELECT
  2. [ ALL | DISTINCT [ ON { ( expression [ , ... ] ) } ] ]
  3. [ * | { expression [ [ AS ] name ] } [ , ... ] ]
  4. [ FROM { from_item [ , ... ] } ] [ WHERE condition ]
  5. [ GROUP BY { grouping_element [ , ... ] } ]
  6. [ HAVING { condition [ , ... ] } ]
  7. [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
  8. [ ORDER BY { order_expr [ , ... ] } ]
  9. [ LIMIT [ integer | ALL ] ]
  10. [ OFFSET integer [ ROW | ROWS ] ]
  11. order_expr ::= expression [ ASC | DESC | USING operator_name ]
  12. [ NULLS { FIRST | LAST } ]

select

SELECT - 图1

order_expr

SELECT - 图2

Semantics

  • An error is raised if the specified table_name does not exist.
  • * represents all columns.

While the where clause allows a wide range of operators, the exact conditions used in the where clause have significant performance considerations (especially for large datasets).

condition

Specify an expression that evaluates to a Boolean value.

For details on from_item, grouping_element, and with_query see SELECT in the PostgreSQL documentation.

Examples

Create two sample tables.

  1. yugabyte=# CREATE TABLE sample1(k1 bigint, k2 float, v text, PRIMARY KEY (k1, k2));
  1. yugabyte=# CREATE TABLE sample2(k1 bigint, k2 float, v text, PRIMARY KEY (k1, k2));

Insert some rows.

  1. yugabyte=# INSERT INTO sample1(k1, k2, v) VALUES (1, 2.5, 'abc'), (1, 3.5, 'def'), (1, 4.5, 'xyz');
  1. yugabyte=# INSERT INTO sample2(k1, k2, v) VALUES (1, 2.5, 'foo'), (1, 4.5, 'bar');

Select from both tables using join.

  1. yugabyte=# SELECT a.k1, a.k2, a.v as av, b.v as bv FROM sample1 a LEFT JOIN sample2 b ON (a.k1 = b.k1 and a.k2 = b.k2) WHERE a.k1 = 1 AND a.k2 IN (2.5, 3.5) ORDER BY a.k2 DESC;
  1. k1 | k2 | av | bv
  2. ----+-----+-----+-----
  3. 1 | 3.5 | def |
  4. 1 | 2.5 | abc | foo
  5. (2 rows)

See also