SQL Notes 12bcs
SQL Notes 12bcs
Order by clause:
Sorting Results of a Table/Relation - ORDER BY clause
Whenever a SELECT query is executed, the resulting rows emerge in a predefined order. You can sort the results or a query in
a specific order using ORDER BY clause.
The data in the table is not sorted ; only the results that appear on thescreen are sorted. The syntax of ORDER BY clause is :
SELECT <column name> [, <column name> , ... ]
FROM <table name> [WHERE <predicate> ] [ORDER BY <column name> ] ;
For example, to display the list of students(refer the above table) in the alphabetical order of their names, we can use the command :
SELECT * FROM Student ORDER BY name asc; (asc keyword is optional by default keyword for ascending order is asc)
Grouping Result-GROUP BY
The Group by Clause is used in SELECT statements to divide the table into groups. Grouping can be done by column name or
with aggregate functions in which case the aggregate produces a value for each group
For Eg: Consider the following student table defined below:
Admn Name Stream Optional Marks
STUDENT 1001 Shrishti Science CS 90
1002 Ashi Humanities Maths 80
1003 Aditya Commerce IP 60
1004 Ritu Raj Science IP 65
1005 Sonali Commerce Maths 60
1006 Saumya Science IP 65
From the above table if you want to display the total no:of students stream wise you may use the query:
Select Stream ,count(*) from student group by Stream;
The output will be:
Stream count(*)
Science 3
Humanities 1
Commerce 2
The condition in HAVING clause is applied on groups of records, not on individual records. Only the condition in
WHERE clause is applied on individual records.
SELECT stream, count(*) FROM student GROUP BY stream HAVING count(*) < 3 ;