Tag Archives

2 Articles

MSSQL datediff in seconds

The following command on a Microsoft SQL Server calculates the difference in seconds between two datetimes:

DATEDIFF(SECOND, date1, date2)

Example query:

  SELECT 
	  date1,
	  date2,
	  DATEDIFF(SECOND, date1, date2) / 1000  as difference_in_seconds
  FROM [TEST].[dbo].[TestTableDatetime]

Result:

If you need the result as a text and also want to add 3 digits after the seconds you can use the following example:

SELECT 
	date1,
	date2,
	CONVERT(VARCHAR(12),  DATEDIFF(MILLISECOND, date1, date2) / 1000)  + ','   
	+ RIGHT('000' + CONVERT(VARCHAR(4), DATEDIFF(MILLISECOND, date1, date2) % 1000), 3) 
		as difference_in_seconds_as_text
FROM [TEST].[dbo].[TestTableDatetime]

Result:

Oracle top 1 record

To select the top 1 records from an oracle database, you filter with the where statement on rownum = 1:

select * from my_table where rownum = 1

If you want to select top 10 records from the table you use the following statement:

select * from my_table where rownum <= 10