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

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.