Search code examples
sql-serverquotes

What is the difference between quote and double quote in mssql


Is there a difference in these two expressions for example?

Select [column] as 'column1' from [table]
Select [column] as "column1" from [table]

Solution

  • Single quotes are for literal strings. Double quotes are the ANSI SQL Delimit Identifier for object names (T-SQL's delimit identifier is brackets ([])).

    Don't use single quotes (') for aliases though, as (as mentioned) single quotes are for literal strings, not delimit identifying object names. Single quotes only work as delimit identifiers on aliases when you define said alias, no where else. This means that you can easily confuse those new to the language (and even those who've been using it for years if your formatting is poor).

    As an example, ORDER BY 'column1' would not order by your column aliased as 'column1', it would order by the varchar literal 'column1'; effectively your data would not be ordered at all and would be returned in an arbitrary order (as every row has the same value for it ordering). Like wise in the following the 1st statement would return no rows and the second would error:

    SELECT 'Column1'
    FROM (SELECT [Column] + '_suffix' AS Column1
          FROM dbo.MyTable) MT
    WHERE 'Column1' LIKE 'ID%';
    GO
    SELECT 'Column1' + 2
    FROM (SELECT [SomeIntColumn] AS 'Column1'
          FROM dbo.MyTable) MT;
    

    The first would return no rows as the literal varchar value 'Column1' will never be LIKE 'ID%'. The second would error as although the column has been aliased as 'Column1', and it's name suggests it's an int column, the outer SELECT would try to convert the literal varchar value 'Column1' to an int, and (obviously) that won't work.

    Also some syntaxes with literal string aliases are deprecated (specifically 'string_alias' = expression).

    Stick to object and alias names that don't need delimit identifying, and if you must delimit identify them use the T-SQL identifier, brackets ([]), or ANSI-SQL's, double quotes ("). column1 does not need identifying, so you should just define is as column1.