Thursday, 15 December 2011

SQL AND & OR


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.

The syntax for a compound condition is as follows: 

SELECT "column_name"
FROM "table_name"

WHERE "simple condition"
{[AND|OR] "simple condition"}+
 

The "custmast" Table:

custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70
2
Bala
Sivakasi
30
56
3
Kanna
Madurai
100
200
4
Vijay
Chennai
30
30
5
Kodee
Srivilliputtur
60
30
5
Kodee
Srivilliputtur
60
30

                                                                  AND
Ex:1

Select  *   from Custmast  WHERE custname='Siva' AND city='Srivilliputtur'


Output :

custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70

Ex:2


Select * From Custmast WHERE custname='Siva' AND City='Sivakasi'

Output :

     No Records

                                                                                 OR


The Above Example to OR condition

SELECT * FROM custmast WHERE custname='Siva' OR City='Sivakasi'

Output :

custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70
2
Bala
Sivakasi
30
56


                                                  Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the custname equal to "Siva" AND the City equal to "Srivilliputtur" OR to "Chennai": 


We use the following SELECT statement

SELECT * FROM custmast WHERE custname='Siva' 
AND (City='Srivilliputtur' OR City='Chennai')

Output :

custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70

No comments:

Post a Comment


”Back