In PL/SQL, the ORDER BY
clause is a vital tool that allows for the sorting of query results by one or more columns, either in ascending or descending order. In this article, We will learn about ORDER BY clause in PL/SQL, its syntax, functionality, and practical usage through examples.
Understanding ORDER BY in PL/SQL
- The
ORDER BY
clause in PL/SQL is used to sort the result set of a SQL query by one or more columns, either in ascending (ASC
) or descending (DESC
) order.
- Sorting the results helps to organize and present the data in a meaningful way, such as displaying records in alphabetical order, sorting by numeric values or ordering dates.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Key Terms:
- table_name: The name of the table from which to retrieve data.
- column1, column2, ...: The columns by which the result set will be sorted.
- ASC: It is used for Sorting the result set in ascending order (default behavior).
- DESC: It is used for Sorting the result set in descending or decreasing order.
Examples of PL/SQL ORDER BY Clause
To illustrate how the ORDER BY clause functions in PL/SQL, let's start by creating a table and inserting some sample data. We'll create a table named Employees with fields such as emp_id, name and salary. By setting up this example once, we can focus on understanding the effects of the ORDER BY clause without redundant table creation.
Creating the 'employee' Table
CREATE TABLE employee (
id INT,
name VARCHAR2(50),
salary NUMBER,
);
Inserting sample data
INSERT INTO employee (id, name, salary, join_date)
VALUES
(1, 'Aryan', 60000),
(2, 'Sam', 75000),
(3, 'Ritika', 65000),
(4, 'Bobby', 70000);
Output:
id | name | salary |
---|
1 | Aryan | 60000 |
2 | Sam | 75000 |
3 | Ritika | 65000 |
4 | Bobby | 70000 |
Example 1: Basic Sorting by 'salary' in Ascending Order
In this example, we will sort the list of employees based on their salary. By default, the ORDER BY clause sorts data in ascending order, meaning the lowest salary will appear first, and the highest salary will appear last. This is useful when you want to see the employees arranged from the least paid to the most paid.
Query:
SELECT id, name, salary
FROM employee
ORDER BY salary;
Output:
id | name | salary |
---|
1 | Aryan | 60000 |
3 | Ritika | 65000 |
4 | Bobby | 70000 |
2 | Sam | 75000 |
Explanation: Here, we use the ORDER BY clause followed by the salary column. Since we didn't specify any sorting direction, the query will automatically sort the results in ascending order. Here the employee with the smallest salary will appear at the top of the list, and the one with the highest salary will be at the bottom.
Example 2: Basic Sorting by 'salary' in Descending Order
In this query, we sort the list of employees by their salary in descending order using the ORDER BY clause with the DESC keyword. This means that the highest salary will appear first, and the lowest salary will appear last. By adding DESC we reverse the default ascending order.
This will make it easy to see which employees are earning the most at the top of the list and those earning the least at the bottom. This is useful when you want to quickly identify the highest-paid employees in the company.
Query:
SELECT * FROM employee
ORDER BY salary DESC;
Output:
id | name | salary |
---|
2 | Sam | 75000 |
4 | Bobby | 70000 |
3 | Ritika | 65000 |
1 | Aryan | 60000 |
Explanation: The output shows employees listed from highest to lowest salary. Sam, with a salary of $75,000, is at the top, followed by Bobby with $70,000. Next is Ritika with $65,000, and finally, Aryan with $60,000. This arrangement makes it clear who the highest-paid and lowest-paid employees are.
Example 3: Multilevel Sorting
In Multilevel Sorting the query sorts employees first by salary in descending order, such that the highest salaries come first and The employees with the same salary are sorted in ascending order by name. This ensures that within each salary group, names are listed alphabetically.
Query:
SELECT * FROM employee
ORDER BY salary DESC, name ASC
Output:
id | name | salary |
---|
2 | Sam | 75000 |
4 | Bobby | 70000 |
3 | Ritika | 65000 |
1 | Aryan | 60000 |
Explanation: The output shows employees are sorted first by salary, with highest salaries at the top. If multiple employees have the same salary, they are then sorted by name in alphabetical order. This ensures a clear ranking is done by salary and among those with identical salaries, the names are sorted alphabetically
Example 4: Sorting by relative position
We can also use the ORDER BY clause to sort the data by relative position in the result set, where the first field in the result is set to 1. The next field is 2, and so on. In the below example, the result set contains four columns. So, the relative position will be 1 for id, 2 for name, 3 for salary.
Query:
SELECT * FROM employee
ORDER BY 2 DESC;
Output:
id | name | salary |
---|
1 | Aryan | 60000 |
2 | Sam | 75000 |
3 | Ritika | 65000 |
4 | Bobby | 70000 |
Explanation: The result is sorted by name in descending order. The output after applying ORDER BY 2 DESC will give the above table as an output. Further, if you notice in the ORDER BY clause, we have specified 2 which means the following SQL Query will sort the data based on the name column.
Advanced Sorting Techniques
PL/SQL also supports more sophisticated sorting techniques, such as sorting by expressions or case-insensitive sorting. You can use expressions in the ORDER BY clause to sort based on calculated values or conditions. For example, you might sort employees by their adjusted salaries, where the adjustment could be based on bonuses or other factors.
Sorting Names Without Case Sensitivity
This query sorts the employee names in a case-insensitive manner by converting all names to lowercase for comparison. It ensures consistent alphabetical ordering regardless of original letter casing. The query sorts employee names without considering whether they are uppercase or lowercase.
By converting all names to lowercase using LOWER(name), it ensures that names are listed in alphabetical order consistently, regardless of how they were originally entered. This way, "Aryan" and "aryan" will be treated the same.
Query:
SELECT * FROM employee
ORDER BY LOWER(name);
Output:
id | name | salary |
---|
1 | Aryan | 60000 |
4 | Bobby | 70000 |
3 | Ritika | 65000 |
2 | Sam | 75000 |
Explanation: The output shows employees' names sorted alphabetically, treating all names as if they are in lowercase. This means names like "Aryan" and "bobby" are listed in a standard alphabetical order. The salaries are shown next to each name but do not affect the sorting
Sorting Based on Calculated Columns
The query creates a new column called adjusted_salary, which is calculated as half of each employee’s original salary (salary * 0.5). It then sorts the employees by this adjusted_salary in descending order, so the employees with the highest adjusted salaries are listed first.
Query:
SELECT id, name, salary * 0.5 AS adjusted_salary
FROM employees
ORDER BY adjusted_salary DESC;
Output:
id | name | salary |
---|
2 | Sam | 75000 |
4 | Bobby | 70000 |
3 | Ritika | 65000 |
1 | Aryan | 60000 |
Explanation: The output displays employees sorted from highest to lowest based on their adjusted_salary. Sam has the highest adjusted_salary because his original salary is the highest, so he appears at the top of the list. Bobby follows, then Ritika, and Aryan is last, reflecting their progressively lower adjusted salaries.
Key Points About ORDER BY Clause in PL/SQL
- Default Sorting Order: The default sorting order is ascending (ASC), so specifying ASC is optional.
- Multiple Columns: You can specify multiple columns for sorting, and the order of these columns affects the final sorting.
- Performance: Sorting large datasets can impact performance. Ensure appropriate indexes are used to optimize queries.
- Integration: The ORDER BY clause can be used with other clauses like WHERE, GROUP BY, and HAVING for refined data retrieval
Conclusion
The ORDER BY
clause is an essential component in PL/SQL for controlling the order of query results. By using this clause, developers can enhance the readability and usefulness of their data, whether by arranging records by a single column or employing more advanced techniques like case-insensitive sorting or sorting by calculated columns.
Similar Reads
SQLite ORDER BY Clause
SQLite is the most popular database engine which is written in C programming language. It is a serverless, easy-to-use relational database system and it is open source and self-contained. In this article, you will gain knowledge on the SQLite ORDER BY clause. By the end of this article, you will get
8 min read
PL/SQL GROUP BY Clause
The GROUP BY clause in PL/SQL is a powerful tool used to organize data into aggregated groups based on one or more columns. It is essential for performing summary operations on large datasets, enabling efficient data analysis by grouping rows that share common values.In this article, We will learn a
7 min read
MySQL Group By Clause
In MySQL, the GROUP BY clause is a powerful tool for grouping rows with the same values into summary rows, enabling efficient data analysis. It is often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data. In this article, We will learn about the
5 min read
SQLite Group By Clause
SQLite is a server-less database engine and it is written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we
6 min read
SQL ORDER BY
The ORDER BY clause in SQL is a powerful feature used to sort query results in either ascending or descending order based on one or more columns. Whether you're presenting data to users or analyzing large datasets, sorting the results in a structured way is essential. In this article, weâll explain
5 min read
MySQL ORDER BY Clause
In MySQL, the ORDER BY Clause is used to sort the result set either in ascending order or descending order. By default, the ORDER BY sorts the displayed data in ascending order. If you want your data displayed in descending order we need to use the DESC keyword along with the ORDER BY Clause. To mak
5 min read
PL/SQL LIMIT Clause
The LIMIT clause in PL/SQL is a powerful tool designed to manage the amount of data retrieved from a query, making it particularly useful for handling large datasets. By specifying the maximum number of rows to be fetched, the LIMIT clause helps in optimizing both performance and memory usage. In th
6 min read
PL/SQL HAVING Clause
The PL/SQL HAVING clause is a powerful tool used in SQL for filtering records in groups defined by the GROUP BY clause. While the WHERE clause filters individual rows, the HAVING clause filters groups based on aggregate functions like SUM, COUNT, MIN, and MAX. This clause is essential when we want t
5 min read
PostgreSQL - GROUP BY clause
The GROUP BY clause in PostgreSQL is an essential tool that allows us to group rows that share the same values in one or more columns. This powerful functionality is commonly used to perform aggregate calculations such as SUM(), COUNT(), AVG(), and more, enabling us to summarize data efficiently. In
4 min read
PL/SQL WITH Clause
The PL/SQL WITH clause is a powerful feature that enhances the readability and performance of your SQL queries. It allows you to define temporary result sets, which can be referenced multiple times within a single query. This feature is particularly useful for simplifying complex queries and improvi
5 min read