0

I am trying to convert SQL code to Seqel to run it from my script. How do I convert this:

select code, count(1) as total 
from school_districts 
group by code order by total desc;

into Sequel? Or, is there a way to pass raw SQL to Sequel? Also the school_districts will be interpolated #{table_name}.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
suyesh
  • 530
  • 7
  • 23
  • This is documented in the Sequel cheatsheet: http://sequel.jeremyevans.net/rdoc/files/doc/cheat_sheet_rdoc.html#label-Using+raw+SQL. That said, it's _NOT_ a good idea to use raw SQL if you can help it. The idea of an ORM is it allows you to write queries that are independent of the DBM you are talking to. That lets you easily change to another DBM without changing your code. – the Tin Man Oct 30 '16 at 22:58
  • I'm tempted to close this as a duplicate of http://stackoverflow.com/q/3144813/128421 – the Tin Man Oct 30 '16 at 23:03

2 Answers2

1
DB[:school_districts].select(:code).group_and_count(:code).reverse_order(:count)

is a Sequel way of executing that query. I did not however alias the count column, but I hope you can do with this.

Even though working in Sequel is preferable as it allows you to change DBMs without changing your code I would prefer you use the fetch method.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Nsoseka
  • 223
  • 2
  • 9
0

You can do it a couple ways:

  1. Use []:

    DB["your sql string"]
    
  2. Use fetch:

    DB.fetch("your sql string")
    
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
idej
  • 5,034
  • 1
  • 11
  • 14