Monday, 9 April 2012

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:

Tuesday, 3 April 2012

SQL SELECT DISTINCT Statement

The SQL SELECT DISTINCT Statement

In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name(s)
FROM table_name