Skip to content

Instantly share code, notes, and snippets.

@dritterman
Last active December 17, 2015 19:49
Show Gist options
  • Save dritterman/5662750 to your computer and use it in GitHub Desktop.
Save dritterman/5662750 to your computer and use it in GitHub Desktop.
1. List employees (names) who have a bigger salary than their boss
SELECT
e.`name`
FROM
employees AS e
INNER JOIN employees AS b ON e.bossid = b.employeeid
WHERE
e.salary > b.salary
2. List employees who have the biggest salary in their departments
SELECT
emain.`name`,
emain.salary
FROM
employees AS emain
WHERE
emain.employeeid = (
SELECT
esub.employeeid
FROM
employees AS esub
WHERE
esub.departmentid = emain.departmentid
ORDER BY
esub.salary DESC
LIMIT 0, 1
)
GROUP BY
emain.departmentid
3. List departments that have less than 3 people in it
SELECT
departments.`name`
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.departmentid
HAVING
COUNT(*) < 3
4. List all departments along with the number of people there (tricky - people often do an "inner join" leaving out empty departments)
SELECT
departments.`name`,
Count(employees.employeeid) as count
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.departmentid
5. List employees that don't have a boss in the same department
SELECT
e.`name`
FROM
employees AS e
INNER JOIN employees AS b ON e.bossid = b.employeeid
WHERE
e.departmentid <> b.departmentid
6. List all departments along with the total salary there
SELECT
departments.`name`,
Sum(employees.salary)
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.`name`
@dritterman
Copy link
Author

Thanks for pointing that out @miguelangelnieto. I don't think I've ever come across that before (or I've just never noticed before!).

In fact I think we were both wrong. See https://news.ycombinator.com/item?id=5779842 for more info.

I've updated answer 2 now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment