#database #development #mysql #reading-list #sql
🔗 For each loops with LATERAL Joins
It is easy to join data with SQL. However, sometimes dependent joins returning just a tiny subset of the joined table's data is badly needed. With LATERAL Joins, the familiar for each loop can be replicated in SQL.
When joining multiple tables, the rows of both tables are linked together based on some conditions. However, when the result should e.g. be limited to the last three bought products for every customer, the standard join clause will not work: The joined bought products table can not be limited to only include three rows for every customer. That is not how joins do work, all rows matching the join criteria are included. But with lateral joins, a subquery will be joined instead of a table which is executed once for every customer resulting in a for-each loop equivalent in SQL.
⚠️ This post links to an external website. ⚠️
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.