The SQL WHERE clause is used to specify a condition that further is used to fetch the data from a single or by joining multiple tables. When the condition aligned with the where clause is true then it returns the values from the table that matches that particular condition. The WHERE clause should be only when it is necessary.
We see the usage of the WHERE clause is more often with the SELECT statements but the use of the WHERE clause is also with UPDATE or DELETE as well which we will cover in other articles.
-
Syntax of SQL WHERE Clause –
SELECT column1,column2,column3,...,columnN FROM table_name WHERE condition;
As in the syntax, it can be seen that a condition is aligned with the SQL WHERE clause.
Demo table –
Product Table
Category |
Region |
City |
Country |
Customer_ID |
Customer_name |
Office Supplies |
Central |
Chicago |
United States |
SM-20950 |
Suzanne McNair |
Technology |
East |
New York City |
United States |
AH-10465 |
Amy Hunt |
Office Supplies |
East |
New York City |
United States |
AH-10465 |
Amy Hunt |
Office Supplies |
East |
Dover |
United States |
EP-13915 |
Emily Phan |
Office Supplies |
East |
Dover |
United States |
EP-13915 |
Emily Phan |
Technology |
West |
Aurora |
United States |
TP-21565 |
Tracy Poddar |
Office Supplies |
West |
Aurora |
United States |
TP-21565 |
Tracy Poddar |
Office Supplies |
East |
Long Beach |
United States |
AR-10825 |
Anthony Rawles |
Office Supplies |
West |
Pasadena |
United States |
HA-14920 |
Helen Andreada |
Furniture |
West |
Pasadena |
United States |
HA-14920 |
Helen Andreada |
Example – Consider the Product table of the Customer database and fetch records of those Customers who belong to the City of “Chicago” from the Product Table.
SELECT Category,Region,City,
[Country/Region],[Customer ID],[Customer Name] FROM [dbo].[Products] WHERE City = 'Chicago';
The output after executing the above statement is as shown –
Category |
Region |
City |
Country |
Customer_ID |
Customer_name |
Office Supplies |
Central |
Chicago |
United States |
SM-20950 |
Suzanne McNair |
The following query fetches the Category, Region, City, Country, Customer ID, and Customer Name from the Products table for City with the name Chicago.
- NOTE – All the strings should be given inside single quotes (‘ ‘). Whereas, numeric values should be given without any quote.
Conditional Operators in WHERE clause –
Other SQL topics to check out:
- How to write SQL Select Statements
- Introduction to SQL for Data Scientists
- What is RDBMS (Relational Database Management System)?
Follow us on Twitter, Facebook, Linkedin, and Tableau Public to stay updated with our latest blog and what’s new in Tableau.