Home > other >  How to fetch the column which have the data in postgres?
How to fetch the column which have the data in postgres?

Time:12-29

enter image description here

I need to fetch the data in this table based on the section_id. for a section id, only one column of the data will be available. I need to fetch only the column which has data.

Example:

  1. if I pass the section_id = 43, it should return only the (id,section_id,genre_id,created_at,created_by )
  2. if I pass the section_id = 51, it should return only the (id,section_id,performer_id,created_at,created_by )

How to create a query for this on PostgreSQL ?

CodePudding user response:

Assuming that only the genre_id or performer_id column would have non null data, you should be able to simply use COALESCE() here:

SELECT id, section_id, COALESCE(genre_id, performer_id), created_at, created_by
FROM yourTable
ORDER BY 2, 3;
  • Related