PostgreSQL SELECT
Summary: in this tutorial, you are going to learn how to use the basicPostgreSQL SELECT statement to query data from a table.
Note that if you don't know how to execute a query against the PostgreSQL database using thepsql command-line tool orpgAdmin GUI tool, you can checkthe connection to the PostgreSQL database tutorial.
One of the most common tasks, when you work with the database, is to retrieve data from tables using theSELECT statement.
TheSELECT statement is one of the most complex statements in PostgreSQL. It has many clauses that you can use to form a flexible query.
Due to its complexity, we will break it down into many shorter and easy-to-understand tutorials so that you can learn about each clause faster.
TheSELECT statement has the following clauses:
- Select distinct rows using
DISTINCToperator. - Sort rows using
ORDER BYclause. - Filter rows using
WHEREclause. - Select a subset of rows from a table using
LIMITorFETCHclause. - Group rows into groups using
GROUP BYclause. - Filter groups using
HAVINGclause. - Join with other tables usingjoins such as
INNER JOIN,LEFT JOIN,FULL OUTER JOIN,CROSS JOINclauses. - Perform set operations using
UNION,INTERSECT, andEXCEPT.
In this tutorial, you are going to focus on theSELECTandFROM clauses.
PostgreSQL SELECT statement syntax
Let's start with the basic form of theSELECT statement that retrieves data from a single table.
The following illustrates the syntax of theSELECT statement:
SELECT select_listFROM table_name;In this syntax:
- First, specify a select list that can be a column or a list of columns in a table from which you want to retrieve data. If you specify a list of columns, you need to place a comma (
,) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk (*) shorthand instead of specifying all the column names. The select list may also contain expressions or literal values. - Second, provide the name of the table from which you want to query data after the
FROMkeyword.
TheFROM clause is optional. If you are not querying data from any table, you can omit theFROM clause in theSELECT statement.
PostgreSQL evaluates theFROM clause before theSELECT clause in theSELECT statement:
Note that the SQL keywords are case-insensitive. It means thatSELECT is equivalent toselect orSelect. By convention, we will use all the SQL keywords in uppercase to make the queries easier to read.
PostgreSQL SELECT examples
Let's explore some examples of using theSELECT statement.
We will use the followingcustomer table in thedvdrentalsample database for the demonstration.
First,connect to the PostgreSQL server using thepostgres user:
psql -U postgresYou'll be prompted to enter a password for thepostgres user. After entering the password correctly, you will be connected to the PostgreSQL server:
postgres=#Second, switch the current database to dvdrental:
\c dvdrentalThird, execute the query in the following examples.
1) Using PostgreSQL SELECT statement to query data from one column example
This example uses theSELECT statement to find the first names of all customers from thecustomer table:
SELECT first_name FROM customer;Here is the partial output:
first_name------------- Jared Mary Patricia Linda Barbara...Notice that we added a semicolon (;) at the end of theSELECT statement. The semicolon is not a part of the SQL statement; rather, it serves as a signal of PostgreSQL indicating the conclusion of an SQL statement. Additionally, semicolons are used to separate two or more SQL statements.
2) Using PostgreSQL SELECT statement to query data from multiple columns example
The following query uses theSELECT statement to retrieve first name, last name, and email of customers from thecustomer table:
SELECT first_name, last_name, emailFROM customer;Partial output:
first_name | last_name | email-------------+--------------+------------------------------------------ Jared | Ely | jared.ely@example.com Mary | Smith | mary.smith@example.com Patricia | Johnson | patricia.johnson@example.com...The output shows three corresponding columns first_name, last_name, and email.
3) Using PostgreSQL SELECT statement to query data from all columns of a table example
The following query uses theSELECT * statement to retrieve data from all columns of thecustomer table:
SELECT * FROM customer;Partial output:
customer_id | store_id | first_name | last_name | email | address_id | activebool | create_date | last_update | active-------------+----------+-------------+--------------+------------------------------------------+------------+------------+-------------+-------------------------+-------- 524 | 1 | Jared | Ely | jared.ely@example.com | 530 | t | 2006-02-14 | 2013-05-26 14:49:45.738 | 1 1 | 1 | Mary | Smith | mary.smith@example.com | 5 | t | 2006-02-14 | 2013-05-26 14:49:45.738 | 1 2 | 1 | Patricia | Johnson | patricia.johnson@example.com | 6 | t | 2006-02-14 | 2013-05-26 14:49:45.738 | 1...In this example, we used an asterisk (*) in theSELECT clause, which serves as a shorthand for all columns.
Instead of listing all columns in theSELECT clause individually, we can use the asterisk (*) to make the query shorter.
However, using the asterisk (*) in theSELECT statement is considered a bad practice when you embed SQL statements in the application code, such asPython,Java, orPHP for the following reasons:
- Database performance. Suppose you have a table with many columns and substantial data, the
SELECTstatement with the asterisk (*) shorthand will select data from all the columns of the table, potentially retrieving more data than required for the application. - Application performance. Retrieving unnecessary data from the database increases the traffic between the PostgreSQL server and the application server. Consequently, this can result in slower response times and reduced scalability for your applications.
For these reasons, it is recommended to explicitly specify the column names in theSELECT clause whenever possible. This ensures that only the necessary data is retrieved from the database, contributing to more efficient and optimized queries.
The asterisk (*) shorthand should be reserved solely for the ad-hoc queries that examine data from the database.
4) Using PostgreSQL SELECT statement with expressions example
The following example uses theSELECT statement to return the full names and emails of all customers from thecustomer table:
SELECT first_name || ' ' || last_name, emailFROM customer;Output:
?column? | email------------------------+------------------------------------------ Jared Ely | jared.ely@example.com Mary Smith | mary.smith@example.com Patricia Johnson | patricia.johnson@example.com...In this example, we used theconcatenation operator|| to concatenate the first name, space, and last name of every customer.
Notice the first column of the output doesn't have a name but?column?. To assign a name to a column temporarily in the query, you can use acolumn alias:
expression AS column_aliasThe AS keyword is optional. Therefore, you can use a shorter syntax:
expression column_aliasFor example, you can assign a column alias full_name to the first column of the query as follows:
SELECT first_name || ' ' || last_name full_name, emailFROM customer;Output:
full_name | email------------------------+------------------------------------------ Jared Ely | jared.ely@example.com Mary Smith | mary.smith@example.com Patricia Johnson | patricia.johnson@example.com...5) Using PostgreSQL SELECT statement without a FROM clause
TheFROM clause of theSELECT statement is optional. Therefore, you can omit it in the SELECT statement.
Typically, you use theSELECT clause with a function to retrieve the function result. For example:
SELECT NOW();In this example, we use theNOW() function in theSELECT statement. It'll return the current date and time of the PostgreSQL server.
Summary
- Use the
SELECT ... FROMstatement to retrieve data from a table. - PostgreSQL evaluates the
FROMclause before theSELECTclause. - Use a column alias to assign a temporary name to a column or an expression in a query.
- In PostgreSQL, the
FROMclause is optional.
Last updated on