Monday, 9 April 2012

SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set.


The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC



ORDER BY Example
The "Persons" table:

P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Tom
Vingvn 23
Stavanger

Now we want to select all the persons from the table above, however, we want to sort the persons by their last name.
We use the following SELECT statement:
SELECT * FROM Persons
ORDER BY LastName

The result-set will look like this:

SQL AND & OR Operators


The AND & OR operators are used to filter records based on more than one condition.


The AND & OR Operators
The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.


AND Operator Example
The "Persons" table:

P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to "Svendson":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'
AND LastName='Svendson'

The result-set will look like this:

P_Id
LastName
FirstName
Address
City
2
Svendson
Tove
Borgvn 23
Sandnes

SQL WHERE Clause

The WHERE clause is used to filter records.


The WHERE Clause 
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value



WHERE Clause Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger

Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'

The result-set will look like this:

P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes



Quotes Around Text Fields
SQL uses single quotes around text values (most database systems will also accept double quotes).
However, numeric values should not be enclosed in quotes.
For text values: