🐘 PostgreSQL Tutorial

SELECT and WHERE in PostgreSQL: Querying and Filtering Rows

Learn PostgreSQL's SELECT statement — choosing columns, aliasing them, and filtering rows with the WHERE clause using comparison and logical operators.

SELECT and WHERE

SELECT is how you read data out of PostgreSQL — the equivalent of MongoDB's find().

Selecting Columns

SELECT * FROM employees;              -- every column
SELECT name, salary FROM employees;   -- specific columns only

Aliasing Columns and Tables

SELECT name AS employee_name, salary AS annual_salary
FROM employees AS e;

Filtering with WHERE

SELECT * FROM employees WHERE department = 'Engineering';

SELECT * FROM employees WHERE salary > 50000;

SELECT * FROM employees WHERE salary >= 50000 AND department = 'Engineering';

SELECT * FROM employees WHERE department = 'HR' OR department = 'Sales';

SELECT * FROM employees WHERE NOT department = 'HR';

Comparison Operators

Operator Meaning
= Equal
<> or != Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Computed Columns

You can select an expression, not just a raw column:

SELECT name, salary, salary * 12 AS annual_salary
FROM employees;

DISTINCT — Remove Duplicate Rows

SELECT DISTINCT department FROM employees;

Common Errors & Troubleshooting

  • ERROR: column "e.name" must appear in the GROUP BY clause — this happens when you accidentally reuse a query pattern from an aggregate query without actually grouping — remove the unrelated aggregate function, or add the column to GROUP BY.
  • String comparisons behaving case-sensitively when you expected otherwise — = and LIKE are case-sensitive by default in PostgreSQL; use ILIKE or wrap both sides in LOWER() for case-insensitive matching (see the Filtering Operators lesson).
  • ERROR: operator does not exist: integer = text — you compared a numeric column against a quoted string; drop the quotes (WHERE id = 5, not WHERE id = '5') or explicitly cast if needed.

Key Takeaways

  • SELECT chooses which columns come back; WHERE chooses which rows do.
  • AS renames a column or table for the duration of the query — purely cosmetic, doesn't change the data.
  • DISTINCT collapses duplicate rows in the result down to one each.