SQL WHERE Clause

SQL WHERE condition

The SQL WHERE clause filters rows by a condition. With SELECT, only rows where the condition evaluates as true are returned.

SELECT id, name, class, mark
FROM student
WHERE class = 'Four';

This returns students whose class value is Four.

idnameclassmark
1John DeoFour75
4Krish StarFour60
5John MikeFour60
6Alex JohnFour55
Full student table with SQL Dump

SQL WHERE Syntax Top ↑

SELECT column1, column2
FROM table_name
WHERE condition;

The condition is tested for each candidate row. Rows for which the condition is true are included in the result.

For example, to return students with marks greater than 70:

SELECT id, name, mark
FROM student
WHERE mark > 70;

WHERE is not limited to SELECT. It is also important with UPDATE and DELETE when only selected rows should be changed or removed.

Comparison Operators in WHERE Top ↑

Common comparison operators include:

OperatorMeaningExample
=Equalclass = 'Four'
<> or !=Not equalclass <> 'Four'
>Greater thanmark > 70
>=Greater than or equalmark >= 70
<Less thanmark < 50
<=Less than or equalmark <= 50
SQL Comparison Operators

Text, Numeric and Date Values Top ↑

String literals are normally enclosed in single quotes:

WHERE class = 'Four'

Numeric literals normally do not need quotes:

WHERE mark >= 70

Date literals are commonly written as quoted values in a format understood by the database:

WHERE join_date >= '2026-01-01'

The column datatype matters. Do not rely on automatic type conversion when the value can be supplied in the correct form.

Multiple WHERE Conditions with AND and OR Top ↑

Use AND when all conditions must be true. This query returns Class Four students with marks above 70:

SELECT id, name, class, mark
FROM student
WHERE class = 'Four'
  AND mark > 70;
idnameclassmark
1John DeoFour75
15Tade RowFour93
16GimmyFour93
31Marry ToeeyFour93

Use OR when either condition can be true:

SELECT id, name, class
FROM student
WHERE class = 'Four'
   OR class = 'Five';
When AND and OR are mixed, use parentheses to make the intended logic clear.
SELECT id, name, class, mark
FROM student
WHERE (class = 'Four' OR class = 'Five')
  AND mark >= 70;
SQL AND and OR Conditions

WHERE with BETWEEN Top ↑

BETWEEN tests an inclusive range. Both boundary values are included.

SELECT id, name, mark
FROM student
WHERE mark BETWEEN 60 AND 70;
idnamemark
4Krish Star60
5John Mike60
20Jackly65
21Babby John69
34Gain Toe69
SQL BETWEEN Tutorial

WHERE with LIKE Top ↑

LIKE performs pattern matching. The percent sign (%) matches any sequence of characters.

SELECT id, name
FROM student
WHERE name LIKE '%John%';

This matches names containing John anywhere in the value. Matching behavior such as case sensitivity can depend on the database and column collation.

SQL LIKE Tutorial

WHERE with IN and NOT IN Top ↑

IN is useful when the same column can match one of several values:

SELECT id, name, class
FROM student
WHERE class IN ('Four', 'Five');

To exclude those values:

SELECT id, name, class
FROM student
WHERE class NOT IN ('Four', 'Five');
SQL IN Tutorial

WHERE with NULL Values Top ↑

NULL represents a missing or unknown value. Do not test it with ordinary equality:

WHERE phone = NULL

Use IS NULL:

SELECT id, name
FROM student
WHERE phone IS NULL;

For rows where the value is present:

SELECT id, name
FROM student
WHERE phone IS NOT NULL;
SQL NULL Conditions

WHERE with Aggregate Queries Top ↑

WHERE can restrict the rows used by aggregate functions such as COUNT(), AVG(), MAX() and MIN().

Maximum mark in Class Three:

SELECT MAX(mark) AS max_mark
FROM student
WHERE class = 'Three';

Number of Class Four students with marks of at least 50:

SELECT COUNT(*) AS student_count
FROM student
WHERE class = 'Four'
  AND mark >= 50;

Several aggregates can be calculated from the same filtered rows:

SELECT COUNT(*) AS student_count,
       AVG(mark) AS average_mark,
       MAX(mark) AS highest_mark,
       MIN(mark) AS lowest_mark
FROM student
WHERE class = 'Three';

WHERE vs HAVING Top ↑

WHERE filters rows before grouping. HAVING filters grouped results after GROUP BY.

SELECT class, AVG(mark) AS average_mark
FROM student
WHERE mark >= 50
GROUP BY class
HAVING AVG(mark) > 70;

Here WHERE mark >= 50 decides which student rows participate in the groups. HAVING AVG(mark) > 70 then keeps only groups whose average is above 70.

SQL HAVING Tutorial

WHERE with a Subquery Top ↑

A subquery can supply a value used by the WHERE condition. To return every student tied for the highest mark:

SELECT id, name, mark
FROM student
WHERE mark = (
    SELECT MAX(mark)
    FROM student
);
SQL Subqueries

WHERE with UPDATE and DELETE Top ↑

WHERE is especially important with statements that modify data.

Increase marks by 5 for Class Five students:

UPDATE student
SET mark = mark + 5
WHERE class = 'Five';

Delete one student by ID:

DELETE FROM student
WHERE id = 10;
Check the WHERE condition before running destructive SQL. An UPDATE or DELETE without WHERE can affect every row in the table.
SQL UPDATE SQL DELETE

Use WHERE Values Safely with PHP PDO Top ↑

When the filter value comes from a form, URL or other external source, use a prepared statement instead of joining that value directly into SQL.

<?php
require 'config.php';

$class='Four';

$sql="SELECT id,name,class,mark
      FROM student
      WHERE class=:class
      ORDER BY id";

$stmt=$dbo->prepare($sql);
$stmt->bindValue(':class',$class,PDO::PARAM_STR);
$stmt->execute();

while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    $id=(int)$row['id'];
    $name=htmlspecialchars((string)$row['name'],ENT_QUOTES,'Windows-1252');
    $student_class=htmlspecialchars((string)$row['class'],ENT_QUOTES,'Windows-1252');
    $mark=(int)$row['mark'];

    echo "$id - $name - $student_class - $mark<br>";
}

Prepared statements handle SQL values safely. Application validation is still required when a value must follow rules such as an allowed range or known set of choices.

Fetching Records with PHP PDO

SQL WHERE Video Tutorial Top ↑

SELECT query with LIMIT, ORDER BY and WHERE conditions using BETWEEN

Common SQL WHERE Problems Top ↑

Using = NULL Top ↑

Use IS NULL or IS NOT NULL for NULL tests.

Mixing AND and OR without Parentheses Top ↑

Operator precedence can produce a different result from what the query author intended. Use parentheses to group related conditions.

Forgetting WHERE in UPDATE or DELETE Top ↑

Without WHERE, an UPDATE or DELETE can affect every row. Preview the target rows with SELECT when working with important data.

Using HAVING for an Ordinary Row Filter Top ↑

Use WHERE for normal row filtering. HAVING is primarily for conditions applied after grouping and aggregation.

Concatenating User Input into the Condition Top ↑

In application code, use prepared statements for external values. Do not build a WHERE condition by directly concatenating untrusted form or URL input.

Assuming LIKE Is Always Case Sensitive Top ↑

String comparison behavior can depend on the database and collation. Check the column/database collation when case-sensitive matching matters.

Filtering on a Calculated Aggregate with WHERE Top ↑

WHERE runs before grouped aggregate results are produced. Use HAVING when a condition depends on an aggregate result such as AVG(mark).

SQL SELECT AND / OR BETWEEN

LIKE IN NULL

UPDATE DELETE Subqueries

Frequently Asked Questions Top ↑

Q1: What does the SQL WHERE clause do?

WHERE filters rows according to a condition. With SELECT it restricts returned rows, and with UPDATE or DELETE it restricts which rows are modified or removed.

Q2: Can WHERE contain more than one condition?

Yes. Combine conditions with operators such as AND and OR, and use parentheses when needed to make the intended logic explicit.

Q3: How do I check for NULL in a WHERE clause?

Use IS NULL or IS NOT NULL. Ordinary comparisons such as = NULL do not correctly test for NULL.

Q4: What is the difference between WHERE and HAVING?

WHERE filters rows before grouping. HAVING filters grouped results after GROUP BY and is commonly used for conditions involving aggregate values.

Q5: Is BETWEEN inclusive in SQL?

Yes. BETWEEN includes both boundary values, so mark BETWEEN 60 AND 70 includes marks equal to 60 and 70.

Q6: What happens if I omit WHERE from UPDATE or DELETE?

The statement can affect every row in the table. Use WHERE when only selected rows should be updated or deleted.

Q7: How should external values be used in a WHERE clause from PHP?

Validate the application input as needed and pass data values through a PDO prepared statement rather than concatenating untrusted values into the SQL string.



SELECT Records AND / OR Conditions


Subscribe to our YouTube Channel here



plus2net.com
Raju

11-04-2013

Can we use Where condition linking more that one table?
wale

23-02-2014

I have 12 tables with the same number of fields and field names. I want to sum one of those fields that have numerical values in all tables. How can I accomplish the task.
Ivan

13-09-2014

Anyone can help me how to resolve this issue?? I am getting a type mismatch with the below syntax... I dont know how to resolve it..

adoCompName.RecordSource = "SELECT * FROM Tbl_Comp_Dtl WHERE CompName = ' * " & Text1.Text & " '"
adoCompName.Refresh




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer