
Joins Using the Not-equal Operator
The not-equal join (<>) is rarely used. As a general rule, not-equal joins make sense only when used with a self-join. For example, this not-equal Transact-SQL join and self-join are used to find the subcategories that have at least two different prices less than $15:
USE AdventureWorks;
GO
SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPrice
FROM Production.Product p1
INNER JOIN Production.Product p2
ON p1.ProductSubcategoryID = p2.ProductSubcategoryID
AND p1.ListPrice <> p2.ListPrice
WHERE p1.ListPrice < $15 AND p2.ListPrice < $15
ORDER BY ProductSubcategoryID; Note: |
|---|
|
The expression NOT column_name = column_name is equivalent to column_name <> column_name. |
The following Transact-SQL example uses a not-equal join combined with a self-join to find all the rows in the ProductVendor table in which two or more rows have the same ProductID but different VendorID numbers (that is, products that have more than one vendor):
USE AdventureWorks;
GO
SELECT DISTINCT p1.VendorID, p1.ProductID
FROM Purchasing.ProductVendor p1
INNER JOIN Purchasing.ProductVendor p2
ON p1.ProductID = p2.ProductID
WHERE p1.VendorID <> p2.VendorID
ORDER BY p1.VendorID