Filtering & Sorting Data using SQL
Once you know the basics (SELECT, FROM, WHERE), filtering
and sorting helps you get the exact rows from tables .
- Use WHERE to filter rows.
- Combine with logical operators:
• AND: all
conditions true
• OR: any condition true
• NOT: negate condition
-- All conditions true (AND)
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
-- Any condition true (OR)
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
-- Negate condition (NOT)
SELECT * FROM employees
WHERE NOT department = 'HR';
- % = any sequence, _ = single char
• Names starting
with 'J'
• Names with 4 letters starting with 'J'
-- Names starting with 'J'
SELECT * FROM customers
WHERE name LIKE 'J%';
-- Names with four letters starting with 'J'
SELECT * FROM customers
WHERE name LIKE 'J___';
- Check if value matches any in list
SELECT * FROM
products WHERE category IN ('Electronics', 'Furniture');
4. Range Checking with BETWEEN
- Filter values in a range (inclusive)
SELECT * FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
- Find NULL:
SELECT * FROM
employees WHERE manager_id IS NULL;
- Find NOT NULL:
SELECT * FROM
employees WHERE manager_id IS NOT NULL;
- Ascending (default):
SELECT * FROM
employees ORDER BY salary;
- Descending:
SELECT * FROM
employees ORDER BY salary DESC;
SELECT * FROM
employees ORDER BY department, salary DESC;
No comments:
Post a Comment