﻿ SQL: Display each item producer company

# SQL Exercise: Display each item producer company

## SQL JOINS: Exercise-21 with Solution

From the following tables write a SQL query to select all rows from both participating tables as long as there is a match between pro_com and com_id.

Sample table: company_mast

Sample table: item_mast

Sample Solution:

``````SELECT *
FROM item_mast
INNER JOIN company_mast
ON item_mast.pro_com= company_mast.com_id;
``````

Output of the Query:

```pro_id	pro_name		pro_price	pro_com	com_id	com_name
101	Mother Board		3200.00		15	15	Asus
102	Key Board		450.00		16	16	Frontech
103	ZIP drive		250.00		14	14	Zebronics
104	Speaker			550.00		16	16	Frontech
105	Monitor			5000.00		11	11	Samsung
106	DVD drive		900.00		12	12	iBall
107	CD drive		800.00		12	12	iBall
108	Printer			2600.00		13	13	Epsion
109	Refill cartridge	350.00		13	13	Epsion
110	Mouse			250.00		12	12	iBall
```

Explanation:

The said SQL query that retrieves all columns from the table item_mast and company_mast and combines the data based on the join condition specified in the ON clause.
The join condition is that the 'pro_com' column in the item_mast table matches the 'com_id' column in the company_mast table. The result of the query is a new table that contains all the columns from both item_mast and company_mast, with rows that have matching values in the specified columns.

Relational Algebra Expression:

Relational Algebra Tree:

## Query Visualization:

Duration:

Rows:

Cost:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Customers from a different city than the salesmen.
Next SQL Exercise: Display the item name, price, and company name.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## SQL: Tips of the Day

Grouped LIMIT in PostgreSQL: Show the first N rows for each group?

```db=# SELECT * FROM xxx;
id | section_id | name
----+------------+------
1 |          1 | A
2 |          1 | B
3 |          1 | C
4 |          1 | D
5 |          2 | E
6 |          2 | F
7 |          3 | G
8 |          2 | H
(8 rows)
```

I need the first 2 rows (ordered by name) for each section_id, i.e. a result similar to:

```id | section_id | name
----+------------+------
1 |          1 | A
2 |          1 | B
5 |          2 | E
6 |          2 | F
7 |          3 | G
(5 rows)
```

PostgreSQL v9.3 you can do a lateral join

```select distinct t_outer.section_id, t_top.id, t_top.name from t t_outer
join lateral (
select * from t t_inner
where t_inner.section_id = t_outer.section_id
order by t_inner.name
limit 2
) t_top on true
order by t_outer.section_id;
```

Database: PostgreSQL

Ref: https://bit.ly/3AfYwZI

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook