PostgreSQL Fetch Data

PostgreSQL Fetch Data

Once data is successfully inserted into a database, you must be able to retrieve it. Fetching data is universally the most common operation performed on any database.

We use the SELECT statement to query the database and return a formatted result set. This allows applications to securely read information without accidentally altering it.

The Basics of Fetching

To fetch data, you must explicitly declare which columns you wish to retrieve. You use the SELECT keyword followed by the targeted columns, and the FROM table.

If you want to quickly fetch absolutely every column, you can use the asterisk *. However, fetching specific columns is vastly superior for overall application performance.

Basic Fetch Example:

-- Fetch only the names and emails of all users
SELECT Username, Email
FROM Users;

Filtering Fetched Data

Fetching an entire table containing millions of rows is dangerously inefficient. You should always utilize the WHERE clause to rigorously filter the fetched data.

This securely guarantees that only relevant, strictly necessary rows are returned over the network. You can filter by exact text matches, numeric ranges, or chronological date stamps.

Filtered Fetch Example:

-- Fetch users who specifically registered from Canada
SELECT Username, Email
FROM Users
WHERE Country = 'Canada';

Sorting Fetched Data

Data inherently sits in a database without any guaranteed structural order. To fetch data alphabetically or chronologically, you must use ORDER BY.

You can precisely sort the fetched results in ascending (ASC) or descending (DESC) order. This cleanly formats the data payload before it even reaches your frontend application.

Sorted Fetch Example:

-- Fetch all users, sorted alphabetically by their Username
SELECT * FROM Users
ORDER BY Username ASC;

Limiting Fetched Results

Sometimes you only want to fetch a tiny handful of results, like the "Top 5". The LIMIT clause aggressively restricts the maximum number of rows fetched natively.

This is crucially important when developing scalable websites with pagination features. It completely prevents memory crashes by capping the returned dataset cleanly.

Limited Fetch Example:

-- Fetch the top 3 oldest users securely
SELECT * FROM Users
ORDER BY Age DESC
LIMIT 3;

Summary

Fetching data intelligently is the absolute cornerstone of backend development. Avoid using SELECT * in production to minimize massive memory consumption.

Always filter with WHERE and restrict sizes with LIMIT for blazing-fast APIs.

Exercise

Which keyword is actively used to forcefully restrict the number of rows fetched?