Ahmad Swultra
05/09/2022, 11:11 AMleft join
and `pagination `and call this function whenever the user wants to fetch data and when it reaches 10 rows it calls the function again to fetch the other rows and so on...Scott P
05/09/2022, 8:09 PMWHERE
statements at the end. By moving those WHERE
statements to the innermost query, it reduces the amount of data PG has to search through. Do this, and you can often improve the execution time of a query by 2 - 10x .
- LATERAL
is something that doesn't seem to be mentioned much unless you go looking for it. It allows you to reference other subqueries without having to nest queries inside each other and can make it much easier to debug and read your query codeAhmad Swultra
05/10/2022, 3:48 PMAhmad Swultra
05/10/2022, 4:09 PMSELECT p.*, COALESCE(c.LikesCount, 0) LikesCount
FROM Posts p
LEFT JOIN (
SELECT postId, COUNT(*) LikesCount
FROM PostsLikes
GROUP BY postId
) c ON c.postId = p.id
ORDER BY p.id DESC
LIMIT 0,10
Then when the user gets the first 10 I will fetch the other 10 rows and so on by calling this function.
But what I'm thinking is for each Post to have a column called `LikesCount `and create a `Trigger `that works when a new row is added in the table of `PostsLikes `and then increase the value of the `LikesCount `in the table of Posts
. in This way I no longer need to create a function to do complex operations like LEFT JOIN and COUNT(*) the rows... but will triggers work well without performance issues or impacts.Ahmad Swultra
05/10/2022, 5:11 PM