# Need help with a query: search by username instead of user\_id

**URL:** https://meta.discourse.org/t/need-help-with-a-query-search-by-username-instead-of-user-id/157366
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [July 10, 2020, 2:43pm UTC](https://meta.discourse.org/t/need-help-with-a-query-search-by-username-instead-of-user-id/157366 "2020-07-10T14:43:47Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Ed\_Bobkov](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/ed_bobkov/32/200014_2.png) [@Ed\_Bobkov](https://meta.discourse.org/u/Ed_Bobkov)
#### Post date: [July 10, 2020, 2:43pm UTC](https://meta.discourse.org/t/need-help-with-a-query-search-by-username-instead-of-user-id/157366/1 "2020-07-10T14:43:47Z")

</div>

Please, help me to change the search. I need to search by username instead of user\_id.

This is my query:

```
-- [params]
-- string :query = white_check_mark
-- integer :user
-- date :start_date
-- date :end_date

SELECT created_at, topic_id, p.id as post_id FROM posts p
LEFT JOIN post_search_data psd ON psd.post_id = p.id
WHERE psd.search_data @@ TO_TSQUERY(:query)
AND user_id = :user
AND p.created_at BETWEEN :start_date::date
AND :end_date::date

```

---

<div class="post-metadata">

### Author: ![michebs](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/michebs/32/190102_2.png) [@michebs](https://meta.discourse.org/u/michebs)
#### Post date: [July 10, 2020, 3:31pm UTC](https://meta.discourse.org/t/need-help-with-a-query-search-by-username-instead-of-user-id/157366/2 "2020-07-10T15:31:37Z")

</div>

I hope it helps you.

```
-- [params]
-- string :query = white_check_mark
-- string :user
-- date :start_date
-- date :end_date

SELECT 
    p.created_at, 
    p.topic_id, 
    p.id as post_id 
FROM posts p
LEFT JOIN users u ON (p.user_id = u.id)
LEFT JOIN post_search_data psd ON psd.post_id = p.id
WHERE psd.search_data @@ TO_TSQUERY(:query)
      AND LOWER(username) LIKE '%'||LOWER(:user)||'%'
      AND p.created_at BETWEEN :start_date::date
      AND :end_date::date

```

---

<div class="post-metadata">

### Author: ![Ed\_Bobkov](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/ed_bobkov/32/200014_2.png) [@Ed\_Bobkov](https://meta.discourse.org/u/Ed_Bobkov)
#### Post date: [July 10, 2020, 5:44pm UTC](https://meta.discourse.org/t/need-help-with-a-query-search-by-username-instead-of-user-id/157366/3 "2020-07-10T17:44:43Z")

</div>

Yes, that works. Thank you for your time!
