Retrieving and Filtering Data in SQL

 

Retrieving and Filtering Data in SQL

We introduced SQL and why it’s essential. Now it’s time to get hands-on! In this blog, we’ll explore how to retrieve specific data from a database and filter it based on conditions. By the end, you’ll be writing your own SQL queries like a pro.

1. Retrieving Data with SELECT

The SELECT statement is the foundation of SQL queries. It tells the database which columns you want to see.

SELECT first_name, last_name, department
FROM employees;
  • Retrieves the first_name, last_name, and department columns from the employees table.

  • If you want all columns, use *:

SELECT *
FROM employees;

2. Filtering Data with WHERE

Often, you don’t want all the rows. The WHERE clause filters data based on conditions.

SELECT first_name, last_name, department
FROM employees
WHERE department = 'Sales';
  • Only shows employees in the Sales department.

  • Conditions can use operators like =, >, <, >=, <=, !=.

Example: Filtering by Number

SELECT first_name, salary
FROM employees
WHERE salary > 50000;
  • Returns employees earning more than 50,000.

3. Combining Conditions

Use AND / OR to combine multiple conditions:

SELECT first_name, last_name, department, salary
FROM employees
WHERE department = 'Sales' AND salary > 50000;
  • Returns employees in Sales with salary over 50,000.

SELECT first_name, last_name, department
FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
  • Returns employees in Sales or Marketing.

4. Sorting Data with ORDER BY

The ORDER BY clause lets you sort results:

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
  • Sorts employees by salary in descending order.

  • Use ASC for ascending (default).

5. Limiting Results

Sometimes, you only want the top few results:

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
  • Shows the top 5 highest-paid employees.

6. Using LIKE for Pattern Matching

LIKE allows you to search for patterns:

SELECT first_name, last_name
FROM employees
WHERE first_name LIKE 'J%';
  • Returns names starting with J (John, Jane…).

  • % – any sequence of characters.

  • _ – single character wildcard.

By now, you can:

  • Select specific columns.

  • Filter rows using WHERE.

  • Combine conditions with AND / OR.

  • Sort results using ORDER BY.

  • Search with patterns using LIKE.

These are the building blocks of all SQL queries, and mastering them will make analyzing data much easier.


Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling