PostgreSQL SELECT

PostgreSQL SELECT Statement

The SELECT statement is the most commonly used command in PostgreSQL. It is primarily used to retrieve and read data from a database table.

When you query a database, the result is stored in a structured format. This structured result is often referred to as a "result set".

The Basic Syntax

The basic syntax of a SELECT statement is incredibly simple and English-like. You must specify the columns you want and the table to pull from.

You use the SELECT keyword followed by a comma-separated list of columns. You then use the FROM keyword followed by the targeted table name.

SELECT Syntax:

SELECT column1, column2, column3
FROM table_name;

Selecting Specific Columns

Often, tables contain dozens of columns with vast amounts of data. Retrieving all columns when you only need two is very inefficient.

You can selectively choose exactly which columns to return. This reduces network load and speeds up your database performance heavily.

Selecting Specific Columns Example:

SELECT CustomerName, ContactName, City
FROM Customers;

Selecting All Columns

Sometimes you genuinely need to see every piece of data in a table. Instead of typing every single column name, you can use a shortcut.

The asterisk (*) is a wildcard character that represents "all columns". Using SELECT * tells PostgreSQL to return everything from the table.

Selecting All Columns Example:

-- This fetches every single column available in the Products table
SELECT * FROM Products;

Using SELECT for Math

The SELECT statement isn't strictly limited to fetching table data. You can also use it to perform simple mathematical calculations on the fly.

You don't even need a FROM clause to evaluate a simple math expression. PostgreSQL acts like a powerful calculator when requested.

Math Evaluation Example:

SELECT 250 * 4 AS total_result;

Summary

The SELECT statement is the core of reading data in SQL. Use specific column names to keep your queries fast and highly optimized.

Only use SELECT * when you truly need all the information available.

Exercise

Which character is used to select ALL columns from a specific table?