sqlsql-serverdate

2 date attributes stored as text strings need to be compared with earliest date selected


I have 2 date attributes stored as text strings that need to be compared with earliest date selected.

In the output shown here, you can see for ID 1 the earliest date has not been correctly identified using my code.

I have tried using casting and creating new columns but cannot find a way to compare the 2 date attributes in their current format, please can someone advise on how to do this.

Current query:

SELECT DISTINCT 
    A.[ID],
    A.[Date field 1 ],
    B.[Date field 2],
    CASE 
        WHEN A.[Date field 1 ] < B.[Date field 2] 
            THEN (A.[Date field 1 ])
        ELSE [Date field 2]
    END AS 'Earliest date'
FROM
    [TABLE A] A
JOIN 
    [TABLE B] B ON A.[ID] = B.[ID]
GROUP BY
    A.[ID], A.[Date field 1 ], B.[Date field 2]

Output:

ID  Date field 1        Date field 2        Earliest date
------------------------------------------------------------
1   02/08/2025 04:00    25/07/2025 15:58    02/08/2025 04:00
2   14/07/2025 04:08    25/07/2025 16:02    14/07/2025 04:08
3   14/07/2025 04:03    25/07/2025 16:11    14/07/2025 04:03
4   14/07/2025 04:03    25/07/2025 16:03    14/07/2025 04:03

Solution

  • If you keep your current design this is one correction you could use: The date strings need to be converted to the DATETIME datatype for proper comparison. I chose style 103 (British/French) because I saw 14/07/2025. I use TRY_CONVERT because of the possible formatting errors identified by Thom A.

    --Corrected Original Query
    SELECT DISTINCT 
      A.[ID],
      A.[Date field 1 ],
      B.[Date field 2],
      CASE 
      WHEN TRY_CONVERT(DATETIME,A.[Date field 1 ],103) IS NULL THEN 'Invalid date field 1'
      WHEN TRY_CONVERT(DATETIME,B.[Date field 2],103) IS NULL THEN 'Invalid date field 2'
      WHEN CONVERT(DATETIME,A.[Date field 1 ],103) < CONVERT(DATETIME,B.[Date field 2],103) THEN (A.[Date field 1 ])
      ELSE [Date field 2]
      END AS 'Earliest date'
      FROM
       [TABLE A] A
     JOIN [TABLE B] B 
     ON A.[ID] = B.[ID]
      group by  A.[ID],   A.[Date field 1 ],  B.[Date field 2]
    
    

    fiddle

    ID Date field 1 Date field 2 Earliest date
    1 02/08/2025 04:00 25/07/2025 15:58 25/07/2025 15:58
    2 14/07/2025 04:08 25/07/2025 16:02 14/07/2025 04:08
    3 14/07/2025 04:03 25/07/2025 16:11 14/07/2025 04:03
    4 14/07/2025 04:03 25/07/2025 16:03 14/07/2025 04:03
    5 31/02/2025 04:03 31/02/2025 16:03 Invalid date field 1
    6 14/07/2025 04:03 14/07/2025 04:02 14/07/2025 04:02
    7 14/07/2025 04:02 14/07/2025 04:03 14/07/2025 04:02