SQL query for today's date minus two months

SqlSql Server

Sql Problem Overview


I want to select all the records in a table where their date of entry is older then 2 months.

Any idea how I can do that?

I haven't tried anything yet but I am on this point:

SELECT COUNT(1) FROM FB WHERE Dte > GETDATE()

Sql Solutions


Solution 1 - Sql

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Solution 2 - Sql

Would something like this work for you?

SELECT * FROM FB WHERE Dte >= DATE(NOW() - INTERVAL 2 MONTH);

Solution 3 - Sql

TSQL, Alternative using variable declaration. (it might improve Query's readability)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.

Solution 4 - Sql

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

Solution 5 - Sql

I use this on SQL Server:

SELECT 

DATEADD(MONTH,-2,GETDATE()) '- 2 months'

FROM MyTable

Solution 6 - Sql

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLazialeView Question on Stackoverflow
Solution 1 - SqlAbe MiesslerView Answer on Stackoverflow
Solution 2 - SqlgeeknikView Answer on Stackoverflow
Solution 3 - SqlArthur ZennigView Answer on Stackoverflow
Solution 4 - SqlGeorge SEDRAView Answer on Stackoverflow
Solution 5 - SqlTheOxView Answer on Stackoverflow
Solution 6 - SqlMarcView Answer on Stackoverflow