PostgreSQL Fetch Data

Learn how to retrieve data from PostgreSQL tables using the SELECT statement and its most common clauses.

The SELECT Statement

SELECT is the workhorse of SQL: it retrieves rows from one or more tables. In its simplest form, you list the columns you want, followed by the table to read from. Using an asterisk (*) selects every column in the table.

Select all columns from a table

SELECT * FROM customers;

Select specific columns

SELECT full_name, email
FROM customers;

Filtering with WHERE

The WHERE clause filters rows so only those matching a condition are returned. Conditions can compare column values using operators like =, <>, <, >, and combine multiple conditions with AND, OR, and NOT.

Filter rows with a condition

SELECT full_name, signup_date
FROM customers
WHERE signup_date >= '2026-01-01';

Sorting and Limiting Results

ORDER BY controls the order in which rows are returned, either ascending (ASC, the default) or descending (DESC). LIMIT restricts how many rows come back, which is useful for previewing data or building paginated results.

  • WHERE filters which rows are included in the result
  • ORDER BY sorts the result set by one or more columns
  • LIMIT caps the number of rows returned
  • OFFSET skips a number of rows, often paired with LIMIT for pagination
  • DISTINCT removes duplicate rows from the result set
ClausePurposeExample
WHEREFilter rowsWHERE price > 20
ORDER BYSort rowsORDER BY price DESC
LIMITRestrict row countLIMIT 10
OFFSETSkip rowsOFFSET 20
Note: Combine LIMIT and OFFSET to page through large result sets, for example LIMIT 10 OFFSET 20 returns rows 21 through 30.
Note: Without an ORDER BY clause, PostgreSQL does not guarantee any particular row order, even if the results appear consistent during testing. Always add ORDER BY when row order matters.

Exercise: PostgreSQL Fetch Data

When combining LIMIT and OFFSET, what does OFFSET control?