iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL Syntax

SQL statements read almost like English. Each one ends with a semicolon and is built from a handful of clauses that always appear in the same order.

The shape of a SELECT

SQL
SELECT <columns>
FROM   <table>
WHERE  <condition>
GROUP BY <columns>
HAVING <condition>
ORDER BY <columns>
LIMIT  <n>;

Clauses, top to bottom

ClauseWhat it does
SELECTWhich columns to return.
FROMWhich table (or join) to read from.
WHEREFilter rows before grouping.
GROUP BYCollapse rows into groups for aggregation.
HAVINGFilter groups (after aggregation).
ORDER BYSort the result.
LIMIT / TOPCap the number of rows returned.

Case & whitespace

  • Keywords are case-insensitive — SELECT and select work the same. Most teams use UPPERCASE for keywords as a convention.
  • Identifiers (table and column names) are usually case-insensitive on Windows and MS SQL Server, but case-sensitive in PostgreSQL.
  • You can break a statement across as many lines as you like — only the final ; ends it.
Tip: Format long queries one clause per line. It makes diffs in code review readable and helps you spot a misplaced comma instantly.

Example

Example
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1;
Try it Yourself »

Exercise

End every SQL statement with this character.

SELECT 1

Test yourself

Q1. Which clause is evaluated FIRST?
Q2. SQL keywords are…
Q3. Every SQL statement ends with…

Discussion

Loading…