Ordering
Limiting the output
7. TOP n rows
Eliminating duplicate results
Aggregation
Grouping
HAVING: filtering and ordering groups
Let's practice

Instruction

Very nice! We'll show you another feature of SQL Server. By default, SQL Server returns every row that matches the given criteria. This is what we normally expect, of course, but there are cases when we might want to change this behavior.

The more rows the database has to fetch, the more time it takes. This isn't good, especially when we don't have to look at all the results and only need a small glimpse at the data. Take a look:

SELECT TOP 10
  *
FROM Order;

TOP n returns the first n rows from the result. This is much more efficient than returning all the data from the database.

You can see something similar in our sandbox environment here. Every time you run a query, it returns the first 20 rows. This way, you get the response faster.

Exercise

Select the top five rows of Salary and Position from the table Employee. Use the template provided.

Try running the template before solving the exercise in order to see the difference for yourself.

Stuck? Here's a hint!

Type:

SELECT TOP 5
  Salary,
  Position
FROM Employee;