0

I am trying to achieve as example below can someone help me out please.

now I am doing like this


CREATE TABLE transfers
id               serial,
init_by          varchar(50),
init_to          varchar(50),
to_location      varchar(50),
from_location    varchar(50)

SELECT id, init_to, to_location as location
FROM transfers WHERE init_by = 'abc';

SELECT id, init_from, from_location as location
FROM transfers WHERE init_to = 'abc';

Now I need to query 2 times and then merge both results. How can I achieve it in single query Thanks in advance.

Manishkumar Adesara
  • 2,221
  • 2
  • 6
  • 13
  • 2
    `UNION` or `UNION ALL`? – sticky bit Nov 27 '21 at 16:52
  • 1
    You can use UNION to combine the results , refer the [documentation](https://www.postgresql.org/docs/14/queries-union.html) – Anand Sowmithiran Nov 27 '21 at 16:53
  • sorry really I don't have any idea. how can I achieve that. – Manishkumar Adesara Nov 27 '21 at 16:53
  • SELECT id, init_to, to_location as location FROM transfers WHERE init_by = 'abc' UNION SELECT id, init_from, from_location as location FROM transfers WHERE init_to = 'abc'; – Anand Sowmithiran Nov 27 '21 at 16:55
  • Does this answer your question? [How to combine results of two queries into a single dataset](https://stackoverflow.com/questions/15230350/how-to-combine-results-of-two-queries-into-a-single-dataset) [Merge two SQL SELECT queries results into one query and one result](https://stackoverflow.com/q/30938721/1048572) Or even better [How do I combine 2 select statements into one?](https://stackoverflow.com/q/542705/1048572) – Bergi Nov 27 '21 at 16:57
  • By the way, your table doesn't have the init_from column..did you mean it as init_by ? – Anand Sowmithiran Nov 27 '21 at 16:57
  • @AnandSowmithiran, my bad – Manishkumar Adesara Nov 27 '21 at 17:04
  • Thanks to all UNION worked perfectly. – Manishkumar Adesara Nov 27 '21 at 17:07
  • No need for `UNION` or `UNION ALL`. Just use [an `OR`](https://www.postgresql.org/docs/14/functions-logical.html) in your `WHERE` clause: `SELECT id, init_to, to_location as location FROM transfers WHERE init_by = 'abc' OR init_to = 'abc';` – Andrew Henle Nov 27 '21 at 17:10

0 Answers0