There is not a whole lot to say, but I found a few small things that could be improved.
###Consistency
Consistency
DECLARE @username as NVarchar(60) = RTRIM(LTRIM(##DisplayName:string? ##)); DECLARE @userId as int = ##UserId:int?-1##; DECLARE @limit as int = ##Limit:int?100##;
Would be better as:
DECLARE @userName AS NVARCHAR(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;
###Aliases
Aliases
I think your aliases mostly obfuscate the query. It's also recommended to explicitly state the type of join, e.g.:
FROM Posts AS posts
INNER JOIN Users AS users ON p.OwnerUserId = u.Id
INNER JOIN Posts AS questions ON p.ParentId = q.Id
###Trim
Trim
Your left and right trim operations don't really achieve anything. Do you expect a user name to have a bunch of white space before or after it? I'm not sure SE would even allow that. I removed them and got identical results.
Everything combined:
DECLARE @username AS NVARCHAR(60) = ##DisplayName:string? ##;
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;
SELECT TOP 100
users.Id AS [User Link],
posts.Id AS [Post Link],
posts.CreationDate
FROM Posts AS posts
INNER JOIN Users AS users ON posts.OwnerUserId = users.Id
INNER JOIN Posts AS questions ON posts.ParentId = questions.Id
WHERE
(@username = '' OR users.DisplayName = @username)
AND (@userId = -1 OR users.Id = @userId)
AND posts.Score = 0
AND posts.Id = questions.AcceptedAnswerId
ORDER BY posts.CreationDate DESC
###Eliminating the empty string check
Eliminating the empty string check
There is a way to eliminate the @username = ''
check, however it does have a performance impact. I ran it and it runs in ~400 ms, which is not bad but a bit slower. It makes the index scan on the [Users].[UIX_Users_Id]
table take longer due to partial string match.
WHERE
u.DisplayName LIKE CONCAT('%', @username, '%')
AND (@userId = -1 OR u.Id = @userId)
AND p.Score = 0
AND p.Id = q.AcceptedAnswerId