Home » SQL

SQL - GROUP BY and ORDER BY

SQL - BROUP BY and ORDER BY: Here, we will learn how to form records on the basis of certain common elements and Order By to display them in an ascending and descending order.
Submitted by Shubham Singh Rajawat, on November 15, 2017

GROUP BY is used to form a group of records on the basis of a certain common element in the records. ORDER BY is used to arrange record either in ascending or descending order in a table.

Syntax:

SELECT column_names FROM table_names WHERE condition 
GROUP BY column_name 
HAVING condition 
ORDER BY column_name ASC/DESC;

Here,

  • Column_names: are the name of the fields in the table
  • table_name: name of the table from which we want to fetch data
  • condition: use to filter data

Note: If we do not specify ASC or DESC in ORDER BY it will by default take it as ascending order

Sample table (Student),

student table in sql example

Example:

1) Select Student and group them by city

SELECT * FROM Student GROUP BY City;
GROUP BY SQL example

2) Select Student and group them by city in descending order

SELECT * FROM Student 
GROUP BY City 
ORDER BY City DESC;
GROUP BY SQL example



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.