I am trying to extract the first row I get after ordering the result by i_version_id
. If I do not use TOP(2)
, my query works as expected ans returns all results sorted by i_version_id. But when I add the TOP(2)
(as shown below), it says that there is a syntax error near distinct
. Please let me know what I am doing wrong.
SELECT TOP(2)
distinct(i_version_id)
FROM
[PaymentGateway_2006].[dbo].[merchant]
WHERE
dt_updated_datetime > '2013-11-11'
GROUP BY
i_version_id
ORDER BY
i_version_id;
Notice that the query “DISTINCT TOP 10” includes the first 10 rows from the query from the “DISTINCT” query. From this we know a DISTINCT list is first created, and then the TOP 10 items returned.
To do so, select Query -> Include Actual Query Plan from the menu before executing the query. The “Stream Aggregate” icon is for the DISTINCT operation and “Top” for the TOP 10 one. It may seem somewhat counterintuitive to see DISTINCT listed first within the SELECT statement.
Introduction to SQL Server SELECT DISTINCTclause Sometimes, you may want to get only distinct values in a specified column of a table. To do this, you use the SELECT DISTINCTclause as follows: SELECTDISTINCTcolumn_name FROMtable_name; Code language:SQL (Structured Query Language)(sql) The query returns only distinct values in the specified column.
ORDER BY items must appear in the select list if SELECT DISTINCT is specified. Because of this you must keep in mind, when using ORDER BY, that the ORDER BY items must appear in the select list when using Distinct. Good post with great examples.
If you're only getting the TOP 1
then distinct
is irrelevant. It's also irrelevant since grouping by the column will give you distinct values,
However, If you want more than one just remove the parentheses:
SELECT DISTINCT TOP(2)
i_version_id
FROM
[PaymentGateway_2006].[dbo].[merchant]
WHERE
dt_updated_datetime > '2013-11-11'
GROUP BY
i_version_id
ORDER BY
i_version_id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With