The SELECT statement in PostgreSQL is used to retrieve data from one or more tables. It allows you to fetch specific columns or all columns.
- Supports filtering with the WHERE clause.
- Can be combined with ORDER BY, GROUP BY, HAVING and LIMIT.
Syntax
SELECT column_1, column_2, ...
FROM table_name;
To retrieve all columns:
SELECT *
FROM table_name;
Where:
- column_1, column_2, ...: The columns to retrieve.
- table_name: The table from which data is fetched.
Working with Select Statement
First, create the following books table, which will be used in the examples below.
Example 1: Retrieve All Columns
The following query retrieves all records from the books table.
SELECT * FROM books;Output:
- The
SELECT *statement retrieves all columns from the bookstable.
Example 2: Retrieve Specific Columns
The following query retrieves only the book_title and price columns.
SELECT book_title, price FROM books;Output:
- The query retrieves only the specified columns instead of all columns.
Example 3: Retrieve Data Using WHERE Clause
The following query retrieves books whose price is greater than 600.
SELECT book_title, price FROM books WHERE price > 600;Output:
Example 4: Retrieve Data Using ORDER BY
The following query retrieves all books sorted by price in descending order.
SELECT * FROM books ORDER BY price DESC;Output: