PostgreSQL SELECT
Overview
The SELECT statement is used to query data from one or more tables. It is the most commonly used SQL statement and forms the foundation of data retrieval in PostgreSQL.
Basic SELECT Syntax
Select All Columns
Select Specific Columns
Column Aliases
Expressions in SELECT
DISTINCT - Remove Duplicates
What is DISTINCT?
The DISTINCT keyword is used to remove duplicate rows from query results. It returns only unique values from the specified columns.
Basic Syntax
Single Column DISTINCT
Multiple Column DISTINCT
When using DISTINCT with multiple columns, PostgreSQL considers the combination of all specified columns to determine uniqueness.
DISTINCT with Aggregate Functions
DISTINCT ON (PostgreSQL-Specific)
DISTINCT ON returns the first row for each unique value in the specified column(s).
DISTINCT Performance Optimization
DISTINCT with JOINs
NULL Handling
DISTINCT treats NULL values as equal:
Common Mistakes
Calculated Fields
Selecting from Multiple Tables
Subqueries in SELECT
SELECT with Functions
SELECT with LIMIT
SELECT with ORDER BY
SELECT with WHERE
SELECT with GROUP BY
SELECT with HAVING
Complete SELECT Example
Best Practices
Common Patterns
Pagination
Top N Records
Conditional Selection
Summary
The SELECT statement is fundamental to PostgreSQL:
- Basic:
SELECT columns FROM table - Filtering: Use WHERE clause
- Sorting: Use ORDER BY clause
- Grouping: Use GROUP BY with aggregates
- Limiting: Use LIMIT and OFFSET
- Aliases: Improve readability
- Functions: Transform and aggregate data