# How to fetch topics ordered by custom field iso8601 value?

**URL:** <https://meta.discourse.org/t/how-to-fetch-topics-ordered-by-custom-field-iso8601-value/166343>\
**Category:** Development\
**Created:** [October 6, 2020, 7:18am UTC](https://meta.discourse.org/t/how-to-fetch-topics-ordered-by-custom-field-iso8601-value/166343 "2020-10-06T07:18:02Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![david](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/david/32/157490_2.png) [@david](https://meta.discourse.org/u/david)\
**Post date:** [October 6, 2020, 10:27am UTC](https://meta.discourse.org/t/how-to-fetch-topics-ordered-by-custom-field-iso8601-value/166343/2 "2020-10-06T10:27:02Z")

</div>

> [@Stefan\_Brighiu\_M](#):
>
> How can I modify or add to this query so I load into memory only those 10 topics, and not more.

The `limit(10)` should do that already 🙂

> [@Stefan\_Brighiu\_M](#):
>
> need to sort data using the value of ‘importedSortDate’ custom field

This kind of thing should do it: (but not tested)

```ruby
Topic.where("category_id in (?)", [cat_id])
         .where("closed = ?", false)
         .joins("LEFT JOIN topic_custom_fields import_tcf ON import_tcf.topic_id = topic.id AND topic_custom_fields.name = 'importedSortDate'")
         .order("TIMESTAMP import_tcf.value")
         .order("created_at desc")
         .limit(10)

```

The problem is, asking postgres to cast the date string into a timestamp will be very inefficient. It will have to do the conversion for every single topic first, then pick the first 10.

There are a couple of options I can think of here - you could store the dates as “seconds since epoch”, rather than ISO8601. That will make them **much** easier for postgres to sort. Or you might be able to use a database migration to add an index to the topic\_custom\_fields table for `TIMESTAMP value`.

---

_[View the full topic](https://meta.discourse.org/t/how-to-fetch-topics-ordered-by-custom-field-iso8601-value/166343)._
