Search code examples
sqlsql-serveradventureworks

SQL Server - Syntax error near "Primary" upon execution


When execute my SELECT statement I receive a syntax error near "Primary". What am I missing?

SELECT Name
FROM Production.Product
WHERE ProductID IN (SELECT ProductID FROM Production.ProductProductPhoto WHERE Primary = 1);

Solution

  • First: You should write "Primary" between square brackes [Primary]. Because it is a reserved word.

    EDIT

    And, if you should narrow your results to the products that has only a primary photo, you have to add a second where condition:

    SELECT Name
    FROM Production.Product
    WHERE 
        ProductID IN (SELECT ProductID FROM Production.ProductProductPhoto WHERE [Primary] = 1)
        AND ProductID NOT IN (SELECT ProductID FROM Production.ProductProductPhoto WHERE [Primary] = 0);