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 |
Advertisement728 x 90
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 toGROUP BY.- String comparisons behaving case-sensitively when you expected otherwise —
=andLIKEare case-sensitive by default in PostgreSQL; useILIKEor wrap both sides inLOWER()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, notWHERE id = '5') or explicitly cast if needed.
Key Takeaways
SELECTchooses which columns come back;WHEREchooses which rows do.ASrenames a column or table for the duration of the query — purely cosmetic, doesn't change the data.DISTINCTcollapses duplicate rows in the result down to one each.
Advertisement320 x 100