Home » SQL » WHERE Clause in SQL

WHERE Clause in SQL

Overview: In this tutorial you will learn and understand the WHERE clause in SQL with examples.

Introduction: WHERE Clause

WHERE clause in SQL is used to extract only those records that fulfil a specified condition. When you use the SELECT query for any table, you will get all the rows of that table, which might be we don’t need, if you need to process only set of rows from table then you can use WHERE clause in SQL query.

When you should use WHERE clause in SQL?

WHERE clause you should use when you need to extract the information from Table based on certain condition on table. The WHERE clause only returns the rows that the search condition evaluate TRUE. In the WHERE clause, you need to specify a search condition to filter out the rows returned by the FROM clause.

The search condition is a logical expression or a combination of multiple logical expressions. In SQL, a logical expression is often called a predicate.

SQL Server uses three logic value, below logical expression can evaluate

  • TRUE,
  • FALSE,
  • UNKNOWN.

The WHERE clause will not return any row that causes the logical condition to FALSE or UNKNOWN.

To get the rows from the table that satisfy one or more conditions, you use the below syntax WHERE clause:

Syntax:

SELECT 
      column1, column2, ...
FROM 
      table_name
WHERE 
      condition;

Lets take below few examples to understand it more:

Example #1: WHERE clause in SQL with one condition

In below example we are trying to extract all columns from “Customers_Tbl” with WHERE clause with condition of “[Product_Category] = ‘Furniture’“. This SQL query will show the all rows which have Furniture in “Product_Category” column,

If condition is not satisfied then it will return result as blank.

SELECT 
       *
FROM
      Customers_Tbl
WHERE
      Product_Category = 'Furniture'

Result:

Example #2: WHERE clause in SQL with multiple conditions using “AND” operator

In below example we are try to put condition on Product_category = Furniture and Margin which is greater then 70% by using AND Operator in query.

SELECT
       Product_Category,
       Region,
       Product_Base_Margin
FROM
       Customers_Tbl
WHERE
       Product_Category = 'Furniture'
       AND
       Product_Base_Margin > 0.70

Result:

Example #3: WHERE clause with multiple conditions using “OR” operator

SELECT
        Product_Category,        
        Region,        
        Product_Base_Margin
FROM
        Customers_Tbl 
WHERE
       Product_Category = 'Furniture'
       OR
       Product_Category = 'Box'

In this example we have used OR operator, which can used if you would like to apply multiple condition on single column, and WHERE clause will return the result based on condition satisfied with column or not.

Read more to know about: WHERE clause in SQL with Group by

If both condition satisfied then it will extract both condition rows, else only return rows based on one condition.