title: How do you get the rows and the columns in the result of a query with ActiveRecord?
body: <p>Is there a way with ActiveRecord to execute a custom SQL query and have it return an array of arrays where the first row is the column names and each following row is the row data?  I want to execute something like:</p>
  
  <pre><code>connection.select_rows_with_headers "SELECT id, concat(first_name, ' ', last_name) as name, email FROM users"
  </code></pre>
  
  <p>And have it return:</p>
  
  <pre><code>[["id","name","email"],["1","Bob Johnson","bob@example.com"],["2","Joe Smith","joe@example.com"]]
  </code></pre>
  
  <p>This would allow me to print the results of the custom query in an HTML table like this:</p>
  
  <pre><code>&lt;table&gt;
    &lt;% result.each_with_index do |r,i| %&gt;
      &lt;tr&gt;
        &lt;% r.each do |c| %&gt;
          &lt;% if i == 0 %&gt;
            &lt;th&gt;&lt;%=h c %&gt;&lt;/th&gt;
          &lt;% else %&gt;
            &lt;td&gt;&lt;%=h c %&gt;&lt;/td&gt;
          &lt;% end %&gt; 
        &lt;% end %&gt;
      &lt;/tr&gt;
    &lt;% end %&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>Note that <code>select_all</code> doesn't work because the keys in each hash are unordered, so you've lost the ordering of the results as specified in the query.</p>