simplified delete statement

Shambhu Rai 1,411 Reputation points
2023-09-12T20:22:57.67+00:00

Hi Expert,

can someone explain me the query below

DELETE FROM Sales.SalesPersonQuotaHistory   
FROM Sales.SalesPersonQuotaHistory AS spqh  
INNER JOIN Sales.SalesPerson AS sp  
ON spqh.BusinessEntityID = sp.BusinessEntityID  
and spqh.date= sp.date and spqh.sourcesystem= sp.sourcesystem
WHERE sp.SalesYTD > 2500000.00;

i want to simply this query without using from for 2 times ...but below query getting error

DELETE FROM Sales.SalesPersonQuotaHistory   spqh  INNER JOIN Sales.SalesPerson AS sp  
ON spqh.BusinessEntityID = sp.BusinessEntityID  
and spqh.date= sp.date and spqh.sourcesystem= sp.sourcesystem
WHERE sp.SalesYTD > 2500000.00;
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,494 questions
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,675 questions
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,337 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 120.2K Reputation points MVP
    2023-09-12T21:20:52.25+00:00

    You can skip the first FROM, but not the second if you are going to use a JOIN later.

    In ANSI syntax, FROM is mandatory and you need to say:

    DELETE FROM tbl WHERE ...
    

    But this FROM is optional in SQL Server.

    On the other hand, the ANSI syntax does not permit for the FROM clause in DELETE but you would have to write something like:

    DELETE FROM Sales.SalesPersonQuotaHistory
    WHERE EXISTS (SELECT * 
                 FROM  Sales.SalesPerson AS sp 
                 WHERE Sales.SalesPersonQuotaHistory AS spqh
                   AND Sales.SalesPersonQuotaHistory.BusinessEntityID = sp.BusinessEntityID
                   AND Sales.SalesPersonQuotaHistory.date= sp.date 
                   AND Sales.SalesPersonQuotaHistory.sourcesystem= sp.sourcesystem
                   AND p.SalesYTD > 2500000.00);
    
    
    

    And, yeah, since you cannot have a FROM clause, there is no provision to define an alias for the target table of the DELETE.

    But this is ANSI-compliant SQL. And most of us, don't care if we are ANSI-compliant or not.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.