Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The Postgres way to do this:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FORM users u LEFT JOIN ( SELECT user_id, count(*) AS friends FROM friends ) f USING (user_id) ORDER BY f.friends DESC NULLS LAST, user_id -- as tiebreaker </code></pre> <ul> <li><p>The keyword <code>AS</code> is just noise for table aliases. But don't omit it from column aliases. I quote the manual on <a href="http://www.postgresql.org/docs/current/interactive/sql-select.html#AEN80736" rel="nofollow noreferrer">"Omitting the AS Key Word"</a>:</p> <blockquote> <p>In <code>FROM</code> items, both the standard and PostgreSQL allow <code>AS</code> to be omitted before an alias that is an unreserved keyword. But this is <strong>impractical for output column names, because of syntactic ambiguities</strong>.</p> </blockquote> <p>Bold emphasis mine.</p></li> <li><p><code>ISNULL()</code> is a custom extension of MySQL or SQL Server. Postgres uses the SQL-standard function <a href="http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL" rel="nofollow noreferrer"><code>COALESCE()</code></a>. But you don't need either here. Use the <a href="https://stackoverflow.com/questions/9510509/postgresql-sort-by-datetime-asc-null-first/9511492#9511492"><code>NULLS LAST</code> clause</a> instead, which is faster and cleaner.</p></li> <li><p>It's to be expected that multiple users have the same number of friends. These peers would be sorted arbitrarily. Calling the same function twice might yield different results, which is normally not desirable. Add more expressions to <code>ORDER BY</code>. Ultimately, the primary key resolves any remaining ambiguities.</p></li> <li><p>If the two tables share the same column name <code>user_id</code> (like they should) you can use the syntax shortcut <code>USING</code> in the join clause. Another standard SQL feature. Very welcome side effect: <code>user_id</code> is only listed once in the output for <code>SELECT *</code>, as opposed to when joining with <code>ON</code>. Many clients wouldn't even accept duplicate column names in the output.</p></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload