ORDER BY Clause

Estimated reading: 2 minutes 18 views

1. How do you sort records in ascending or descending order? Provide an example.

You can sort records using the ORDER BY clause. By default, it sorts in ascending order. To sort in descending order, use the DESC keyword.
Example:

				
					SELECT * FROM employees 
ORDER BY salary ASC;  -- Ascending order (default)

				
			
				
					SELECT * FROM employees 
ORDER BY salary DESC;  -- Descending order

				
			

2. Write a query to sort rows by multiple columns.

You can sort by multiple columns by specifying them in the ORDER BY clause, separated by commas.
Example:

				
					SELECT * FROM employees 
ORDER BY department_id ASC, salary DESC;

				
			

This sorts first by department_id in ascending order, and within each department, it sorts by salary in descending order.

3. How can you sort records by a computed value in SQL?

You can sort by a computed value by including the expression in the ORDER BY clause.
Example:

				
					SELECT name, salary * 12 AS annual_salary 
FROM employees 
ORDER BY annual_salary DESC;

				
			

This sorts employees based on their annual salary (calculated by multiplying the monthly salary by 12).


4. Explain the difference between ORDER BY and GROUP BY.

  • ORDER BY: Sorts the result set by one or more columns in ascending or descending order. It is applied to the entire result set after the query is executed.
  • GROUP BY: Groups rows that have the same values in specified columns into summary rows, typically used with aggregate functions.

Example:

  • ORDER BY:
				
					SELECT name, salary FROM employees 
ORDER BY salary DESC;

				
			

This sorts all employees by salary in descending order.

  • GROUP BY:
				
					SELECT department_id, COUNT(*) AS total_employees 
FROM employees 
GROUP BY department_id;

				
			

Leave a Comment

Share this Doc

ORDER BY Clause

Or copy link

CONTENTS