Filtering rows from a table with respect to a given condition or a set of conditions is a very common practice in data analysis. In SQL, you can do this using the where clause. In this tutorial, you will be using it for a number of different scenarios.
You will use PostgreSQL as the RDBMS (Relational Database Management System), but the syntaxes do not vary much when it comes to using other database systems. You will start off by setting up a PostgreSQL database and manually creating a table containing country data. After this is set up, you will execute several filter queries incorporating the WHERE clause.
Note: To follow along with the tutorial, you must be familiar with the basics of SQL and PostgreSQL. Following resources might be helpful if you are not familiar with them.
To follow along with this tutorial, you’ll need to create a table in PostgreSQL that contains information about countries around the world. This table will be used to demonstrate how the WHERE clause works in different scenarios.
Step 1: Create a new database
Open pgAdmin (or your preferred SQL interface) and create a new PostgreSQL database. You can name it something like world_data or anything else you prefer.
Step 2: Create and populate our table
Once your database is ready, open a new SQL query editor window and run the following SQL code. It will create a table called countries and insert a set of records covering a wide range of continents, independence years, and regions:
The table has different information about a total of about 16 countries around the globe. The table has the following columns:
code which is the primary key of the table and denotes the universal country code for a given country
name i.e., name of a country
continent to which a country belongs
region the geographical location where a country is located
surface_area of the country
indep_year i.e., the year in which a country got its independence
local_name of a country
gov_form i.e., the kind of government that is active in a country
capital of a country
cap_long i.e., longitude of the capital of a country
cap_lat i.e., latitude of the capital of a country
Let's now start filtering some records with the WHERE clause.
Using the SQL WHERE Clause
In SQL, the WHERE clause lets you filter records based on both textual and numeric values. You can compare these values, and the following comparison-based operations are supported -
= equal
<> and != not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to
It's advised to use <> rather than != as per the SQL standards.
Let's now get the record of the country where the code is AUS. The column you should compare here is the code column and the value to be compared is AUS. The query would be:
SELECT*FROM countries WHERE code ='AUS';ขับเคลื่อนโดย
And you get:
Notice a couple of things here -
The WHERE clause always comes after FROM.
In SQL, the strings quoted using single quotes.
Let's now see a numerical comparison. Let's get the records of the country which gained their independence (indep_year) after 1901:
SELECT*FROM countries WHERE indep_year >1901;ขับเคลื่อนโดย
You get the records of a total of 3 countries that gained their independence after 1901. Take note of the comparator used here. The indep_yearcolumn is an integer in type. Hence, no quotes in the comparison.
You can connect multiple conditions in a WHERE clause using AND and OR connectives. Following query gets you the records of those countries where continent = 'Asia' and indep_year > 1900 -
SELECT*FROM countries WHERE continent ='Asia'AND indep_year >1901;ขับเคลื่อนโดย
You get information about a total of three countries that are situated in the continent of Asia and gained their independence after 1901. Note that in the above query, you compared both textual and numerical values. As an exercise, you play with different combinations of AND and OR in the WHERE clause.
Note: When you are combining AND and OR, don't forget to enclose each of the conditions within parentheses. Otherwise, SQL will get confused when determining the precedence of the evaluation of the conditions.
With the following query, you get a total of six countries.
SELECT*FROM countries WHERE(continent ='Europe'AND indep_year >1900)or(continent ='Asia'AND indep_year >1900);ขับเคลื่อนโดย
You can even connect more than two conditions in a WHERE clause:
SELECT*FROM countries WHERE continent ='Asia'OR indep_year >1900OR surface_area >652090;ขับเคลื่อนโดย
Here, you get a total of 15 countries that are either situated in Asia or have gained their independence after 1901 or have a surface area greater than 652090.
Let's now convert the query into an AND variant, which is more restrictive:
SELECT*FROM countries WHERE continent ='Asia'AND indep_year >1901AND surface_area >652090;ขับเคลื่อนโดย
You will get a total of two countries in this case.
You can pair up sub-queries in a WHERE clause as well. Let's say you want to fetch the record of the country having the highest surface area, but you don't know what the maximum surface area obtained by a country is. The following query can come to the rescue in situations like this:
SELECT*FROM countries WHERE surface_area in(SELECTMAX(surface_area)FROM countries);ขับเคลื่อนโดย
You should get the record of Russia.
Conclusion
Congrats, you have completed this tutorial. Filtering query results with respect to conditions is definitely a vital skill, and this tutorial served as an introduction to it. If you want to hone in your SQL skills even further, then you can check out our courses (link below).
ผู้เขียน
Sayak Paul
Sayak works at Hugging Face where he codes, writes, and speaks. His time is mostly spent around everything related to the Diffusers library. He's also a DataCamp project instructor and the author of many DataCamp tutorials. Off work, you will catch him binge-watching Suits on Netflix for the nth time.
SQL WHERE Clause FAQs
Can I use both text and numeric columns in a WHERE clause?⌄
Yes, you can filter by both text (e.g., 'Asia') and numeric (e.g., > 1901) values. Just remember that text values must be enclosed in single quotes.
Is there a difference between <> and != in SQL?⌄
Both mean "not equal," but <> is the standard SQL operator. Some databases also support !=, but it's best to use <> for compatibility.
How do I filter records with NULL values?⌄
Use IS NULL or IS NOT NULL. For example:
SELECT*FROM countries WHERE indep_year ISNULL;ขับเคลื่อนโดย
Can I use subqueries in a WHERE clause?⌄
Yes, subqueries can be used to compare a column against the result of another query. For example:
SELECT*FROM countries WHERE surface_area =(SELECTMAX(surface_area)FROM countries);ขับเคลื่อนโดย
Does the WHERE clause come before or after the FROM clause?⌄
The WHERE clause always comes after the FROM clause and before clauses like GROUP BY or ORDER BY.
Can I use WHERE with JOINs?⌄
Absolutely. You can apply the WHERE clause after performing a JOIN to filter the combined result set.
Discover how WHERE filters row-level data in SQL queries, while HAVING filters grouped data after aggregation, and master their distinct uses in SQL querying.
The SQL IN operator allows you to filter query results to include only rows that meet specified conditions. Explore its full potential and alternatives.
If you are looking to get started with SQL, we’ve got you covered. In this SQL tutorial, we will introduce you to SQL queries - a powerful tool that enables us to work with the data stored in a database.
Filtering rows from a table with respect to a given condition or a set of conditions is a very common practice in data analysis. In SQL, you can do this using the
whereclause. In this tutorial, you will be using it for a number of different scenarios.You will use PostgreSQL as the RDBMS (Relational Database Management System), but the syntaxes do not vary much when it comes to using other database systems. You will start off by setting up a PostgreSQL database and manually creating a table containing country data. After this is set up, you will execute several filter queries incorporating the
WHEREclause.Note: To follow along with the tutorial, you must be familiar with the basics of SQL and PostgreSQL. Following resources might be helpful if you are not familiar with them.
Creating a Table in PostgreSQL
To follow along with this tutorial, you’ll need to create a table in PostgreSQL that contains information about countries around the world. This table will be used to demonstrate how the
WHEREclause works in different scenarios.Step 1: Create a new database
Open pgAdmin (or your preferred SQL interface) and create a new PostgreSQL database. You can name it something like
world_dataor anything else you prefer.Step 2: Create and populate our table
Once your database is ready, open a new SQL query editor window and run the following SQL code. It will create a table called
countriesand insert a set of records covering a wide range of continents, independence years, and regions:The table has different information about a total of about 16 countries around the globe. The table has the following columns:
codewhich is the primary key of the table and denotes the universal country code for a given countrynamei.e., name of a countrycontinentto which a country belongsregionthe geographical location where a country is locatedsurface_areaof the countryindep_yeari.e., the year in which a country got its independencelocal_nameof a countrygov_formi.e., the kind of government that is active in a countrycapitalof a countrycap_longi.e., longitude of the capital of a countrycap_lati.e., latitude of the capital of a countryLet's now start filtering some records with the
WHEREclause.Using the SQL WHERE Clause
In SQL, the
WHEREclause lets you filter records based on both textual and numeric values. You can compare these values, and the following comparison-based operations are supported -=equal<>and!=not equal<less than>greater than<=less than or equal to>=greater than or equal toIt's advised to use
<>rather than!=as per the SQL standards.Let's now get the record of the country where the
codeisAUS. The column you should compare here is thecodecolumn and the value to be compared isAUS. The query would be:And you get:
Notice a couple of things here -
The
WHEREclause always comes afterFROM.In SQL, the strings quoted using single quotes.
Let's now see a numerical comparison. Let's get the records of the country which gained their independence (
indep_year) after1901:You get the records of a total of 3 countries that gained their independence after
1901. Take note of the comparator used here. Theindep_yearcolumn is an integer in type. Hence, no quotes in the comparison.You can connect multiple conditions in a
WHEREclause usingANDandORconnectives. Following query gets you the records of those countrieswhere continent = 'Asia' and indep_year > 1900-You get information about a total of three countries that are situated in the continent of
Asiaand gained their independence after1901. Note that in the above query, you compared both textual and numerical values. As an exercise, you play with different combinations ofANDandORin theWHEREclause.Note: When you are combining
ANDandOR, don't forget to enclose each of the conditions within parentheses. Otherwise, SQL will get confused when determining the precedence of the evaluation of the conditions.With the following query, you get a total of six countries.
You can even connect more than two conditions in a
WHEREclause:Here, you get a total of 15 countries that are either situated in
Asiaor have gained their independence after1901or have a surface area greater than652090.Let's now convert the query into an
ANDvariant, which is more restrictive:You will get a total of two countries in this case.
You can pair up sub-queries in a
WHEREclause as well. Let's say you want to fetch the record of the country having the highest surface area, but you don't know what the maximum surface area obtained by a country is. The following query can come to the rescue in situations like this:You should get the record of
Russia.Conclusion
Congrats, you have completed this tutorial. Filtering query results with respect to conditions is definitely a vital skill, and this tutorial served as an introduction to it. If you want to hone in your SQL skills even further, then you can check out our courses (link below).