# Users In Specific Group(s) BUT NOT In Other Group(s)

**URL:** https://meta.discourse.org/t/users-in-specific-group-s-but-not-in-other-group-s/275159
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [14 mei 2019 om 14:50 UTC](https://meta.discourse.org/t/users-in-specific-group-s-but-not-in-other-group-s/275159 "2019-05-14T14:50:11Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![SvenC56](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/svenc56/32/132235_2.png) [@SvenC56](https://meta.discourse.org/u/SvenC56)
#### Post date: [14 mei 2019 om 14:50 UTC](https://meta.discourse.org/t/users-in-specific-group-s-but-not-in-other-group-s/275159/1 "2019-05-14T14:50:11Z")

</div>

## Users In Specific Group(s) BUT NOT In Other Group(s)

Info: The Parameters have to be written as arrays. For example: {1,2,3}

```sql
-- [params]  
-- string :opt_in_groups
-- string :opt_out_groups
SELECT
   u.id AS user_id,
   g.id AS GROUP_ID 
FROM
   users u 
   join
      group_users gu 
      ON gu.user_id = u.id 
   join
      GROUPS g 
      ON g.id = gu.group_id 
WHERE
   g.id = ANY (:opt_in_groups::int[]) 
   AND u.id NOT IN 
   (
      SELECT
         u.id AS user_id 
      FROM
         users u 
         join
            group_users gu 
            ON gu.user_id = u.id 
         join
            GROUPS g 
            ON g.id = gu.group_id 
      WHERE
         g.id = ANY (:opt_out_groups::int[]) 
   )
ORDER BY
   u.primary_group_id

```
