PostgreSQL SELECT: Querying Data from a Table

Summary: in this tutorial, you will learn how to use the PostgreSQL SELECT statement to retrieve data from a table.

PostgreSQL SELECT statement #

To retrieve data from a table, you use the PostgreSQL SELECT statement.

Here’s the basic syntax of the SELECT statement:

SELECT column1, column2, ...
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

In this syntax:

  • First, list one or more columns of a table to retrieve data after the SELECT keyword. You use a comma to separate multiple columns.
  • Second, specify the table name in the FROM keyword.

When executing the SELECT FROM statement, PostgreSQL evaluates the FROM clause before the SELECT clause.

In the SELECT clause, you can retrieve data from one column:

SELECT column1
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

Or you can retrieve data from multiple columns:

SELECT column1, column2
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

If you want to retrieve data from all the columns of a table, you can list out all the columns with the assumption that the table_name has three columns:

SELECT column1, column2, column3
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

Or you can use SELECT * to retrieve data from all the column of the table:

SELECT *
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

Asterisk (*) or star is a shortcut for all columns. The SELECT * is often pronounced as SELECT star.

Selecting data from all table columns #

The following example uses the SELECT statement to retrieve data from all the columns of the inventories table:

SELECT * FROM inventories;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)

Try it

Output:

       name       |  brand  | quantity |  price
------------------+---------+----------+---------
 iPhone 14 Pro    | Apple   |       10 |  999.99
 Galaxy S23 Ultra | Samsung |       15 | 1199.99
 Pixel 7 Pro      | Google  |        8 |  899.99
 Xperia 1 IV      | Sony    |        7 | 1299.99Code language: plaintext (plaintext)

It returns four rows in the inventories table.

Selecting data from some columns #

The following example uses the SELECT statement to retrieve data from the name and price columns:

SELECT
  name,
  price
FROM
  inventories;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)