Re: SQl help to build a result with custom aliased bool column

From: Arup Rakshit <ar(at)zeit(dot)io>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: SQl help to build a result with custom aliased bool column
Date: 2019-04-08 09:39:31
Message-ID: DA14E90F-BA29-42F4-AA3B-8D17D889348B@zeit.io
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I knew that will be more compact way. Thanks for showing it. One thing I still would like to handle is that, to make sure the column contains only True/False. But right now sometimes it shows NULL. How can I fix this?

id|name|active|
--|----|------|
1|f1 |true |
2|f2 |true |
3|f3 |false |
4|f4 | |

Thanks,

Arup Rakshit
ar(at)zeit(dot)io

> On 08-Apr-2019, at 3:28 PM, Szymon Lipiński <mabewlun(at)gmail(dot)com> wrote:
>
> Hey,
> you could just use
>
> SELECT
> features.id,
> features.name,
> company_features.company_id = 1 as active
>
> regards,
> Szymon
>
> On Mon, 8 Apr 2019 at 09:55, Arup Rakshit <ar(at)zeit(dot)io> wrote:
> I have 2 tables Company and Feature. They are connected via a join table called CompanyFeature. I want to build a result set where it will have id, name and a custom boolean column. This boolean column is there to say if the feature is present for the company or not.
>
> Company table:
>
> | id | name |
> |----|------|
> | 1 | c1 |
> | 2 | c2 |
> | 3 | c3 |
>
> Feature table:
>
> | id | name |
> |----|------|
> | 1 | f1 |
> | 2 | f2 |
> | 3 | f3 |
>
> Company Feature table:
>
> | id | feature_id | company_id |
> |----|------------|------------|
> | 1 | 2 | 1 |
> | 2 | 1 | 1 |
> | 3 | 3 | 2 |
>
> The result should look like for company `c1`:
>
> | id | name | active |
> |----|------|--------|
> | 1 | f1 | t |
> | 2 | f2 | t |
> | 3 | f3 | f |
>
> I tried something like:
>
> SELECT
> features.id,
> features.name,
> CASE WHEN company_features.company_id = 1 THEN
> TRUE
> ELSE
> FALSE
> END AS active
> FROM
> features
> LEFT JOIN company_features ON company_features.feature_id = features.id
>
> It works. But is there any better way to achieve this?
>
>
> Thanks,
>
> Arup Rakshit
> ar(at)zeit(dot)io
>
>
>
>
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Szymon Lipiński 2019-04-08 09:58:30 Re: SQl help to build a result with custom aliased bool column
Previous Message Arup Rakshit 2019-04-08 07:54:47 SQl help to build a result with custom aliased bool column