The Read operation in CRUD refers to retrieving data stored in a database. In relational databases, data retrieval is performed primarily using the SQL SELECT statement.
The SELECT command allows developers to query tables, filter rows, sort results, and combine data from multiple tables.
While most relational databases follow the ANSI SQL standard, systems like PostgreSQL extend it with additional features such as LIMIT and DISTINCT ON, making data retrieval more flexible and efficient.
Understanding these read operations is essential for building applications that rely on structured data stored in relational databases.
The simplest read operation retrieves all rows from a table.
ANSI SQL syntax:
Example using the web shop database:
This query returns all columns and rows stored in the customer table.
However, using * is generally discouraged in production systems because it retrieves unnecessary data and can reduce performance.
Instead of selecting all columns, it is better to specify exactly which fields are needed.
Syntax:
Example:
This query retrieves only the firstname, lastname and email columns from the table.
Often, applications need only a subset of records. The WHERE clause filters rows based on conditions.
Syntax:
Example:
This query returns only entries from address where the city is Oxford.
Logical operators such as AND, OR, and NOT can also be used to combine conditions.
Query results can be sorted using the ORDER BY clause.
Syntax:
Example:
ASC sorts results in ascending order (default), while DESC sorts them in descending order.
Large datasets often require returning only a subset of results.
PostgreSQL supports the LIMIT clause:
This query returns only the first 10 rows.
Using OFFSET:
This retrieves 10 rows starting from the 21st row.
The ANSI SQL standard uses FETCH FIRST instead of LIMIT.
Many modern databases support both approaches, but LIMIT is commonly used in PostgreSQL.
Relational databases allow combining data from different tables using JOIN operations.
Example:
This query retrieves customer last names along with their corresponding orders and total amounts.
** Note: In PostgreSQL, "order" is a reserved keyword (used in ORDER BY), so it must be enclosed in double quotes when used as a table or column name.
Common join types include:
While most read operations follow the ANSI SQL standard, PostgreSQL provides additional capabilities.
PostgreSQL allows selecting unique rows based on a specific column using DISTINCT ON.
This retrieves the most recent order for each customer. This feature is not part of the ANSI SQL standard.
** As noted before, the "order" table name must be quoted.
Although primarily used in INSERT, UPDATE, and DELETE, PostgreSQL allows returning rows affected by those operations.
This immediately returns the updated row.
+48 790-430-860
analysislessons@gmail.com