0% found this document useful (0 votes)
10 views3 pages

ORDER BY Clause - Sort Data in SQL - 1keydata

Uploaded by

vickroid007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

ORDER BY Clause - Sort Data in SQL - 1keydata

Uploaded by

vickroid007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3/2/2016 ORDER BY Clause ­ Sort Data In SQL | 1Keydata

SQL ORDER BY

SQL Data Warehousing CSS PHP HTML Database Normalization

SQL Tutorial Google Web Hosting


Build Your Online Presence With Google Sites. Free 30­Day Trial!
Basic SQL Commands
SQL SELECT
SQL DISTINCT
SQL WHERE SQL > SQL Commands > Order By
SQL AND OR
So far, we have seen how to get data out of a table using SELECT and WHERE commands. Often, however, we need to list
SQL IN
particular order. This could be in ascending order, in descending order, or could be based on either numerical value or tex
SQL BETWEEN
cases, we can use the ORDER BY keyword to achieve our goal.
SQL Wildcard
SQL LIKE The syntax for an ORDER BY statement is as follows:
SQL ORDER BY
SQL GROUP BY SELECT "column_name"
SQL HAVING FROM "table_name"
[WHERE "condition"]
SQL ALIAS
ORDER BY "column_name" [ASC, DESC];
SQL AS
SQL SELECT UNIQUE
The [ ] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before the ORDER BY
SQL JOIN
that the results will be shown in ascending order, and DESC means that the results will be shown in descending order. If n
SQL INNER JOIN
the default is ASC.
SQL OUTER JOIN
SQL LEFT OUTER JOIN It is possible to order by more than one column. In this case, the ORDER BY clause above becomes
SQL CROSS JOIN
SQL INSERT INTO ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]
SQL INSERT INTO SELECT
SQL UPDATE Assuming that we choose ascending order for both columns, the output will be ordered in ascending order according to co
SQL DELETE FROM tie for the value of column 1, we then sort in ascending order by column 2.
Advanced SQL
For example, we may wish to list the contents of Table Store_Information by Sales, in descending order:
SQL UNION
SQL UNION ALL Table Store_Information
SQL Inline View
SQL INTERSECT Store_Name Sales Txn_Date
SQL MINUS Los Angeles 1500 Jan-05-1999
SQL LIMIT San Diego 250 Jan-07-1999
SQL TOP San Francisco 300 Jan-08-1999
SQL Subquery Boston 700 Jan-08-1999
SQL EXISTS
SQL CASE we key in,
SQL DECODE
SQL AUTO INCREMENT SELECT Store_Name, Sales, Txn_Date
SQL IDENTITY FROM Store_Information
ORDER BY Sales DESC;
SEQUENCE & NEXTVAL

SQL Functions Result:


SQL Average
SQL COUNT
Store_Name Sales Txn_Date
SQL MAX
Los Angeles 1500 Jan-05-1999
SQL MIN
Boston 700 Jan-08-1999
SQL SUM
San Francisco 300 Jan-08-1999
SQL ROUND
San Diego 250 Jan-07-1999
String Functions
SQL CAST In addition to column name, we may also use column position (based on the SQL query) to indicate which column we wan
SQL CONVERT ORDER BY clause. The first column is 1, second column is 2, and so on. In the above example, we will achieve the same re
SQL CONCATENATE following command:
SQL SUBSTRING
SQL INSTR SELECT Store_Name, Sales, Txn_Date
SQL TRIM FROM Store_Information
ORDER BY 2 DESC;
[Link] 1/3
3/2/2016 ORDER BY Clause ­ Sort Data In SQL | 1Keydata
ORDER BY 2 DESC;
SQL LENGTH
SQL REPLACE
SQL TO_DATE
The column(s) we use to sort the result do not need to be in the SELECT clause. For example, the following SQL,

Date Functions
SELECT Store_Name
FROM Store_Information
ORDER BY Sales DESC;

works fine and will give the following result:

Store_Name
Los Angeles
Boston
San Francisco
San Diego

It is also possible to sort the result by an expression. For example, in the following table,

Table Product_Sales

Product_ID Price Units


1 10 9
2 15 4
3 25 3

we can use the following SQL to order the results by Revenue (defined as Price * Units):

SELECT Product_ID, Price*Units Revenue


FROM Product_Sales
ORDER BY Price*Units DESC;

Result:

Product_ID Revenue
1 90
3 75
2 60

Need Color Consultation?


Get Tailored Color Design Solutions Sign­Up for Free In House Quotation

Exercises

For these exercises, assume we have a table called User_Sales with the following data:

Table User_Sales

First_Name Last_Name Gender Join_Date Sales


Sophie Lee F Apr-05-2015 500
Richard Brown M Apr-05-2015 200
Jamal Santo M Apr-09-2015 350
Casey Healy M Apr-09-2015 80
Jill Wilkes F Apr-15-2015 210

1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT * FROM User_Sales ORDER BY Sales;
b) SELECT * FROM User_Sales ORDER BY Last_Name DESC;
c) SELECT * FROM User_Sales ORDER BY First_Name WHERE Sales > 100;
d) SELECT * FROM User_Sales ORDER BY Last_Name, First_Name;
[Link] 2/3
3/2/2016 ORDER BY Clause ­ Sort Data In SQL | 1Keydata

2. What is the result of the following query?


SELECT * FROM User_Sales WHERE Join_Date IN ('Apr-05-2015','Apr-15-2015') ORDER BY Sales;

3. What is the result of the following query?


SELECT * FROM User_Sales ORDER BY Join_Date DESC, Sales;

Show Answers

Next: SQL GROUP BY

Start Download
Convert Any File to a PDF. Get the Free From Doc to Pdf App!

Copyright © 2016 [Link] All Rights Reserved Privacy Policy About Contact

[Link] 3/3

Common questions

Powered by AI

The SQL ORDER BY clause can be effectively combined with commands like WHERE and SELECT to filter data sets before sorting. For instance, filtering sales records for a specific date range using WHERE clauses, then sorting them in descending order of sales provides a clear view of performance over a timeframe. Using ORDER BY with conditions allows for efficient data handling, especially vital for large datasets where both filtering and sorting dramatically improve data processing .

The ORDER BY clause interacts with SQL functions such as COUNT, MAX, and SUM by organizing the results these functions produce into a specified order. For instance, when using COUNT to tally records, ORDER BY can sort these counts to identify datasets with the highest or lowest occurrence. Similarly, for functions like MAX or SUM, ORDER BY helps rank datasets effectively for further analysis, such as prioritizing top-performing metrics in reports .

Ordering by columns not included in the SELECT clause allows for the desired sorting criteria without bloating the result set with unnecessary columns. This is important for minimizing data transfer and reducing output size, which is crucial when dealing with limited bandwidth or large datasets. It maintains concise and relevant query results while optimizing data readability and usability .

The SQL ORDER BY clause enhances data selection by allowing the sorting of query results in either ascending or descending order based on one or multiple columns, providing a more organized and human-readable output. This is particularly useful when dealing with large datasets where interpretation of unordered data could lead to inefficiencies or errors. For example, when working with sales data, ordering by sales figures can quickly highlight trends or outliers .

The syntax for the SQL ORDER BY clause is: SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC]. To sort by multiple columns, you extend the ORDER BY clause like so: ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]. This allows for hierarchical sorting, where the system first orders by column_name1 and then breaks ties using column_name2 .

When used with large datasets, the ORDER BY clause can lead to performance bottlenecks due to the need to sort potentially massive records, which can be resource-intensive. Optimization challenges include ensuring that indices exist on the columns being sorted, as this can significantly improve sorting speed. Additionally, using proper query design to limit dataset size before applying ORDER BY, such as via WHERE clauses, can also mitigate performance issues .

Expressions in the SQL ORDER BY clause allow complex data operations, such as calculations or concatenations, to be used as sorting criteria. This can add significant flexibility by facilitating custom ranking or reevaluating derived metrics, such as ordering products by total revenue calculated with price and units. This is beneficial for dynamic datasets where the importance of individual data points can be context-dependent on calculated values .

Ordering by expressions allows for more nuanced and meaningful ordering based on calculated factors rather than raw data values. For instance, ordering sales data by calculated revenue (Price*Units) rather than just price offers insights into actual business performance rather than potential price-led metrics. This approach ensures more practical analytics and strategic decision-making .

Using column position in the SQL ORDER BY clause can be preferable for simplicity and brevity, especially in cases where column names are lengthy or complex. It also reduces the chance of errors when column names change but positions remain the same. This method refers directly to the positional output of the SELECT clause, which can make the SQL statements more generalizable across similar table structures .

The ORDER BY clause significantly impacts query execution plans as it specifies the sequence of the results, often requiring additional sorting steps by the execution engine. This necessitates extra computational and memory resources, which can slow down query execution, particularly on large datasets. Query optimizers may alter execution strategies based on available indices or existing sorting, impacting overall performance .

You might also like