How can I optimize and speed up a query Below query never completes and runs for over 14 hours:

SELECT 
U.Age, U.CreationDate, U.DisplayName, 
P.AcceptedAnswerId, P.ClosedDate, p .Title, P.ViewCount,
C.CreationDate,C.Score ,C.UserId
FROM dbo.Users As U
LEFT JOIN dbo.Posts As P on U.id = P.id
LEFT JOIN dbo.Comments As C on U.id =C.id
WHERE
(
U.Location = 'India'
OR U.Location ='United Kingdom'
)
AND U.LastAccessDate&gt;= '04/02/2018'
AND U.LastAccessDate&lt; '06/02/2018'
AND P.LastActivityDate&gt;= '04/02/2018'
AND P.LastActivityDate&lt; '06/02/2018'
AND U.LastAccessDate&gt;= '04/02/2018'
AND U.LastAccessDate&lt; '06/02/2018'
AND U.Age&gt;10
AND U.Age is NOT NULL


How can I improve and speed it up ?
The biggest problem I see is in your joins. You're joining the "id" of Users, to the "id" of Posts and Comments. This basically says, take every record in Users and join it to every record in Posts, then join it to every record in Comments.

Presuming that the UserID exists as a foreign key in Posts and Comments, the code below should work. If not, you'll need to determine the correct foreign keys for the JOIN statements.

SELECT 
    U.Age, 
    U.CreationDate, 
    U.DisplayName,
    P.AcceptedAnswerId, 
    P.ClosedDate, 
    P.Title, 
    P.ViewCount,
    C.CreationDate,
    C.Score,
    C.UserId
FROM 
    dbo.Users AS U
    LEFT OUTER JOIN dbo.Posts AS P 
        ON U.UserID = P.UserID
    LEFT OUTER JOIN dbo.Comments AS C 
        ON U.UserID = C.UserID
WHERE
    U.Location IN ('India','United Kingdom')
    AND U.LastAccessDate&gt;= '04/02/2018'
    AND U.LastAccessDate&lt; '06/02/2018'
    AND P.LastActivityDate&gt;= '04/02/2018'
    AND P.LastActivityDate&lt; '06/02/2018'
    AND U.Age&gt;10


I replaced the location OR statement with an IN.

I removed the duplicated U.LastAccessDate conditions.

I removed the unnecessary U.Age IS NOT NULL condition.

If this query still runs slowly. My next best guess would be a missing index on Users.LastAccessDate and/or Posts.LastActivityDate.