sqlserver basic questions part 3

SQL The WHERE Clause

The WHERE clause is used to specify a selection criterion.

 The WHERE Clause

To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.

Syntax

SELECT column FROM table

WHERE column 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 !=

 Using the WHERE Clause

To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement:

SELECT * FROM Persons WHERE City='Sandnes'

"Persons" table

 LastName FirstName Address City Year

Hansen Ola Timoteivn 10 Sandnes 1951

Svendson Tove Borgvn 23 Sandnes 1978

Svendson Stale Kaivn 18 Sandnes 1980

Pettersen Kari Storgt 20 Stavanger 1960

 Result

 LastName FirstName Address City Year

 Hansen Ola Timoteivn 10 Sandnes 1951

Svendson Tove Borgvn 23 Sandnes 1978

Svendson Stale Kaivn 18 Sandnes 1980

 Using Quotes

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). Numeric values should not be enclosed in quotes.

 For text values:

This is correct:

SELECT * FROM Persons WHERE FirstName='Tove'This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove

 For numeric values:

 This is correct:

SELECT * FROM Persons WHERE Year>1965This is wrong:

SELECT * FROM Persons WHERE Year>'1965'

 The LIKE Condition

 The LIKE condition is used to specify a search for a pattern in a column.

 Syntax

 SELECT column FROM table

WHERE column LIKE pattern

 A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.

 

No comments:

Post a Comment