T-SQL » Clauses » WHERE

Syntax:
SELECT { fieldlist | * } FROM table WHERE criteria
fieldlist
The list of fields that are to be retrieved from the table.
table
The name of the table from which the information is being retrieved.
criteria
The condition(s) that dictate which rows are to be retrieved.

The WHERE clause is an optional clause that can be used with the DELETE, SELECT, and UPDATE statements to specify a selection criteria. The syntax for the DELETE, SELECT, and UPDATE statements are very similar.

Examples

Code:
SELECT * FROM MusicArtists;
Output:
MusicianIDFirstNameLastNameInstrumentStyle
1ElvisPresleyGuitarRock and Roll
2B. B.KingGuitarBlues
3CharlieDanielsFiddleCountry
4JohnnyCashGuitarCountry
5HenryEricksonViolinClassical
6JonnyLangGuitarBlues
7JerryJamisonFluteClassical
8BobbyLeeFiddleClassical





(8 row(s) affected)
Explanation:

This simple query will return all rows from the table 'MusicArtists'.

Language(s): MS SQL Server
Code:
SELECT * FROM MusicArtists WHERE Style='Country';
Output:
MusicianIDFirstNameLastNameInstrumentStyle
3CharlieDanielsFiddleCountry
4JohnnyCashGuitarCountry





(2 row(s) affected)
Explanation:

The addition of a WHERE to the previous example allows you to efficiently narrow the values that will be selected. In this example, we narrow the criteria to only 'Country'.

Language(s): MS SQL Server
Code:
SELECT * FROM MusicArtists
WHERE Style='Country' AND Instrument='Guitar';
Output:
MusicianIDFirstNameLastNameInstrumentStyle
4JohnnyCashGuitarCountry





(1 row(s) affected)
Explanation:

By using the AND logical operator we can further narrow the criteria to 'Country' artists who play the 'Guitar'.

Language(s): MS SQL Server
Code:
SELECT * FROM MusicArtists
WHERE Style='Country' OR Style='Blues';
Output:
MusicianIDFirstNameLastNameInstrumentStyle
2B. B.KingGuitarBlues
3CharlieDanielsFiddleCountry
4JohnnyCashGuitarCountry
6JonnyLangGuitarBlues





(4 row(s) affected)
Explanation:

This example demonstrates how to widen a search to include multiple music styles using the OR logical operator.

Language(s): MS SQL Server
Code:
SELECT * FROM MusicArtists
WHERE Style='Country' OR Style='Blues' OR Style='Rock and Roll'
AND Instrument='Guitar' OR Instrument='Fiddle';
Output:
MusicianIDFirstNameLastNameInstrumentStyle
1ElvisPresleyGuitarRock and Roll
2B. B.KingGuitarBlues
3CharlieDanielsFiddleCountry
4JohnnyCashGuitarCountry
6JonnyLangGuitarBlues





(5 row(s) affected)
Explanation:

This example uses multiple criteria for the WHERE clause using the AND and OR operators. Within a WHERE clause, you can link up to a total of forty (40) such expressions using logical operators.

Language(s): MS SQL Server

See Also: