The WHERE clause is used to specify a selection criterion.
To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.
SELECT columnName FROM tableName WHERE columnName operator value; |
With the WHERE clause, the following operators can be used:
Operator |
Description |
= |
Equal |
<> |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
BETWEEN |
Between an inclusive range |
LIKE |
Search for a pattern |
Note: In some versions of SQL the <> operator may be written as !=.
To select only the books published by "Fast Press", we add a WHERE clause to the SELECT statement:
SELECT * FROM Books WHERE Publisher = 'Fast Press'; |
The "Books" table:
Title |
Author |
Publisher |
Year |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Linux Distributions |
J. Sam |
Fast Press |
2003 |
Operating Systems |
M. Stone |
Coriolis |
2005 |
The result is:
Title |
Author |
Publisher |
Year |
Java 2 |
L. Johnston |
Fast Press |
2002 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Linux Distributions |
J. Sam |
Fast Press |
2003 |
Note that we have used single quotes around the conditional values in the examples.
SQL uses single quotes around text values (most database systems will also accept double quotes). Some versions of SQL (such as MySQL) accept single and double quotes also for numeric values. However, they (numeric values) should not be enclosed in quotes for most database systems.
For text values:
This is correct:
This is
wrong: |
For numeric values:
This is correct:
This is wrong
for most
database systems: |
The LIKE condition is used to specify a search for a pattern in a column.
SELECT columnName FROM tableName WHERE columnName LIKE pattern; |
A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
The following SQL statement will return books with titles that start with 'Linux':
SELECT * FROM Books WHERE Title LIKE 'Linux%'; |
The following SQL statement will return books with titles that end with an 's':
SELECT * FROM Books WHERE Title LIKE '%s'; |
The following SQL statement will return books with titles that contain the pattern 'in':
SELECT * FROM Books WHERE Title LIKE '%in%'; |
To test your SQL skills click here.