Informatics Practices

What is the difference between the order by and group by clauses when used along with a select statement? Explain with an example.

SQL Queries

3 Likes

Answer

ORDER BY:

The ORDER BY clause is used to sort the result set in ascending or descending order based on one or more columns.

Example:

SELECT *
FROM Vehicles
ORDER BY Price ASC;

This query selects all columns (*) from the Vehicles table and sorts the result set in ascending order (ASC) based on the Price column. The output will display the vehicles with the lowest price first.

GROUP BY:

The GROUP BY clause is used to group the result set based on one or more columns. It divides the result set into groups, and each group contains rows with the same values in the specified columns.

Example:

SELECT Type, AVG(Price) AS Average_Price
FROM Vehicles
GROUP BY Type;

This query selects the Type column and calculates the average price (AVG(Price)) for each group of vehicles with the same Type. The result set will display the average price for each type of vehicle.

Answered By

2 Likes


Related Questions