SQL•Filtering
SQL WHERE Filtering: Comparison and Logical Operators (AND, OR, IN)
The WHERE clause restricts rows returned by a query, filtering data based on boolean criteria.
Syntax
SELECT * FROM table WHERE condition1 AND condition2;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| WHERE | Clause | Filters rows before aggregation. |
| IN | Operator | Matches any value in a list of literals. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT,
price REAL,
category TEXT
);
INSERT INTO products VALUES
(1, 'Mechanical Keyboard', 120.00, 'Hardware'),
(2, 'Wireless Mouse', 45.50, 'Hardware'),
(3, 'USB Cable', 9.99, 'Accessories'),
(4, '4K Monitor', 380.00, 'Hardware');
-- Filter hardware products priced between $40 and $200
SELECT name, price, category
FROM products
WHERE category = 'Hardware' AND price BETWEEN 40.00 AND 200.00;Expected Output:
name price category ------------------- ----- -------- Mechanical Keyboard 120.0 Hardware Wireless Mouse 45.5 Hardware
How It Works: Step-by-Step
- Lines 1-12: Sets up products schema with sample prices.
- Lines 15-17: WHERE applies logical AND with BETWEEN range check.
Key Concepts
- BETWEEN min AND max is inclusive in SQL.
- Strings are enclosed in single quotes 'Hardware' in standard SQL.
- Use IS NULL instead of = NULL when checking for missing data.
Common Mistake: Comparing NULL values with = NULL instead of IS NULL
In SQL, NULL = NULL evaluates to UNKNOWN. You must write column IS NULL.
❌ Incorrect
WHERE deleted_at = NULL; // Never matches anything!
✅ Correct
WHERE deleted_at IS NULL; // Correct null check
Related SQL Tutorials & Compiler
SQL Session-Level Variable Mapping Constraints and CTE Declarations
Define and map session-level variables, CTE bind parameters, and column expressions in SQL queries.
SQL ORDER BY, LIMIT, and OFFSET for Pagination
Sort rows with ORDER BY (ASC, DESC) and paginate results using LIMIT and OFFSET.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.