SQL:SQL WHERE Filtering: Comparison and Logical Operators (AND, OR, IN)
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:

ParameterTypeDescription
WHEREClauseFilters rows before aggregation.
INOperatorMatches any value in a list of literals.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler