SQL Server SECOND() Function

SECOND() is a built-in SQL Server function used to extract the seconds (0-59) part from a datetime value. This function is typically used in conjunction with other date and time functions to achieve more complex date and time processing requirements.

Syntax

The syntax for the SECOND() function is as follows:

SECOND(date)

Where the date parameter is the datetime value from which to extract the seconds. This parameter can be a datetime value, a variable containing a datetime value, or a column containing a datetime value.

Use Cases

The SECOND() function is commonly used in scenarios where the seconds need to be retrieved from a datetime value. For example, you may need to query the exact time an order was created, as well as the number of seconds the order was created.

Examples

Here are two examples of using the SECOND() function:

Example 1

Assume you have an Orders table containing the order creation time and you need to query the exact time the order was created and the number of seconds when it was created. You can use the following query:

SELECT OrderID, OrderDate, SECOND(OrderDate) AS OrderSecond
FROM Orders

This query returns a result set containing the order ID, order creation time, and the number of seconds when the order was created. Suppose the result set returned is as follows:

OrderID OrderDate OrderSecond
1 2023-03-10 08:15:42.000 42
2 2023-03-11 11:35:12.000 12
3 2023-03-12 15:20:05.000 05

Example 2

Assume you need to query whether the number of seconds in a datetime value is even or odd. You can use the following query:

DECLARE @MyDateTime DATETIME = '2023-03-11 08:00:01.000'

SELECT IIF(SECOND(@MyDateTime) % 2 = 0, 'Even', 'Odd') AS SecondType

This query returns a result set containing the type of seconds (even or odd) in the datetime value. Suppose the result set returned is as follows:

SecondType
Odd

Conclusion

The SECOND() function is a convenient built-in SQL Server function used to retrieve the seconds part from a datetime value. In scenarios where date and time data needs to be queried or processed, the SECOND() function can be used in conjunction with other date and time functions to achieve more complex date and time processing requirements.