CleverSphere

SQL formula sheet

Every rule and formula of the trainer on one page, for revision before the exam or to print.

Practise with problems

SQL formula sheet · CleverSphere

SELECT & WHERE

Topic page →
  • ·SELECT columns FROM table
  • ·WHERE filters rows
  • ·Text in single quotes
  • ·DISTINCT removes duplicates
  • ·ORDER BY column ASC or DESC
  • ·Several sort keys with commas
  • ·LIMIT goes at the very end

Aggregate functions

Topic page →
  • ·COUNT(*) counts rows
  • ·COUNT(column) skips NULL
  • ·SUM, AVG, MIN, MAX

Reading queries

Topic page →
  • ·Read FROM and WHERE first
  • ·Then groups and aggregates
  • ·SELECT last
  • ·Every non-aggregated column goes in GROUP BY
  • ·One result row per group
  • ·WHERE filters rows
  • ·HAVING filters groups
  • ·Aggregates only in HAVING
  • ·JOIN table ON a = b
  • ·Aliases shorten the query
  • ·n tables need n − 1 joins

JOIN & GROUP BY

Topic page →
  • ·Join first, then group
  • ·LEFT JOIN keeps rows without a partner
  • ·COUNT(column) skips NULL

Subqueries

Topic page →
  • ·IN (SELECT …) for lists
  • ·NOT IN finds what is missing
  • ·Comparing with a single value: = (SELECT AVG …)