Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select same fields from multiple tables using postgresql

Tags:

sql

postgresql

I have three tables that have four columns in common. I want a query that retrieves data from these four columns. For example, the four columns are id, name, email, phone. I want to retrieve data from those four columns.

Can someone help?

like image 388
Trung Tran Avatar asked Dec 19 '22 20:12

Trung Tran


1 Answers

Use UNION:

select id, name, email, phone
from table1

union

select id, name, email, phone
from table2

union

select id, name, email, phone
from table3;

In the above query identical rows from different tables will be presented as one row. If you want all rows from all tables use UNION ALL.

Use INTERSECT to select only identical rows in all three tables:

select id, name, email, phone
from table1

intersect

select id, name, email, phone
from table2

intersect

select id, name, email, phone
from table3;
like image 121
klin Avatar answered Jan 06 '23 04:01

klin