Search code examples
sqloracle-databasedatetimesubquerywhere-clause

SQL Converting the date format in where clause


When trying to connect two tables with a where exists clause, but the results don't get matched because of the time portions of my dates. The date in table 1 is 2020-09-01 00:00:00 and in table 2 is 2020-09-01 12:54:00.

How do I format the date to match only based on YYYY-MM-DD?

SELECT * 
FROM  table1 a 
WHERE exists (
    SELECT '1' 
    FROM table2 b 
    WHERE a.company = b.company 
        AND a.emp =b.emp AND a.account_date = b.account_date
    )

Solution

  • In Oracle, you can use trunc():

    SELECT * 
    FROM table1 a 
    WHERE exists (
        SELECT 1 
        FROM table2 b 
        WHERE 
            a.company = b.company 
            AND a.emp = b.emp 
            AND trunc(a.account_date) = trunc(b.account_date)
    )
    

    It is often more efficient to express the date condition as follows:

    WHERE
        ...
        AND b.account_date >= trunc(a.account_date) 
        AND b.account_date < trunc(a.account_date) + 1