SlideShare a Scribd company logo
1 of 3
Download to read offline
Difference between Group By and Order By in SQL Server

      S.No   Group By                               Order By

      1      Meaning:                               Meaning:
             Group By performs grouping             Order By performs sorting operation
             operation i.e., it provides a way to   i.e., it provides a way to sort SQL
             sub-total SQL Query results,or         Query results like ascending or
             perform some other aggregate           descending . It does not affect what
             functions (GROUPING SETS,              shows up in the result set,only what
             CUBE, ROLLUP, WITH CUBE,               order it is displayed.
             or WITH ROLLUP) on them.

      2      Used for:                              Used for:
             Controlling the presentation of the    Controlling the presentation of the
             rows for the results of the            columns for the results of the
             SELECT statement.                      SELECT statement.

      3      Change in order of columns:            Change in order of columns:
             Order of columns make no               Order of Columns makes difference in
             difference in the GROUP BY             ORDER BY Clause.
             Clause.
                                                    For Example,
             For Example,
                                                    ORDER BY A, B, C
             GROUP BY A, B, C                       and
             and                                    ORDER BY C,A,B
             GROUP BY C,A,B
                                                    Both returns the same number of
             Both returns the same results.         Records. But Row order will be
                                                    different.

      4      Allowed in Create View                 Allowed in Create View Statement
             Statement or not:                      or not:
             GROUP BY clause can be used in         ORDER BY clause is not allowed in
             the CREATE VIEW statement to           the CREATE VIEW statement.
             sort data.

      5      Execution Sequence:                    Execution Sequence:
             The GROUP BY clause is always          The ORDER BY clause is always
             placed before the ORDER BY             placed after the GROUP BY clause in
             clause in the SELECT statement.        the SELECT statement.

      6      Impact on performance:                 Impact on performance:
             As we know that Group By clubs         As we now that Order By sorts the
             all the similar rows and display       data either in ascending order or in
             only the distinct data. So here        descending order as specified in the
             clubbing and displaying distinct       query. So here Sorting the data is an
             data is an overhead.                   overhead.


Example-1 for Group By:
select * from employee group by emp_name.

this gives the output data in the group of the emp_name.

Example-2 for Group By:

SELECT department, sum(salary)
FROM tblEmployee
GROUP BY department;

will give us salary totals by department, whereas the sum statement by itself would just give us the
grand total of all salaries in tblEmployee.

Example-3 for Group By:

Group By helps us to display any aggregate of any column based on a field what has repeated
names.

use AdventureWorksDW2008R2

go

select Title,SUM(BaseRate) as Rate from dbo.DimEmployee group by Title


             Title                                    Rate
       1     The Accountant                           52.88
       2     Accounts Manager                         34.74
       3     Accounts Payable Specialist              38
       4     Accounts Receivable Specialist           57
       5     Application Specialist                   109.62
       6     Assistant to the Chief Financial Officer 13.46
       7     Benefits Specialist                      16.59
       8     Buyer                                    164.42
       9     Chief Executive Officer                  125.5
       10    Chief Financial Officer                  120.19
       11    Control Specialist                       33.65
       12    Database Administrator                   76.92

Example-1 for Order By:

select * from employee order by emp_name desc,emp_no asc;

this query gives the output in the ascending order of the emp_no and descending order of the
emp_name.

Example-2 for Order By:
SELECT *
FROM tblEmployee
ORDER BY lastname;

will give us all tblEmployee data, in order of last name. If we want the results in descending
(reversed) order, simply add DESC to the end of the clause: ORDER BY lastname DESC;
Example-3 for Order By:

Order By clause helps us to display any table based on the values present on that particular column.

use AdventureWorksDW2008R2

go

select FirstName,Title from dbo.DimEmployee order by FirstName

              First Name      Title
        1     A. Scott        The Master Scheduler
        2     Alan            Scheduling Assistant
        3     Alejandro       Production Technician - WC40
        4     Alex            Production Technician - WC45
        5     Alice           Production Technician - WC50
        6     Amy             European Sales Manager
        7     Andreas         Quality Assurance Technician
        8     Andrew          Production Supervisor -WC10
        9     Andrew          Production Technician - WC45
        10    Andy            Production Technician - WC30
        11    Angela          Production Technician - WC50
        12    Anibal          Production Technician - WC20

Summary:

     1. All non-aggregate columns selected must be listed in the GROUP BY clause.
     2. Integers cannot be used in the GROUP BY to represent columns after the SELECT keyword,
        similar to using the ORDER BY clause.
     3. The GROUP BY clause is generally not necessary unless using aggregate functions.
     4. If we GROUP, the results are not necessarily sorted; although in many cases they may come
        out in an intuitive order, that's not guaranteed by the GROUP clause. If we want our groups
        sorted, always use an explicity ORDER BY after the GROUP BY. – Dave Costa
     5. Processing of "group by" or "order by" clause often requires creation of Temporary tables to
        process the results of the query. Which depending of the result set can be very expensive.

And, further updates on difference between questions and answers, please visit my blog @
http://onlydifferencefaqs.blogspot.in/

More Related Content

What's hot

What's hot (20)

Sql DML
Sql DMLSql DML
Sql DML
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Web controls
Web controlsWeb controls
Web controls
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Php string function
Php string function Php string function
Php string function
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Features of java
Features of javaFeatures of java
Features of java
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Applets
AppletsApplets
Applets
 

Similar to Difference between group by and order by in sql server

Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
maxpane
 
e computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clausee computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clause
ecomputernotes
 

Similar to Difference between group by and order by in sql server (20)

Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
Les17
Les17Les17
Les17
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Les04
Les04Les04
Les04
 
chap 9 dbms.ppt
chap 9 dbms.pptchap 9 dbms.ppt
chap 9 dbms.ppt
 
1 z0 001
1 z0 0011 z0 001
1 z0 001
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
OUTPUT Clause Correlated Subqueries and Subquery Extensions
OUTPUT Clause Correlated Subqueries and Subquery ExtensionsOUTPUT Clause Correlated Subqueries and Subquery Extensions
OUTPUT Clause Correlated Subqueries and Subquery Extensions
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
You can do THAT without Perl?
You can do THAT without Perl?You can do THAT without Perl?
You can do THAT without Perl?
 
e computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clausee computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clause
 
Group by clause mod
Group by clause modGroup by clause mod
Group by clause mod
 
7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
 
SQL Views
SQL ViewsSQL Views
SQL Views
 

More from Umar Ali

More from Umar Ali (20)

Difference between wcf and asp.net web api
Difference between wcf and asp.net web apiDifference between wcf and asp.net web api
Difference between wcf and asp.net web api
 
Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()
 
Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4
 
Difference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcDifference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvc
 
Difference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvcDifference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvc
 
ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1
 
Link checkers 1
Link checkers 1Link checkers 1
Link checkers 1
 
Affiliate Networks Sites-1
Affiliate Networks Sites-1Affiliate Networks Sites-1
Affiliate Networks Sites-1
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1
 
US News Sites- 1
US News Sites- 1 US News Sites- 1
US News Sites- 1
 
How to create user friendly file hosting link sites
How to create user friendly file hosting link sitesHow to create user friendly file hosting link sites
How to create user friendly file hosting link sites
 
Weak hadiths in tamil
Weak hadiths in tamilWeak hadiths in tamil
Weak hadiths in tamil
 
Bulughul Maram in tamil
Bulughul Maram in tamilBulughul Maram in tamil
Bulughul Maram in tamil
 
Asp.net website usage and job trends
Asp.net website usage and job trendsAsp.net website usage and job trends
Asp.net website usage and job trends
 
Indian news sites- 1
Indian news sites- 1 Indian news sites- 1
Indian news sites- 1
 
Photo sharing sites- 1
Photo sharing sites- 1 Photo sharing sites- 1
Photo sharing sites- 1
 
File hosting search engines
File hosting search enginesFile hosting search engines
File hosting search engines
 
Ajax difference faqs compiled- 1
Ajax difference  faqs compiled- 1Ajax difference  faqs compiled- 1
Ajax difference faqs compiled- 1
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1
 

Recently uploaded

Recently uploaded (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Difference between group by and order by in sql server

  • 1. Difference between Group By and Order By in SQL Server S.No Group By Order By 1 Meaning: Meaning: Group By performs grouping Order By performs sorting operation operation i.e., it provides a way to i.e., it provides a way to sort SQL sub-total SQL Query results,or Query results like ascending or perform some other aggregate descending . It does not affect what functions (GROUPING SETS, shows up in the result set,only what CUBE, ROLLUP, WITH CUBE, order it is displayed. or WITH ROLLUP) on them. 2 Used for: Used for: Controlling the presentation of the Controlling the presentation of the rows for the results of the columns for the results of the SELECT statement. SELECT statement. 3 Change in order of columns: Change in order of columns: Order of columns make no Order of Columns makes difference in difference in the GROUP BY ORDER BY Clause. Clause. For Example, For Example, ORDER BY A, B, C GROUP BY A, B, C and and ORDER BY C,A,B GROUP BY C,A,B Both returns the same number of Both returns the same results. Records. But Row order will be different. 4 Allowed in Create View Allowed in Create View Statement Statement or not: or not: GROUP BY clause can be used in ORDER BY clause is not allowed in the CREATE VIEW statement to the CREATE VIEW statement. sort data. 5 Execution Sequence: Execution Sequence: The GROUP BY clause is always The ORDER BY clause is always placed before the ORDER BY placed after the GROUP BY clause in clause in the SELECT statement. the SELECT statement. 6 Impact on performance: Impact on performance: As we know that Group By clubs As we now that Order By sorts the all the similar rows and display data either in ascending order or in only the distinct data. So here descending order as specified in the clubbing and displaying distinct query. So here Sorting the data is an data is an overhead. overhead. Example-1 for Group By:
  • 2. select * from employee group by emp_name. this gives the output data in the group of the emp_name. Example-2 for Group By: SELECT department, sum(salary) FROM tblEmployee GROUP BY department; will give us salary totals by department, whereas the sum statement by itself would just give us the grand total of all salaries in tblEmployee. Example-3 for Group By: Group By helps us to display any aggregate of any column based on a field what has repeated names. use AdventureWorksDW2008R2 go select Title,SUM(BaseRate) as Rate from dbo.DimEmployee group by Title Title Rate 1 The Accountant 52.88 2 Accounts Manager 34.74 3 Accounts Payable Specialist 38 4 Accounts Receivable Specialist 57 5 Application Specialist 109.62 6 Assistant to the Chief Financial Officer 13.46 7 Benefits Specialist 16.59 8 Buyer 164.42 9 Chief Executive Officer 125.5 10 Chief Financial Officer 120.19 11 Control Specialist 33.65 12 Database Administrator 76.92 Example-1 for Order By: select * from employee order by emp_name desc,emp_no asc; this query gives the output in the ascending order of the emp_no and descending order of the emp_name. Example-2 for Order By:
  • 3. SELECT * FROM tblEmployee ORDER BY lastname; will give us all tblEmployee data, in order of last name. If we want the results in descending (reversed) order, simply add DESC to the end of the clause: ORDER BY lastname DESC; Example-3 for Order By: Order By clause helps us to display any table based on the values present on that particular column. use AdventureWorksDW2008R2 go select FirstName,Title from dbo.DimEmployee order by FirstName First Name Title 1 A. Scott The Master Scheduler 2 Alan Scheduling Assistant 3 Alejandro Production Technician - WC40 4 Alex Production Technician - WC45 5 Alice Production Technician - WC50 6 Amy European Sales Manager 7 Andreas Quality Assurance Technician 8 Andrew Production Supervisor -WC10 9 Andrew Production Technician - WC45 10 Andy Production Technician - WC30 11 Angela Production Technician - WC50 12 Anibal Production Technician - WC20 Summary: 1. All non-aggregate columns selected must be listed in the GROUP BY clause. 2. Integers cannot be used in the GROUP BY to represent columns after the SELECT keyword, similar to using the ORDER BY clause. 3. The GROUP BY clause is generally not necessary unless using aggregate functions. 4. If we GROUP, the results are not necessarily sorted; although in many cases they may come out in an intuitive order, that's not guaranteed by the GROUP clause. If we want our groups sorted, always use an explicity ORDER BY after the GROUP BY. – Dave Costa 5. Processing of "group by" or "order by" clause often requires creation of Temporary tables to process the results of the query. Which depending of the result set can be very expensive. And, further updates on difference between questions and answers, please visit my blog @ http://onlydifferencefaqs.blogspot.in/