Archive for MySQL

SQL – Select Where clause Example

Saturday, November 28th, 2009

SQL where clause option can filter records from database table name. This returns only required rows which we put clause in query. where keyword can be used on one column name and more than one column name in SQL query. where clause can be implemented in MySQL, oracle, db2, Microsoft SQL server.

SQL select where query example explains how to use select where query in SQL.

Table class_name with all records without desired column name sorting

+---------+-------------+------------+------------+
| Roll_No | Name        | Class_Name | Year_Start |
+---------+-------------+------------+------------+
|       1 | Amit Mishra | B.Science  |       2005 |
|       2 | Robot       | B.Tech     |       2005 |
|       3 | Rohan       | M.Tech     |       2005 |
|       4 | Vivek       | B.Tech     |       2009 |
|       5 | Chander     | B.Science  |       2009 |
|       6 | Deepak      | B.Science  |       2009 |
+---------+-------------+------------+------------+

Where clause

SELECT * FROM class_name c where Year_Start = 2005;

Output

+---------+-------------+------------+------------+
| Roll_No | Name        | Class_Name | Year_Start |
+---------+-------------+------------+------------+
|       1 | Amit Mishra | B.Science  |       2005 |
|       2 | Robot       | B.Tech     |       2005 |
|       3 | Rohan       | M.Tech     |       2005 |
+---------+-------------+------------+------------+

this SQL query returns those row which column name (Year_Start) having 2005 value only from table.

select * from class_name where Year_Start > 2005;

Output

+---------+---------+------------+------------+
| Roll_No | Name    | Class_Name | Year_Start |
+---------+---------+------------+------------+
|       4 | Vivek   | B.Tech     |       2009 |
|       5 | Chander | B.Science  |       2009 |
|       6 | Deepak  | B.Science  |       2009 |
+---------+---------+------------+------------+

this SQL query returns only those row in column Year_Start greater than 2005 value only.

group by on more than one column name

SELECT * FROM class_name c
   where Year_Start= 2005 and Class_Name = 'B.Tech';

Output

+---------+-------+------------+------------+
| Roll_No | Name  | Class_Name | Year_Start |
+---------+-------+------------+------------+
|       2 | Robot | B.Tech     |       2005 |
+---------+-------+------------+------------+

this SQL query returns only those row in column Year_Start having 2005 value only and also class_name column value having B.Tech.

* indicates fetch all columns records from table.