TSQL show only first row

In SQL Server you can use TOP:

SELECT TOP 1 MyTable1.Date
FROM MyTable1 
INNER JOIN MyTable2 
  ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' 
ORDER BY MyTable1.Date DESC

If you need to use DISTINCT, then you can use:

SELECT TOP 1 x.Date
FROM
(
   SELECT DISTINCT MyTable1.Date
   FROM MyTable1 
   INNER JOIN MyTable2 
     ON MyTable1.Id = MyTable2.Id
    WHERE Name = 'John' 
) x
ORDER BY x.Date DESC

Or even:

SELECT MAX(MyTable1.Date)
FROM MyTable1 
INNER JOIN MyTable2 
  ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' 
--ORDER BY MyTable1.Date DESC

Tags:

Tsql

Select

Limit