MySQL Where

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 201 of 256

Filtering Rows With WHERE

In simple terms: Usually you do not want all rows from a table — you want the products in one category, the orders of one customer, or the items cheaper than ₹1,000. The WHERE clause tells the database which rows to return (or update, or delete), so only matching data is processed and sent to PHP.

Technically: WHERE takes a condition that is evaluated for every row; only rows for which it is true are included. Conditions use comparison operators, BETWEEN, IN, LIKE, IS NULL, and logical operators AND, OR, NOT. Whenever a condition contains values from outside the code, they must be passed as prepared statement parameters (see MySQL Prepared).

The examples use the products from MySQL Insert Multiple:

idskunamepricestockcategory
1PEN-01Gel Pen20.00120stationery
2NB-A5Notebook A560.0045stationery
3LAMP-01Desk Lamp1299.008electronics
4BAG-02Backpack899.000bags
5MOUSE-01Wireless Mouse599.0025electronics

A Basic WHERE Clause

<?php
require __DIR__ . '/src/db.php';

$category = 'electronics';   // e.g. from $_GET['category']

$result = db()->execute_query(
    'SELECT name, price FROM products WHERE category = ? ORDER BY id',
    [$category]
);

foreach ($result as $row) {
    echo "{$row['name']}: ₹{$row['price']}\n";
}

Output

Desk Lamp: ₹1299.00
Wireless Mouse: ₹599.00

The ? placeholder receives the category value. MySQL compares each row's category with it and returns only the matches. Because the table uses a case-insensitive collation, 'Electronics' would match too.


Comparison Operators

OperatorMeaningExample
=Equalcategory = ?
<> or !=Not equalstatus <> 'cancelled'
<, <=, >, >=Less / greater thanstock > 0
BETWEEN a AND bWithin a range (inclusive)price BETWEEN ? AND ?
IN (...)Matches one of several valuessku IN (?, ?, ?)
LIKEPattern match (% = any characters, _ = one character)name LIKE ?
IS NULL / IS NOT NULLMissing / present valuecity IS NULL

Ranges With BETWEEN

<?php
require __DIR__ . '/src/db.php';

$result = db()->execute_query(
    'SELECT name, price FROM products WHERE price BETWEEN ? AND ? ORDER BY id',
    [50, 900]
);

foreach ($result as $row) {
    echo "{$row['name']}: ₹{$row['price']}\n";
}

Output

Notebook A5: ₹60.00
Backpack: ₹899.00
Wireless Mouse: ₹599.00

BETWEEN 50 AND 900 includes both limits (equivalent to price >= 50 AND price <= 900).


Searching Text With LIKE

<?php
require __DIR__ . '/src/db.php';

function likePattern(string $term): string
{
    return '%' . addcslashes($term, '%_\\') . '%';
}

foreach (['lamp', 'pen', '100%'] as $term) {
    $names = array_column(
        db()->execute_query('SELECT name FROM products WHERE name LIKE ? ORDER BY id', [likePattern($term)])->fetch_all(MYSQLI_ASSOC),
        'name'
    );

    echo str_pad("'$term'", 8) . '→ ' . ($names === [] ? 'no results' : implode(', ', $names)) . "\n";
}

Output

'lamp'  → Desk Lamp
'pen'   → Gel Pen
'100%'  → no results

How It Works

  1. % around the term means "any characters before and after", so %lamp% matches "Desk Lamp" (case-insensitively).
  2. % and _ are wildcards in LIKE. If a user searches for 100%, the % would otherwise match anything. addcslashes() escapes %, _, and `` with a backslash, so they are matched literally.
  3. The pattern is still passed as a parameter, never inserted into the SQL.

LIKE '%term%' cannot use a normal index, so it scans the whole table. That is fine for small tables; for large catalogs, use MySQL's FULLTEXT indexes or a search engine.


Combining Conditions: AND, OR, and Parentheses

AND binds more tightly than OR — just as multiplication binds more tightly than addition. Missing parentheses are a classic source of bugs:

<?php
require __DIR__ . '/src/db.php';

$db = db();

$withoutParentheses = "SELECT name FROM products
    WHERE category = 'stationery' OR category = 'electronics' AND stock > 50
    ORDER BY id";

$withParentheses = "SELECT name FROM products
    WHERE (category = 'stationery' OR category = 'electronics') AND stock > 50
    ORDER BY id";

foreach (['Without' => $withoutParentheses, 'With' => $withParentheses] as $label => $sql) {
    $names = array_column($db->query($sql)->fetch_all(MYSQLI_ASSOC), 'name');
    echo "$label parentheses: " . implode(', ', $names) . "\n";
}

Output

Without parentheses: Gel Pen, Notebook A5
With parentheses: Gel Pen

Without parentheses, MySQL reads the condition as "stationery (any stock) OR (electronics with stock > 50)", so the Notebook with only 45 in stock is included. The intended rule — "stationery or electronics, and more than 50 in stock" — requires parentheses. Always use parentheses when mixing AND and OR.


NULL Needs Special Operators

NULL means "unknown". Any comparison with NULL using =, <>, <, or > results in "unknown", which is treated as not true:

SELECT name FROM customers WHERE city = NULL;      -- always returns no rows
SELECT name FROM customers WHERE city IS NULL;     -- customers without a city
SELECT name FROM customers WHERE city IS NOT NULL; -- customers with a city

When a PHP value may be null (for example, an optional filter), the null-safe equality operator <=> compares correctly in both cases: city <=> ? matches NULL when the parameter is null, and matches the city otherwise.


Practical Example: Optional Search Filters

A product search page offers optional filters — category, maximum price, in-stock only, and a search term. The WHERE clause is built from the filters that are actually set, always with placeholders:

<?php
require __DIR__ . '/src/db.php';

function findProducts(mysqli $db, array $filters): array
{
    $conditions = [];
    $params = [];

    if (($filters['category'] ?? '') !== '') {
        $conditions[] = 'category = ?';
        $params[] = $filters['category'];
    }

    if (isset($filters['max_price'])) {
        $conditions[] = 'price <= ?';
        $params[] = $filters['max_price'];
    }

    if (!empty($filters['in_stock'])) {
        $conditions[] = 'stock > 0';
    }

    if (($filters['search'] ?? '') !== '') {
        $conditions[] = 'name LIKE ?';
        $params[] = '%' . addcslashes($filters['search'], '%_\\') . '%';
    }

    $where = $conditions === [] ? '' : 'WHERE ' . implode(' AND ', $conditions);

    $result = $db->execute_query(
        "SELECT name FROM products $where ORDER BY id",
        $params === [] ? null : $params
    );

    return array_column($result->fetch_all(MYSQLI_ASSOC), 'name');
}

$db = db();

echo implode(', ', findProducts($db, ['category' => 'electronics', 'max_price' => 1000, 'in_stock' => true])) . "\n";
echo implode(', ', findProducts($db, ['search' => 'note'])) . "\n";
echo implode(', ', findProducts($db, [])) . "\n";

Output

Wireless Mouse
Notebook A5
Gel Pen, Notebook A5, Desk Lamp, Backpack, Wireless Mouse

Step-by-Step Explanation

  1. Each active filter adds a condition with placeholders (or a fixed condition such as stock > 0) and, where needed, a parameter.
  2. Conditions are combined with AND. Only fixed SQL fragments written in the code are concatenated; all user values go into $params.
  3. Without filters, there is no WHERE clause and all products are returned. In that case, null is passed instead of an empty array, because MySQLi rejects an empty parameter array with a ValueError.
  4. In the first call, the Desk Lamp (₹1,299) is excluded by the price limit, leaving only the Wireless Mouse.

In real code, the filter values would come from $_GET after validation — for example, max_price with FILTER_VALIDATE_FLOAT (see PHP Filters).


Performance: WHERE and Indexes

WriteInstead ofWhy
created_at >= '2026-10-01' AND created_at < '2026-11-01'MONTH(created_at) = 10Applying a function to a column prevents index use
sku = ? on an indexed columnLOWER(sku) = ?The collation is already case-insensitive
name LIKE 'desk%'name LIKE '%desk%' when a prefix search is enoughA leading % prevents index use

Columns that appear frequently in WHERE clauses (foreign keys, status, dates) should be indexed (see MySQL Create Table).


Common Mistakes

Inserting Values Into the WHERE Clause

Effect: SQL injection.

Fix: Always use placeholders.

Mixing AND and OR Without Parentheses

Effect: Wrong rows are returned.

Fix: Group conditions explicitly.

Using = NULL

Effect: No rows match.

Fix: Use IS NULL, IS NOT NULL, or <=>.

Not Escaping LIKE Wildcards

Effect: Searches for % or _ match unexpected rows.

Fix: Escape them with addcslashes($term, '%_0').


Best Practices

  • Filter in the database with WHERE instead of loading all rows into PHP.
  • Pass every external value as a prepared-statement parameter.
  • Use parentheses whenever AND and OR are combined.
  • Handle NULL with IS NULL / <=>.
  • Write conditions that can use indexes, and index frequently filtered columns.

Official reference: https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about MySQL Where and get answers drawn from it.

Signed-in readers only.