Search code examples
sqlsql-serverdate-formatting

SQL query to bring back list of servers from specific date range


I'm trying to make a query with SQL Server Management Studio 2017 that brings back a count of all the servers with a projected migration date of this year. I have one query made now, but it's still bringing back some servers with dates from years before.

SELECT MONTH(Projected) as [Month], count(*) as [Total] FROM dbo.tFake WHERE Projected >='01/01/2019' AND Projected <='12/31/2019 GROUP BY Month(Projected) ORDER BY [Month]

Date format is mm/dd/yyyy btw. How can I get this query to bring back just servers that are projected for the year 2019?


Solution

  • Going by the assumption that your data type is wrong, the first step is to fix that. Note, I am assuming that your data only contains dates, and not time (which your query implies). Firstly, you'll need to change the value of all your rows to an convertible value, we'll go with the ISO format yyyyMMdd:

    UPDATE dbo.tFake
    SET Projected = CONVERT(varchar(8),CONVERT(date,Projected,101),112);
    

    Now that all the rows are a literal string in the format yyyyMMdd we can alter the column:

    ALTER TABLE dbo.tFake ALTER COLUMN Projected date; 
    

    Now, we can run your query again, but now your data type is correct, you won't have the problem:

    SELECT MONTH(Projected) as [Month], count(*) as [Total]
    FROM dbo.tFake
    WHERE Projected >= '20190101' AND Project < '20200101' --I prefer the >= and < method. This is especially import with date & time data types
    GROUP BY Month(Projected)
    ORDER BY [Month];
    

    Notice the literal strings I passed are also in the yyyyMMdd format. If you must pass a literal string in the format MMddyyyy you can wrap in a CONVERT with the style code 101: CONVERT(date,'12/31/2019',101). 101 means the US style date (CAST and CONVERT (Transact-SQL).

    Remember, this solution assumes you have date only values, and not date and time values. If you do (have date and time values) you'll want to use an appropriate date and time data type and use the ISO8601 style, instead of the ISO style.