title: The best way to find the Department with the maximum total salary Postgresql
body: <p>Lets we have 2 standard tables Employees and Departments</p>
  
  <pre><code>CREATE TABLE departments (
    id SERIAL PRIMARY KEY,
    name VARCHAR
  );
  
  CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    department_id INTEGER,
    name VARCHAR,
    salary NUMERIC(13,2)
  );
  </code></pre>
  
  <p>What is the best way to find the name of the department with the maximum employees' total salary.</p>
  
  <p>I've found two solutions and they looks too complicated for such simple task.</p>
  
  <p><strong>Using rank()</strong></p>
  
  <pre><code>SELECT name FROM (
     SELECT name, rank() OVER ( ORDER BY salary DESC ) AS rank
     FROM (
            SELECT
              departments.name,
              sum(salary) AS salary
            FROM employees
              JOIN departments ON department_id = departments.id
            GROUP BY departments.name
          ) AS t1
   ) AS t2
  WHERE rank = 1;
  </code></pre>
  
  <p><strong>Using subquery</strong></p>
  
  <pre><code>WITH t1 AS (SELECT
           departments.name,
           sum(salary) AS salary
         FROM employees
         JOIN departments ON departments.id = employees.department_id
         GROUP BY departments.name
  )
  SELECT name FROM t1
  WHERE t1.salary = (SELECT max(salary) FROM t1);
  </code></pre>
  
  <p>At first glance using rank should be less efficient as it performs unnecessary sorting. Though <code>EXPLAIN</code> shows that the first option is more efficient.
  Or maybe someone suggests another solution.</p>
  
  <p>So, what is the best way to find the Department with the maximum total salary using postgres?</p>