SQL SELECT from Multiple Tables

SQL SELECT from Multiple Tables

SQL SELECT from Multiple Tables

When working with relational databases, retrieving data from multiple tables is a common requirement. The SELECT statement allows us to fetch specific fields from different tables by using JOIN queries to establish relationships between them.

Complete Python Course with Advance topics:-Click Here
SQL Tutorial :-Click Here

Example Query for Selecting from Multiple Tables

Let’s consider an example where we have two supplier-related tables and an orders table. Using the INNER JOIN clause, we can retrieve relevant data from both tables:

SELECT orders.order_id, suppliers.company_name   
FROM suppliers  
INNER JOIN orders  
ON suppliers.supplier_id = orders.supplier_id  
ORDER BY order_id;  

Consideration of Three Tables Example

Suppose we have three tables: two customer tables named client1 and client2, and a sales table that stores product sales information.

client1 Table:

client_id first_name
101 Alice
102 Bob

client2 Table:

client_id last_name
101 Johnson
102 Smith

sales Table:

sale_id client_id product_name
501 101 Laptop
502 102 Smartphone
503 C101 Printer
504 C102 Desk

SQL Query to Select from Multiple Tables

The following SQL query uses LEFT JOIN to retrieve data from the sales table while including information from both client1 and client2 tables:

SELECT s.sale_id, s.client_id, s.product_name, c1.first_name, c2.last_name  
FROM sales AS s  
LEFT JOIN client1 AS c1  
ON s.client_id = c1.client_id  
LEFT JOIN client2 AS c2  
ON s.client_id = c2.client_id;  

Expected Output:

sale_id client_id product_name first_name last_name
501 101 Laptop Alice Johnson
502 102 Smartphone Bob Smith
503 C101 Printer NULL NULL
504 C102 Desk NULL NULL

Explanation:

  • The LEFT JOIN ensures that all records from the sales table are returned, even if there is no matching record in client1 or client2.
  • If a corresponding match is found in client1 or client2, it retrieves the respective values; otherwise, it returns NULL.

Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE

Conclusion

Fetching data from multiple tables using SQL joins is an essential technique that helps in efficiently combining and analyzing data from different sources. With proper table relationships and join conditions, you can get meaningful insights with ease.

For more such professional tutorials, stay tuned to updategadh!


sql select multiple tables without join
sql select from multiple tables with same column name
how to select data from two tables in sql with where clause
sql select from multiple tables with conditions
sql select from multiple tables with join
select data from multiple tables in single query
sql select from multiple tables w3schools
select from multiple tables mysql
sql join
sql
sql select from multiple tables example
sql select from multiple tables oracle
sql select from multiple tables multiple columns

Post Comment