SQL SERVER BASIC QUESTIONS PART 7

SQL IN
The IN operator may be used if you know the exact value you want to return for at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
Original Table (used in the examples)

LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes
Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes

Example 1
To display the persons with LastName equal to "Hansen" or "Pettersen", use the following SQL:

SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen')

Result:
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Pettersen Kari Storgt 20 Stavanger

SQL BETWEEN 
BETWEEN ... AND
The BETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates.

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2

Original Table (used in the examples)
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes
Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes

Example 1
To display the persons alphabetically between (and including) "Hansen" and exclusive "Pettersen",

use the following SQL:

SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'

Result:

LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes

IMPORTANT! The BETWEEN...AND operator is treated differently in different databases.
With some databases a person with the LastName of "Hansen" or "Pettersen" will not be listed
(BETWEEN..AND only selects fields that are between and excluding the test values).
With some databases a person with the last name of "Hansen" or 

No comments:

Post a Comment