SQL WHERE Clause

By | September 6, 2020
SQL WHERE Clause

WHERE is one of the major clauses of SQL and it is used to specify the conditions while retrieving the data from the single or multiple tables. The WHERE clause act like an IF statement of high-level programming languages and this often use when we want to access a specific data range or data from the tables.

The WHERE clause filters the data according to the conditions and performs its task, apart from retrieving data where clause also used along with the UPDATE, DELETE and CREATE statements.

Vamware

WHERE CLAUSE Syntax

Follow this syntax to use WHERE clause.

SELECT column_name_1, column_name_n
FROM table_name
WHERE [condition];

The condition uses the comparison or logical operators such as  >, <, =, LIKE, NOT, etc.

Example

Considered the table students:

+------+--------+------+--------+-------+
| id   | name   | age  | grades | marks |
+------+--------+------+--------+-------+
|    1 | Luffy  |   16 | A      |   970 |
|    2 | Naruto |   18 | A      |   960 |
|    3 | Zoro   |   20 | A      |   940 |
|    4 | Sanji  |   21 | B      |   899 |
|    5 | Nami   |   17 | B      |   896 |
|    6 | Robin  | NULL | NULL   |   860 |
+------+--------+------+--------+-------+

WHERE clause Example 1

Query: Show all the details of the student name Luffy:

SELECT *
FROM students
WHERE name = "Luffy";

Output:

+------+-------+------+--------+-------+
| id   | name  | age  | grades | marks |
+------+-------+------+--------+-------+
|    1 | Luffy |   16 | A      |   970 |
+------+-------+------+--------+-------+
1 row in set (0.00 sec)

Behind the Query

Here the SELECT * represents show all the table data and the WHERE name = “luffy” signify the condition that shows all the column data where the name field is luffy.

Here we have used the “ ” double inverted comma for luffy, because the name is a string data type, and to represent a spring data we have to put the double or single inverted comma.  

WHERE clause Example 2

Query: Show the ID, name and age of the students whose marks are greater than 900

SELECT id, name, age
FROM students
WHERE marks > 900;

Output

+------+--------+------+
| id   | name   | age  |
+------+--------+------+
|    1 | Luffy  |   16 |
|    2 | Naruto |   18 |
|    3 | Zoro   |   20 |
+------+--------+------+
3 rows in set (0.00 sec)

Summary

  • The WHERE clause is used to filter the condition.
  • It often used with SELECT statement to show the specific range of data.
  • It can also be used along with the UPDATE, DELETE and CREATE statement.
  • There should always be a condition along with the WHERE clause.

Leave a Reply

Your email address will not be published. Required fields are marked *