DATA with BARAA

SQL Where

SQL WHERE

In this tutorial, you will learn how to filter rows based on specified conditions using the WHERE clause. 

Once you know how to fetch your data using  SELECT and FROM and the next step is to learn how to filter your data using WHERE clause.

In the previous tutorial, you learned how to retrieve all your rows from tables, but in real-world scenarios, we usually select only the rows which fulfill certain conditions like customers who come from a certain country.

Syntax

The basic syntax of the WHERE clause to filter the data returned by a query can be given with:

				
					SELECT column_names
FROM table_name
WHERE condition
				
			

It’s real easy to read in a plain-English way: select some columns from a table, except that the results will only include rows where that fulfill my conditions.

  • The clauses need to be in this order e SELECT  FROM WHERE
  • The WHERE clause  appears immediately after the FROM clause
  • In WHERE clause, you can specify one or more comparisons and logical operators.
.

Examples

To understand the WHERE statement in a better way, let’s look at the following customers table in our tutorial database:

Customers
customer_id first_name last_name country score
1 Maria Cramer Germany 350
2 John Steel USA 900
3 Georg Pipps UK 750
4 Martin Müller Germany 500
5 Peter Franken USA NULL

Now, let’s check out some examples that demonstrate how it actually works.

We have the following task be to solve using SQL statements

List only german customers

The following SQL statement will return only german customers from the database

				
					SELECT *
FROM customers
WHERE country = 'Germany'
				
			

After executing the above query, you’ll get the result set something like this:

customer_id first_name last_name country score
1 Maria Cramer Germany 350
4 Martin Müller Germany 500

As you can see the output contains only german customers.

Find all customers whose score is greater than 500

The following SQL statement will return only customers with score greater than 500

				
					SELECT *
FROM customers
WHERE score > 500
				
			

After executing the above query, you’ll get the result set something like this:

customer_id first_name last_name country score
2 John Steel USA 900
3 Georg Pipps UK 750

Operators in WHERE Clause

You can filter your results in a number of ways using comparison and logical operators, which you’ll learn about in the next tutorials. I summarized in the following table the most important ones.

Comparison Operators

= Equal
!= or <> Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Logical Operators

AND Return True if both conditions are True
OR Return True if one of conditions is True
NOT Reverse the result of any Boolean operator
IN Return True if a value is in a set of values
BETWEEN Return True if a value falls within a specific range
LIKE Return True if a value matches a pattern
.
Share it !
Exit mobile version