← Back to PostgreSQL Course | Chapter 8: Subqueries & CTEs | Lesson 7 of 7

Lateral Joins का उपयोग

LATERAL FROM में एक subquery को इससे पहले listed tables के columns refer करने देता है, एक per-row function की तरह।

In this page:

  1. Lateral Joins
Syntax
sql
SELECT columns
FROM table1 t1
CROSS JOIN LATERAL (
  SELECT columns FROM table2 t2 WHERE t2.key = t1.key LIMIT n
) sub;

Lateral Joins

एक LATERAL subquery preceding table की प्रति row एक बार चलता है और उस row की values इस्तेमाल कर सकता है, उदाहरण के लिए ORDER BY ... LIMIT 3 के साथ हर customer के latest तीन orders fetch करने के लिए।

यह top-N-per-group problems के लिए PostgreSQL का answer है। JOIN LATERAL ... ON true syntax को valid रखता है।

Note:
  • LEFT JOIN LATERAL ...
  • ON true बिना orders वाले customers रखता है।

उदाहरण: Lateral joins

bash
shop=# SELECT c.name, o.id AS order_id, o.total
shop-# FROM customers c
shop-# CROSS JOIN LATERAL (
shop(#   SELECT id, total FROM orders WHERE customer_id = c.id ORDER BY total DESC LIMIT 2
shop(# ) o
shop-# ORDER BY c.id, o.total DESC;
 name | order_id | total
------+----------+-------
 Ada  |       11 |    70
 Ada  |       10 |    50
 Bob  |       13 |    95
 Bob  |       12 |    20

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. LATERAL भूल जाना और missing columns के बारे में एक error पाना
  2. बिना indexes के बड़ी tables पर इसे इस्तेमाल करना
  3. इसे WHERE में एक correlated subquery से confuse करना
चैप्टर सारांश
  • LATERAL subqueries earlier tables देख सकती हैं
  • प्रति outer row चलता है
  • Top-N per group के लिए great
  • JOIN LATERAL के साथ ON true इस्तेमाल करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.