Order By Clause in SQL Server
This Order By Clause tutorial guides you to how we can use
order by clause in the SQL server.
ORDER BY clause is used to sort the records fetched from the database table. The ORDER BY clause is used with SELECT statements only.
When we use the SELECT statement to fetch data from a table,
the order of rows in the result set is not maintained.
The SQL Server can return a result set with an unspecified
order of rows.
The way it can return the result set in proper and well maintained
then we have to use Order by clause.
Syntax:-
SELECT columns
FROM table_name
where conditions
ORDER BY expressions [ASC/DESC]
Parameters or Arguments:-
expressions
The columns on which we need to apply for the order by clause.
tables
The table from which you need to fetch data from the database.
WHERE conditions
This parameter is optional these conditions filter data fetched
from the database table.
ASC
Optional. It sorts the result set in ascending order by expression
DESC
Optional. It sorts the result set in descending order by expression.
SQL Server ORDER BY clause example
1. Order by clause on
one column to order in ascending order
Note:- If not applied asc|desc after expression then it defaults fetch result with asc
2. Order by clause on
one column to order in descending order
this example returns the result set with firstname expression in descending order
3. Order by clause on the relative position
Relative position means result set is returned according to selecting column number as here firstname is at #1 in the select statement so the order by clause is applied on firstname as asc
4. Order by clause with
both ASC and DESC
No comments:
Post a Comment