SQL Filtering and Ordering - Employee Query

easySQL

Lesson

SQL Filtering with WHERE and Ordering with ORDER BY

SQL queries become powerful when you can filter data to find exactly what you need and present it in a meaningful order. Two essential clauses make this possible: WHERE for filtering and ORDER BY for sorting.

The WHERE Clause

The WHERE clause acts like a filter, allowing only rows that meet specific conditions to be included in your results. You can use various operators:

  • = for exact matches
  • >, <, >=, <= for comparisons
  • AND, OR for combining conditions
  • LIKE for pattern matching

When working with multiple conditions, AND requires all conditions to be true, while OR requires at least one condition to be true.

The ORDER BY Clause

The ORDER BY clause sorts your results based on one or more columns. By default, sorting is ascending (smallest to largest, A to Z), but you can specify DESC for descending order (largest to smallest, Z to A).

Combining Filters and Sorting

These clauses work together seamlessly. The database first applies the WHERE filter to select matching rows, then sorts those results according to your ORDER BY specification. This two-step process ensures you get exactly the data you want in the order that makes most sense for your use case.

Remember that string values in SQL must be enclosed in single quotes, and date comparisons work intuitively with ISO format dates (YYYY-MM-DD).

Example
1-- Find all products in the 'Electronics' category priced over $100, 2-- ordered by price from highest to lowest 3SELECT name, category, price 4FROM products 5WHERE category = 'Electronics' AND price > 100 6ORDER BY price DESC;
L3WHERE clause filters for Electronics products over $100
L4AND combines both conditions - both must be true
L5ORDER BY DESC sorts by price from highest to lowest

Key Takeaways

  • •Use WHERE with AND to apply multiple filter conditions simultaneously
  • •ORDER BY with DESC sorts results in descending order (largest first)
  • •String values in SQL conditions must be enclosed in single quotes
Loading...