How list only rows of newer dates?

Microsoft SQL server

How to in a view only list the data rows for the last 3 years?


You need to have a column with the date in your fact table. If the date column in your fact table is a int, you have to join it with a date conversion table or use cast/convert.

We have used a date table (DM.dimdate).

The key_dimdate is a integer, and the date column is in the date format in SQL. The date format make it easy to compare it to a date question in SQL.

Create a SQL similar to this:

SELECT a.[Customer]
,a.[startDate] as [startDate]
,a.[endDate] as [endDate]
,a.[IsActive] as [IsActive]
FROM [DM].[facttable] a
inner JOIN [DM].[dimDate] f on a.[key_dimDate] = f.[key_dimDate]
where 1=1
and a.[IsActive] = 'Y'
-- and DATEADD(year, -3, GETDATE() ) < f.[Date] -- will list 3 years
and DATEADD(Quarter, -13, GETDATE() ) < f.[Date]  -- will list 39 months


If you get error like Column ‘id’ in field list is ambiguous, then you have missed to set the alias letter in front of all the columns references in the SQL query.

If you are getting an error: “Arithmetic overflow error converting expression to data type datetime.” Is that the F.Date in above SQL is a int, you have to convert it to a date somehow.

Only using CONVERT(DATETIME,[key_dimDate],103) can give overflow error.

Change the SQL to reflect your columns and tables.


More Information: 

Let’s say you need to add five months to current date, use this:

WHERE YourDate < DATEADD(month, 5, GETDATE())

I used function GETDATE() for getting current DateTime.

If you need to subtract some time, just add minus to second parameter:

WHERE YourDate < DATEADD(month, -5, GETDATE()) 


To see the SQL job log for a time period, try this in SQL server (will not work in Azure SQL)

@@SERVERNAME as ‘Server’, as ‘Job Name’,
jh.run_date as ‘Run Date’, jh.run_status as ‘Job Status’
FROM msdb.dbo.sysjobs j
SELECT ROW_NUMBER() OVER(PARTITION BY jh.job_id ORDER BY jh.run_date DESC) AS row_num, jh.*
FROM msdb.dbo.sysjobhistory jh
jh.step_id = 0 AND
jh.run_date >= CONVERT(varchar(8), DATEADD(DAY, -7, GETDATE()), 112) AND
jh.run_date <= CONVERT(varchar(8), GETDATE() + 1, 112)
–ORDER BY jh.run_date DESC
) AS jh ON jh.job_id = j.job_id
WHERE j.enabled = 1 AND jh.run_status = 0
ORDER BY, jh.run_date; 

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables
  • LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
  • FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table