Search code examples
sqlperformancereadability

SQL - reducing duplication in SELECT and WHERE clause


Excuse the ambiguous title. But is there a way I can reduce duplication in SQL with the following query:

SELECT LTRIM(RTRIM(Address1))
FROM Customers
WHERE LTRIM(RTRIM(Address1)) = Address2

Notice LTRIM(RTRIM(Address1)) is duplicated? Can I avoid this


Solution

  • Correct way:

    Trim your data and store it in clean form if possible.


    Alternatively use subquery and decide if it is more readable:

    SELECT Address1
    FROM (SELECT LTRIM(RTRIM(Address1)) AS Address1, Address2
          FROM Customers) AS sub
    WHERE Address1 = Address2