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, departmentFROM employees;
-
Retrieves the
first_name,last_name, anddepartmentcolumns from theemployeestable. -
If you want all columns, use
*:
SELECT *FROM employees;2. Filtering Data with WHERE
Often, you don’t want all the rows. The
WHEREclause filters data based on conditions.SELECT first_name, last_name, departmentFROM employeesWHERE department = 'Sales';
Only shows employees in the Sales department.
Conditions can use operators like
=,>,<,>=,<=,!=.Example: Filtering by Number
SELECT first_name, salaryFROM employeesWHERE 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, salaryFROM employeesWHERE department = 'Sales' AND salary > 50000;
Returns employees in Sales with salary over 50,000.
SELECT first_name, last_name, departmentFROM employeesWHERE department = 'Sales' OR department = 'Marketing';
Returns employees in Sales or Marketing.
4. Sorting Data with ORDER BY
The
ORDER BYclause lets you sort results:SELECT first_name, last_name, salaryFROM employeesORDER BY salary DESC;
Sorts employees by salary in descending order.
Use
ASCfor ascending (default).5. Limiting Results
Sometimes, you only want the top few results:
SELECT first_name, last_name, salaryFROM employeesORDER BY salary DESCLIMIT 5;
Shows the top 5 highest-paid employees.
6. Using LIKE for Pattern Matching
LIKEallows you to search for patterns:SELECT first_name, last_nameFROM employeesWHERE 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
Post a Comment