Computer Science‎ > ‎

Databases and SQL: SELECT Queries with conditions and clauses



One of the most frequently used SQL commands is SELECT. Here are some examples of its usage.


EXAMPLES :

Basic SELECT-FROM-WHERE query


1. Display the birthday and address of the student named ‘Ahmad’.

-> SELECT Bdate, Address
    FROM Student
    WHERE SName=’Ahmad’;

The query “selects” the Student tuples that satisfy the condition of the WHERE clause then takes the result from the Bdate and Address attributes listed in the SELECT clause.
All the queries are of the form SELECT-FROM-WHERE.

Bdate

Address

20-10-1990

2113,Sec42,Chandigarh





Select-Project-Join Query


2. Retrieve the name and St_Id of all the students who are in  ‘Civil’ Branch.

-> SELECT SName , St_Id
   FROM Student , Branch
   WHERE BName = ‘Civil’ AND Br_No=Bno;

In the query in WHERE clause, BName = ‘Civil’ is the selection condition and ‘Br_No=BNo’ is the join condition . It is used when two tables (here , Student and Branch) need to be joined.
SNameSt_Id
Anjali1201
Ahmad1202
Gaurav1211




Use of Asterisk “*”


3. Retrieve all attributes of all students  with Branch No. = 3.

-> SELECT *
    FROM Student
    WHERE Br_No = 3;

To retrieve all the attributes of the selected tuples of the table using the WHERE clause, we use ( * ).

SNameSt_IdBdateAddressSexBr_No
Sonia120319-02-199019,Patel Road, DelhiF3
Parag120915-08-199356A,EatStreet, ChennaiM3




Aliasing


4. List the courses in ‘Chemical’ Branch.

-> SELECT CName
    FROM Branch as B, Course as C

     WHERE BName=’Chemical’ AND B.BNo = C.BNo;


If same name is used for two attributes in different relations, prefixing is done to avoid ambiguity. Aliasing is done. Here Branch is aliased as B and Course is aliased as C. This way, we know which attribute belongs to which table.

CName

Chemical Analysis
Organic Chemistry




SELECT ALL Operator


5. Retrieve the Branch Number of all the courses.

-> SELECT ALL BNo
    FROM Course;

SELECT ALL displays all the entries of the specified field including the duplicate values. The       same value will appear as many times as it has appeared.
BNo

1

4

2

3

4

5

1

2




Comments