SQL TOP x Command
See more tutorials in Database. This post has Comments Off on SQL TOP x Command.
In this tutorial we will learn how to use the SQL TOP x Command. the SQL TOP x Command let’s you choose the TOP x number of rows from a SQL Table. This can be useful for finding the top 5 lowest/highest of a number in a table. The TOP x Command works great with the Order By Command.
Step 1. Creating the Table
1. Create a table called Sales with the Columns ID(Primary Key), Amount, and Name
2. Fill it out with 5 rows of data like below
Step 2. Creating the SQL Command
1. Now that we have the Data we can use the TOP 3 SQL Command to pull out the TOP 3 Rows with the highest Sales. Copy the code below and run it. You will notice that the TOP 5 command runs after the ORDER BY command despite the order that they appear in. So it will order them by the amount they sold then grab the TOP 3. This is how the TOP x command becomes useful with large tables when you only need a certain amount of data.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//
<form id=“form1” runat=“server”>
<asp:SqlDataSource ID=“SqlDataSource1” runat=“server”
ConnectionString=“<%$ ConnectionStrings:ConnectionString %>“
SelectCommand=“SELECT TOP 3 [Amount], [Name] FROM [Sales]
ORDER BY Amount DESC”></asp:SqlDataSource>
<asp:GridView ID=“GridView1” runat=“server” AutoGenerateColumns=“False”
<asp:BoundField DataField=“Amount” HeaderText=“Amount”
<asp:BoundField DataField=“Name” HeaderText=“Name”
2. It Should display this once you run it.
In this Tutorial we learned what the TOP x command in SQL can do and why it is useful. We also learned how to use it and a basic overview of the SQL command structure and how the order of the command structure works.