# Can I use subquery in fragments?

**URL:** <https://forum.elixirforum.com/t/can-i-use-subquery-in-fragments/41239>\
**Category:** Questions\
**Tags:** ecto\
**Created:** [July 25, 2021, 5:33pm UTC](https://forum.elixirforum.com/t/can-i-use-subquery-in-fragments/41239 "2021-07-25T17:33:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ccstorch](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/c/2acd7d/32.png) [@ccstorch](https://forum.elixirforum.com/u/ccstorch)\
**Post date:** [July 25, 2021, 5:33pm UTC](https://forum.elixirforum.com/t/can-i-use-subquery-in-fragments/41239/1 "2021-07-25T17:33:44Z")

</div>

Hello!

I am stuck with a problem and can’t seem to find an easy solution.

I have a column on postgres, it is an array of integers (`[]int4`), and I want to check if one array overlaps the other. I was able to do this with fragments:

```elixir
group_ids = [1,2]
query
|> where([e], fragment("? && ?", , e.group_ids))

```

But the problem is that group\_ids is from another query, and I want to use as a subquery, like this:

```elixir
query
|> where([e], fragment("? && ?", subquery(group_ids_query), e.group_ids))

```

The only solution that worked for me was querying first the group\_ids and then do the main query. But it is something that I can do in a single query with SQL, but can’t do it with Ecto.

Is there a way to use subqueries inside fragments?  
If not, is there any alternative?

---

<div class="post-metadata">

**Author:** ![aziz](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/aziz/32/35984_2.png) [@aziz](https://forum.elixirforum.com/u/aziz)\
**Post date:** [July 25, 2021, 7:14pm UTC](https://forum.elixirforum.com/t/can-i-use-subquery-in-fragments/41239/2 "2021-07-25T19:14:02Z")

</div>

Maybe you can solve this by using `with_cte`?

```elixir
query
|> with_cte("group_ids", as: ^subquery(group_ids_query))
|> where([e], fragment("(SELECT * FROM group_ids) && ?.group_ids", e))

```

Not sure. I’d be surprised if this worked. 😄
