Chapter 18: PostgreSQL Select Data

Part 1: What is the SELECT Statement?

At its core, the SELECT statement is how you retrieve data from a PostgreSQL database . It’s the “R” in CRUD (Create, Read, Update, Delete) operations. When you use SELECT, you’re asking the database to show you specific information from one or more tables, and it returns that information in a result table called a result set .

The Simplest Form

The most basic SELECT statement has two main parts :

sql

  • SELECT: Specifies what columns or calculated values you want to see

  • FROM: Specifies which table(s) to get the data from

A Complete Breakdown

Here’s a more complete picture of what a SELECT statement can include :

sql

Don’t worry if this looks overwhelming – we’ll build up to this step by step!

Part 2: Basic SELECT Queries

Let’s start with the fundamentals. Imagine we have a simple table called products:

sql

1. SELECT All Columns

To see everything in a table, use the asterisk (*) shorthand :

sql

Result:

id name category price in_stock created_date
1 Laptop Electronics 999.99 true 2024-01-15
2 Desk Chair Furniture 249.50 true 2024-01-20
3 Coffee Maker Appliances 79.99 false 2024-02-01
4 Notebook Office Supplies 4.99 true 2024-02-10
5 Desk Lamp Furniture 45.00 true 2024-02-15
6 Mouse Electronics 29.99 true 2024-02-20
7 Paper Clips Office Supplies 2.50 true 2024-02-25
8 Blender Appliances 129.99 false 2024-03-01

⚠️ Important Note: While SELECT * is convenient for quick exploration, it’s considered bad practice in production code . If your table structure changes (columns added or removed), your application might break unexpectedly. Always specify exactly the columns you need.

2. SELECT Specific Columns

To retrieve only certain columns, list them after SELECT :

sql

Result:

name price
Laptop 999.99
Desk Chair 249.50
Coffee Maker 79.99
Notebook 4.99
Desk Lamp 45.00
Mouse 29.99
Paper Clips 2.50
Blender 129.99

This is more efficient – the database only retrieves the data you actually need.

3. SELECT with Expressions and Calculations

You’re not limited to just column names – you can use expressions and calculations :

sql

Result:

name price price_with_tax sale_price
Laptop 999.99 1099.989 799.992
Desk Chair 249.50 274.45 199.60

The AS keyword creates an alias – a temporary name for the calculated column . This makes your results much more readable.

4. SELECT Without a Table (Using PostgreSQL as a Calculator)

Here’s a fun fact – you don’t always need a table! PostgreSQL can evaluate expressions directly :

sql

Result:

multiplication today uppercase random_number
18 2025-02-13 HELLO WORLD 73.4567

This is incredibly useful for testing functions or performing quick calculations.

5. Concatenating Columns

You can combine columns using the concatenation operator || :

sql

Result:

name product_description
Laptop Product: Laptop – $999.99
Desk Chair Product: Desk Chair – $249.50

Part 3: Filtering Data with WHERE

The real power of SELECT comes when you start filtering. The WHERE clause lets you specify conditions that rows must meet to be included .

1. Basic Equality Filter

sql

Result:

name price in_stock
Laptop 999.99 true
Mouse 29.99 true

2. Comparison Operators

You can use all the usual comparison operators :

sql

Result:

name price
Laptop 999.99
Desk Chair 249.50
Blender 129.99

3. Multiple Conditions with AND/OR

Combine conditions using logical operators :

sql

Result:

name price category
Laptop 999.99 Electronics
Mouse 29.99 Electronics
sql

Result:

name category price
Desk Chair Furniture 249.50
Notebook Office Supplies 4.99
Desk Lamp Furniture 45.00
Paper Clips Office Supplies 2.50

4. Range Conditions with BETWEEN

For ranges, BETWEEN is cleaner than using >= and <= :

sql

Result:

name price
Desk Lamp 45.00
Mouse 29.99

This is equivalent to price >= 50 AND price <= 200.

5. Pattern Matching with LIKE

Use LIKE for text pattern matching :

sql

Result:

name category
Desk Chair Furniture
Desk Lamp Furniture
  • % matches any sequence of characters

  • _ matches a single character

6. List Matching with IN

When you need to match against multiple values :

sql

Result:

name category price
Laptop Electronics 999.99
Coffee Maker Appliances 79.99
Mouse Electronics 29.99
Blender Appliances 129.99

7. Handling NULL Values

NULL represents missing or unknown data. You can’t use = with NULL – you need special operators :

sql

Result:

name price
Sample Product NULL

Note: Use IS NULL or IS NOT NULL, never = NULL.

Part 4: Removing Duplicates with DISTINCT

Sometimes you only want to know the unique values in a column :

sql

Result:

category
Appliances
Electronics
Furniture
Misc
Office Supplies

The DISTINCT keyword removes duplicate rows from your result set. For multiple columns, it considers the combination of all columns:

sql

Part 5: Sorting Results with ORDER BY

Data often comes back in unpredictable order. ORDER BY lets you control the sorting :

1. Ascending Order (Default)

sql

Result (ascending by price):

name price
Paper Clips 2.50
Notebook 4.99
Mouse 29.99
Desk Lamp 45.00
Coffee Maker 79.99
Blender 129.99
Desk Chair 249.50
Laptop 999.99

2. Descending Order

sql

Result (descending by price):

name price
Laptop 999.99
Desk Chair 249.50
Blender 129.99
Coffee Maker 79.99
Desk Lamp 45.00
Mouse 29.99
Notebook 4.99
Paper Clips 2.50

3. Multiple Sort Columns

sql

This sorts first by category (alphabetically), then within each category by price (highest first):

name category price
Blender Appliances 129.99
Coffee Maker Appliances 79.99
Laptop Electronics 999.99
Mouse Electronics 29.99
Desk Chair Furniture 249.50
Desk Lamp Furniture 45.00
Sample Product Misc NULL
Notebook Office Supplies 4.99
Paper Clips Office Supplies 2.50

Part 6: Limiting Results with LIMIT and OFFSET

When working with large tables, you often want only a subset of rows :

1. Get Top N Records

sql

Result:

name price
Laptop 999.99
Desk Chair 249.50
Blender 129.99

2. Pagination with OFFSET

Use OFFSET to skip a certain number of rows :

sql

Result:

name price
Coffee Maker 79.99
Desk Lamp 45.00
Mouse 29.99

This is perfect for implementing pagination in applications!

Part 7: Grouping and Aggregation

Sometimes you need summary statistics rather than individual rows :

1. Basic Aggregation Functions

sql

Result:

total_products average_price highest_price lowest_price products_in_stock
8 192.24375 999.99 2.50 6

2. Grouping with GROUP BY

To get these statistics per category :

sql

Result:

category products_in_category avg_price max_price min_price
Electronics 2 514.99 999.99 29.99
Furniture 2 147.25 249.50 45.00
Appliances 2 104.99 129.99 79.99
Office Supplies 2 3.745 4.99 2.50

3. Filtering Groups with HAVING

HAVING is like WHERE but for groups :

sql

Result:

category products_in_category avg_price
Electronics 2 514.99
Furniture 2 147.25

This shows only categories where the average price exceeds $100.

Part 8: Joining Tables – The Real Power

Real databases have multiple related tables. JOIN lets you combine them :

Let’s add a related table:

sql

INNER JOIN – Only Matching Rows

sql

Result:

product_name price category_name description
Laptop 999.99 Electronics Gadgets and electronic devices
Desk Chair 249.50 Furniture Items for furnishing your space
Blender 129.99 Appliances Home and kitchen appliances
Coffee Maker 79.99 Appliances Home and kitchen appliances

This combines product information with category details.


Part 9: Putting It All Together – Real-World Examples

Let’s see how these pieces work together in practical scenarios:

Example 1: Product Catalog with Pagination

sql

Example 2: Sales Dashboard Summary

sql

Example 3: Inventory Check

sql

Part 10: Best Practices and Performance Tips

DO:

  1. Specify columns explicitly – Never use SELECT * in production

  2. Use meaningful aliases – Make your results readable

    sql

  3. Filter early – Use WHERE to reduce data before joins and aggregations

  4. Index columns used in WHERE, JOIN, and ORDER BY – Dramatically improves performance

  5. Use appropriate data types – Don’t store numbers as text

DON’T:

  1. Don’t use SELECT DISTINCT as a crutch – It often hides poor query design

  2. Don’t overuse subqueries – Sometimes joins are more efficient

  3. Don’t forget NULL handling – NULLs behave unexpectedly in comparisons

  4. Don’t assume sort order – Always use ORDER BY if order matters

Understanding Query Execution Order

It’s crucial to understand that SQL is written in one order but executed in another:

  1. FROM (including JOINs) – Identify tables

  2. WHERE – Filter rows

  3. GROUP BY – Form groups

  4. HAVING – Filter groups

  5. SELECT – Choose columns and calculate expressions

  6. ORDER BY – Sort results

  7. LIMIT/OFFSET – Limit output

This explains why you can’t use column aliases from SELECT in WHERE – the alias doesn’t exist yet when WHERE is evaluated!

Summary: The SELECT Statement Philosophy

The SELECT statement is your primary tool for conversation with your database. It’s how you ask questions and get answers. Master these concepts in order:

  1. Simple Selection – Get specific columns

  2. Filtering – Narrow down to relevant rows

  3. Sorting – Organize results meaningfully

  4. Aggregation – Summarize and analyze

  5. Joining – Connect related data

  6. Combining – Use all features together

Every great SQL query starts with understanding what question you’re asking your data. The SELECT statement is simply the grammar you use to phrase that question precisely.

Remember: The database will give you exactly what you ask for – no more, no less. Learning to ask the right way is the art and science of working with PostgreSQL.

Would you like me to elaborate on any specific aspect of SELECT queries, such as more advanced join types, subqueries, window functions, or performance optimization?

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *