# Exploring Further Methods of SQL Data Retrieval

### Sorting Data with `ORDER BY`

We don’t always want our results in the order they are stored in the database. The `ORDER BY` clause lets us sort the data based on one or more columns, either in ascending (default) or descending order.

#### Example: Sorting Users by Age (Oldest to Youngest)

```sql
SELECT username, age 
FROM users
ORDER BY age DESC;
```

By adding `DESC`, we’re telling SQL to sort the results in descending order (oldest first). Without `DESC`, the results would be sorted in ascending order (youngest first).

![SQL ORDER BY Clause (With Examples)](https://www.programiz.com/sites/tutorial2program/files/sql-order-by.png align="left")

### Limiting Results with `LIMIT`

If we are working with large datasets or just want to preview a small subset of our data, you can use the `LIMIT` clause to restrict the number of rows returned.

#### Example: Fetching the First 5 Users

```sql
SELECT * 
FROM users
LIMIT 5;
```

This query will return only the first 5 rows from the `users` table, regardless of how many rows are in the full dataset.

### Aliasing Columns with `AS`

Sometimes the default column names aren’t descriptive enough, or maybe they are just too long. Using `AS` allows us to rename columns in the output, making the results easier to read.

#### Example: Renaming Columns for Clarity

```sql
SELECT username AS user_name, email AS contact_email 
FROM users;
```

In this case, we’re renaming `username` to `user_name` and `email` to `contact_email` in the query results, which can be helpful for reporting or exporting data.

### Combining Multiple Concepts

We can combine filtering, sorting, and limiting in a single query to get exactly the data we need. Let’s say we want to find the top 3 oldest users who live in New York:

```sql
SELECT username, age 
FROM users
WHERE city = 'New York'
ORDER BY age DESC
LIMIT 3;
```

This query will:

1. Filter out users who don’t live in New York.
    
2. Sort the remaining users by age, from oldest to youngest.
    
3. Return only the top 3 results.
    

### Conclusion: Mastering `SELECT`

The `SELECT` statement is the foundation of SQL. Whether we are working with a simple database or managing complex queries, knowing how to select and retrieve the right data is critical. By mastering the `SELECT` statement and its accompanying clauses like `WHERE`, `DISTINCT`, `ORDER BY`, and `LIMIT` we gain the ability to work with our data effectively and efficiently.
