Forum Discussion

Neils2401's avatar
Neils2401
Copper Contributor
Jul 22, 2024

SQL Query Incremental data load

I have source and staging tables & target table, I want to bring in incremental data into staging from source. I have 2 date columnCreatedDate and UpdatedDate to work with to bring in the incrementa...
  • LainRobertson's avatar
    LainRobertson
    Jul 22, 2024

    Neils2401 

     

    If you're not maintaining the reference timestamp outside of the source table, and instead, you're going to use the target table to determine a reference date, then you would leverage a subquery to pull the maximum value contained in either createdDate or updatedDate in that target table.

     

    This would look something like this:

     

    SELECT
    	[s].*
    FROM
    	[sourceTable] AS [s]
    WHERE
    	COALESCE([s].[updatedDate], [s].[createdDate]) > (
    		SELECT
    			CASE
    				WHEN MAX([t].[updatedDate]) >= MAX([t].[createdDate]) THEN MAX([t].[updatedDate])
    				ELSE MAX([t].[createdDate])
    			END
    		FROM
    			[targetTable] AS [t]
    	);

     

    Nothing changes prior to the original COALESCE, you're just changing the WHERE statement after the relational operator.

     

    Cheers,

    Lain

Resources