Structured Query Language (SQL) : (Chapter 11)
Structured Query Language (SQL) : (Chapter 11)
Language (SQL)
(Chapter 11)
SORTING IN SQL—ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. The ORDER BY keyword is used to sort the result-set by one or
more fields in a table. This clause sorts the records in the ascending order (ASC) by default.
Therefore, in order to sort the records in descending order, DESC keyword is to be used. Sorting
using ORDER BY clause can be done on multiple columns, separated by comma.
Syntax for ORDER BY clause:
SELECT <column-list> FROM <table_name> [WHERE <condition>]
ORDER BY <column_name> [ASC|DESC];
Here, WHERE clause is optional. Rollno Name Marks
For example, 8. Akshay Dureja 90
• To display the roll number, name and marks of students 3. Ankit Sharma 76
on the basis of their marks in the ascending order. 2. Deep Singh 98
mysql> SELECT Rollno, Name, Marks FROM student 6. Diksha Sharma 80
ORDER BY Name; 7. Gurpreet Kaur NULL
• To display the roll number, name and marks of all the 5. Payal Goel 82
students in the descending order of their marks and 10. Prateek Mittal 75
ascending order of their names. 4. Radhika Gupta 78
mysql> SELECT Rollno, Name, Marks FROM student 1. Raj Kumar 93
ORDER BY Marks DESC, Name; 9. Shreya Anand 70
Sorting on Column Alias
If a column alias is defined for a column, it can be used for displaying rows in ascending or
descending order using ORDER BY clause.
For example, SELECT Rollno, Name, Marks AS Marks_obtained
FROM student
Alias name
ORDER BY Marks_obtained;
AGGREGATE FUNCTIONS
Till now we have studied about single row functions which work on a single value. SQL also
provides multiple row functions which work on multiple values. So, we can apply SELECT
query on a group of records rather than the entire table. Therefore, these functions are called
aggregate functions or group functions.
Generally, the following aggregate functions are applied on groups as described below:
Table 1: Aggregate Functions in SQL
S.No. Function Description/Purpose
1. MAX() Returns the maximum/highest value among the values in the given column/expression.
2. MIN() Returns the minimum/lowest value among the values in the given column/expression.
3. SUM() Returns the sum of the values under the specified column/expression.
4. AVG() Returns the average of the values under the specified column/expression.
5. COUNT() Returns the total number of values/records under the specified column/expression.
Consider a table Employee (Employee code, employee name, job, salary and city) with the
following structure:
Ecode Name Salary Job City
E1 Ritu Jain 5000 Manager Delhi
E2 Vikas Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
E4 Leena Arora 7200 Manager Bangalore
E5 Shikha Sharma 8000 Accountant Kanpur
1. MAX()
MAX() function is used to find the highest value among the given set of values of any column
or expression based on column. MAX() takes one argument which can be either a column
name or any valid expression involving a particular column from the table.
For example,
mysql> Select MAX(Salary) from EMPLOYEE;
Output:
+----------------+
| MAX(Salary)|
+----------------+
| 8000 |
+----------------+
This command on execution shall return the maximum value from the specified column
(Salary) of the table Employee, which is 8000.
4. AVG()
AVG() function is used to find the average value of any column or expression based on a
column. Like sum(), it also accepts the entire range of values of a particular column to
be taken average of, or even a valid expression based on this column name. Like SUM()
function, the AVG() function always takes argument of integer type only. Average of String
and Date type data is not defined.
For example,
mysql> Select AVG(Salary) from EMPLOYEE;
+----------------+
| AVG(Salary) |
+----------------+
| 6140 |
+----------------+
This command on execution shall return the average of the salaries of all the employees from
the specified column (Salary) of the table Employee, which is 6140.
5. COUNT()
COUNT() function is used to count the number of values in a column. COUNT() takes one
argument which can be any column name, or an expression based on a column, or an asterisk (*).
When the argument is a column name or an expression based on column, COUNT() returns
the number of non-NULL values in that column. If the argument is asterisk (*), then COUNT()
Computer Science with Python—XI
counts the total number of records/rows satisfying the condition, if any, in the table.
For example,
1. mysql> Select COUNT(*) from EMPLOYEE;
+----------------+
| COUNT(*) |
+----------------+
| 5 |
+----------------+
This command on execution shall return the total number of records in the table Employee,
which is 5.
36
2. mysql> Select COUNT(DISTINCT City) from EMPLOYEE;
+-------------------------------+
| COUNT(DISTINCT City) |
+-------------------------------+
| 4 |
+-------------------------------+
This command on execution shall return the total number of records on the basis of city with
no duplicate values, i.e., Kanpur is counted only once; the second occurrence is ignored by
mySQL because of the DISTINCT clause. Thus, the output will be 4 instead of 5.
37
SOLVED QUESTIONS
1. Consider the following two tables: STATIONERY and CONSUMER.
Table: Stationery
S_ID StationeryName Company Price StockDate
DP01 Dot Pen ABC 10 2011-03-31
PL02 Pencil XYZ 6 2010-01-01
ER05 Eraser XYZ 7 2010-02-14
PL01 Pencil CAM 5 2009-01-09
GP02 Gel Pen ABC 15 2009-03-19
Note:
• S_ID is the Primary Key.
Table: Consumer
C_ID ConsumerName Address P_ID
01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bengaluru PL01
Note:
• C_ID is the Primary Key.
• P_ID is the Foreign Key referencing S_ID of Stationery table.
Write SQL statements for the queries (i) to (iii) and output for (iv) and (v):
(i) To display details of all the Stationery items in the Stationery table in descending order of StockDate.
(ii) To display details of that Stationery item whose Company is XYZ and price is below 10.
(iii) To increase the price of all the Stationery items in Stationery table by 2.
(iv) Select COUNT(DISTINCT Address) from Consumer;
(v) Select StationeryName, price * 3 from Stationery
where Company = ‘CAM’;
Ans. (i) Select * from Stationery
order by StockDate desc;
(ii) Select * from Stationery
where Company = ‘XYZ’ and Price < 10;
(iii) Update Stationery
Set Price = Price + 2;
(iv) 3
(v) Pencil 15
2. Answer the questions given below on the the basis of the following tables SHOP and ACCESSORIES.
Table: SHOP
Id SName Area
S01 ABC Computronics CP
S02 All Infotech Media GK II
S03 Tech Shoppe CP
S04 Geek Tenco Soft Nehru Place
Computer Science with Python—XI
UNSOLVED QUESTIONS
1. Consider the following tables STORE and SUPPLIERS. Write SQL commands for the statements (a) to (d)
and give outputs for SQL queries (e) to (g).
Table: STORE
ItemNo Item Scode Qty Rate LastBuy
2005 Sharpener Classic 23 60 8 31-Jun-09
2003 Ball Pen 0.25 22 50 25 01-Feb-10
2002 Gel Pen Premium 21 150 12 24-Feb-10
2006 Gel Pen Classic 21 250 20 11-Mar-09
2001 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09
Table: SUPPLIERS
Scode Sname
21 Premium Stationery
23 Soft Plastics
22 Tetra Supply
(a) To display details of all the items in the Store table in ascending order of LastBuy.
(b) To display Itemno and item name of those items from store table whose rate is more than 15 rupees.
(c) To display the details of those items whose supplier code is 22 or Quantity in store is more than 110
from the table Store.
(d) To display minimum rate of items for each Supplier individually as per Scode from the table Store.
(e) SELECT COUNT(DISTINCT Scode) FROM STORE;
(f) SELECT Rate*Qty FROM STORE WHERE Itemno=2004;
(g) SELECT MAX(LastBuy)FROM STORE;
2. Consider the given table and answer the questions.
Table: SchoolBus
Rtno Area_Covered Capacity Noofstudents Distance Transporter Charges
1 Vasant Kunj 100 120 10 Shivam travels 100000
2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
Computer Science with Python—XI