PostgreSQL – INNER JOIN

The INNER JOIN operation is used to retrieve records that have matching values in both tables being joined. It combines data from two or more tables based on a common column, and it only includes rows where there is a match in both tables.

The basic syntax of an INNER JOIN is as follows:

SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Here’s a step-by-step explanation:

  1. SELECT columns: Specify the columns you want to retrieve from the combined result.
  2. table1 and table2: The names of the tables you’re joining.
  3. ON table1.column = table2.column: This is the condition that specifies how the tables should be joined. It indicates which columns in the two tables should be compared for matches.

Here’s an example using two tables, orders and customers, with a common column customer_id:

SELECT orders.order_id, orders.order_date, customers.customer_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id;

In this example, the query retrieves the order_id and order_date from the orders table and the customer_name from the customers table. The INNER JOIN operation is based on the customer_id column, which is common to both tables. Only orders with matching customer IDs and corresponding customer names will be included in the result set.

INNER JOIN is particularly useful when you want to combine data from different tables based on a specific relationship or key. It allows you to retrieve only the records that have matching entries in both tables, filtering out unmatched records.

Similar Posts