# Ordering categories using SQL

**URL:** <https://meta.discourse.org/t/ordering-categories-using-sql/111960>\
**Category:** Development\
**Created:** [March 18, 2019, 9:37pm UTC](https://meta.discourse.org/t/ordering-categories-using-sql/111960 "2019-03-18T21:37:48Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)\
**Post date:** [March 18, 2019, 9:55pm UTC](https://meta.discourse.org/t/ordering-categories-using-sql/111960/2 "2019-03-18T21:55:38Z")

</div>

I’ve not tested this recently but here’s at least a hint for how to alpha-sort categories at the rails console:

```ruby
# alpha sort all categories matching search and their sub-categories

  def sort_matching_categories_and_subcategories(search)
    categories = Category.where("name like ?", search)
    position = 100
    categories.order(:name).each do |cat|
      position += 5
      cat.position = position
      cat.save!()
      c_position = 0
      children = Category.where(:parent_category_id=>cat.id)
      children.order(:name).each do |c|
        c_position += 5
        c.position = c_position
        c.save!()
      end
    end
  end

 # alpha sort subcategories of a single category matching search
def sort_matching_subcategories(search)
  categories = Category.where("name like ?", search)
  if categories.count > 1
    puts "Found more than one category"
  end
  categories.order(:name).each do |cat|
    c_position = 5
    children = Category.where(:parent_category_id=>cat.id)
    children.order(:name).each do |c|
      c_position += 5
      c.position = c_position
      c.save!()
    end
  end
end

```

---

_[View the full topic](https://meta.discourse.org/t/ordering-categories-using-sql/111960)._
