I have a T-SQL query and I want to make it faster.
I have Entity and Address tables, and wish to bring back an address if a mailing address exists.
Sometimes there are multiple addresses for any given entity. There is a primary mailing address tinyint that sometimes is set and sometimes not, there's no rules here there could be 5 default mailing addresses all the flag set or none with the flag set.
This runs at around 20 seconds for 11k rows I really need to get this time down, can anyone help?
SELECT
e.*, addr.*
FROM
[Entity] e
--Address does not always exist
--PrimaryAddress is a Not Null TinyInt, sometimes this flag is enable twice for a given entity.
LEFT OUTER JOIN
[Address] addr ON addr.[EntityID] = e.[EntityID]
AND addr.Code = 'MAILING'
AND addr.[AddressID] = (
--This remove duplicates but add's a long delay(15 seconds) to execution time.
SELECT Top 1 a.[AddressID]
FROM [Address] AS a
WHERE a.Code = 'MAILING'
AND a.[EntityID] = e.[EntityID]
ORDER BY a.[PrimaryAddress] DESC)
It should also be noted that I can't add any indexes to the two tables either :(
Kind regards Simon Jackson