Thuta Learning
SQL
BasicData & DatabasesBeginner

SQL Syntax

SQLLesson 418 min

What you'll walk away with

  • Split a statement into clauses, keywords, identifiers and literals
  • Explain that keywords are case-insensitive and that PostgreSQL folds unquoted identifiers to lowercase
  • Use single quotes for text values and double quotes only for identifiers
  • Write -- and /* */ comments and text containing a quote, such as 'O''Brien'

Explain it simply

Explain it simply

Read an SQL statement like an English sentence. Keywords such as SELECT, FROM and WHERE are the grammar words that give it structure. Names such as CustomerName and Customers (identifiers) say which column and table you mean, and a value such as 'Mexico' (a literal) is the data you are looking for.

Just as a sentence ends with a full stop, a statement ends with a semicolon (;). There are only a few rules, but small slips such as using the wrong kind of quote cause confusing errors, so this lesson goes through them one at a time.

Problem → Why → Solution

The problem: a query that works in MySQL fails in PostgreSQL

Say you copy the query below from an online tutorial and run it in PostgreSQL. With default settings it works in MySQL, but PostgreSQL replies with a puzzling error: column "Mexico" does not exist. Mexico is a value, not a column, so many beginners get stuck right here.

double-quotes.sql
SELECT CustomerName, Country
FROM Customers
WHERE Country = "Mexico";
-- ERROR:  column "Mexico" does not exist

Why does this error appear?

In standard SQL, single quotes ('...') make a text value and double quotes ("...") make an identifier, the name of a column or table. PostgreSQL follows the standard strictly, so it reads "Mexico" as a column named Mexico, cannot find one, and errors. Writing 'Mexico' fixes it.

Core concept: the anatomy of a statement

A statement is built from clauses: a SELECT clause, a FROM clause, a WHERE clause, each starting with its keyword. The order of clauses is fixed; you cannot put WHERE before FROM. Spaces, tabs and line breaks all count the same, so you may write a statement on one line or put each clause on its own line.

PartExampleRule
KeywordSELECT, from, WhereCase-insensitive; uppercase by convention
IdentifierCustomers, CustomerNameFolded to lowercase unless quoted
Quoted identifier"Customer Name"Exact case; may contain spaces
Text literal'Mexico', 'O''Brien'Single quotes; write ' as ''
Number literal42, 3.50No quotes

Identifier folding is a key PostgreSQL trait. CREATE TABLE Customers without quotes actually stores the name customers. So Customers, CUSTOMERS and customers all refer to the same table, and result headers show lowercase names such as customername. Write "Customers" in double quotes, though, and PostgreSQL looks for that exact capitalised name, finds nothing, and errors. That is why production schemas favour lowercase snake_case names such as customer_name.

The semicolon ends a statement. Some tools tolerate a single statement without it, but psql treats a missing ; as "not finished yet" and keeps waiting, and scripts with several statements need it to separate them. Comments are written with -- (to the end of the line) or /* ... */ (across lines).

Watch out for keywords used as names, too. Calling a table or column order, user or select (all reserved words) tends to give a syntax error in PostgreSQL, and it only works when quoted as "order". Pick names that are not keywords, such as orders or app_user.

literals.sql
/* Literals: text in single quotes, a quote inside text doubled,
   numbers bare */
SELECT 'O''Brien' AS surname, 42 AS answer, 3.50 AS price;
Mental model: the quote decides the meaning
  1. Keyword: SELECT, FROM, WHERE
  2. No quotes: a name, lowercased
  3. "...": a name, exact case
  4. '...': a text value

Single quotes hold data; double quotes hold names.

General pattern

sql
-- line comment
SELECT column_a, column_b       /* block comment */
FROM table_name
WHERE column_c = 'text value'
  AND column_d = 123;

One clause per line and uppercase keywords keep a query readable. Text goes in single quotes, numbers stay bare, and ; closes the statement. AND gets its own lesson (Lesson 8).

Example: one query, several syntax rules

This query uses the Customers table from Lesson 3. Notice the mixed-case keywords and the table name written in lowercase; PostgreSQL runs it happily anyway. The comments have no effect when it runs. Read each line together with its comment: every one demonstrates a different rule from the concept section above.

syntax-tour.sql
-- Syntax tour: one statement, three clauses
select CustomerName, City          -- keywords work in lowercase too
FROM   customers                   -- unquoted names fold to lowercase
WHERE  City = 'Mexico City';       -- text values use single quotes

Code breakdown

  1. Line 1-- Syntax tour: one statement, three clauses

    From -- to the end of the line is a comment, a note for the next reader of the query.

  2. Line 2select CustomerName, City

    select in lowercase is still the keyword. The two columns are separated by a comma; forget it and City becomes an alias instead of a column (see the mistakes section).

  3. Line 3FROM customers

    The table was created as Customers without quotes, so its real name is customers and the lowercase spelling finds it. The extra spaces change nothing.

  4. Line 4WHERE City = 'Mexico City';

    'Mexico City' is a text literal, so the space inside is fine. The ; closes the statement, and a comment after it is harmless.

  5. Output

    The headers come back lowercase, customername and city, and only the two customers living in Mexico City are returned.

You should see
  customername  |    city
----------------+-------------
 Ana Trujillo   | Mexico City
 Antonio Moreno | Mexico City
(2 rows)

When double quotes are really needed

Use double quotes when a name must contain a space or keep its exact capitalisation, typically for an output header. The query below shows the header Customer Name with its space and capitals. Avoid them for table names: create a table with quotes and every future query has to quote it too.

quoted-alias.sql
SELECT CustomerName AS "Customer Name"
FROM Customers;
DatabaseMeaning of "text"
PostgreSQLIdentifier (column or table name)
MySQL (default)Text value (identifier only in ANSI_QUOTES mode)
SQLiteIdentifier, but may fall back to a text value

In real projects

Where this shows up in real projects

Teams write SQL under a style guide just like other code: uppercase keywords, lowercase snake_case table and column names, one clause per line. Linters such as sqlfluff check these rules automatically before code review. Explaining in a -- comment why a migration adds a column is another common habit.

Identifier folding is one of the most common pain points when moving between databases. A schema migrated from SQL Server with CamelCase names like "OrderDate" forces every PostgreSQL query to quote them, which developers quickly grow to hate. Choosing lowercase names from the start avoids the whole problem. ORMs hide some of this, but the moment you open psql to debug a production issue, you are typing the raw names yourself.

Common mistakes

Common mistakes

1. Forgetting the comma between columns

SELECT CustomerName City FROM Customers; does not error! PostgreSQL reads City as an alias for CustomerName (as if you wrote AS City) and returns a single column headed city that is full of customer names. With no error to warn you, this bug is easy to miss.

2. Double-quoting a table name

A table created without quotes is named customers. FROM "Customers" searches for the capitalised name and fails with relation "Customers" does not exist. Drop the quotes.

3. Breaking text that contains an apostrophe

'O'Brien' makes PostgreSQL think the text ended at 'O', and you get a syntax error. Double the quote: 'O''Brien'. When user input from an app goes into SQL, do not escape it by hand at all; use parameterized queries (Lesson 26).

Best practices

Best practices

  • Write keywords in uppercase and table and column names in lowercase snake_case.
  • Put each clause on its own line, and one column per line when the list is long.
  • End every statement with ;, even when it is the only one.
  • Keep double quotes for output headers and avoid them in table names.
  • Explain the reason behind a tricky condition in a -- comment.

Mini challenge

Mini challenge: repair the query

This query should show the name and city of the customers in the UK, but it has four syntax problems. Find and fix them all.

  • Return CustomerName and City as two separate columns
  • Write the table name so PostgreSQL finds it
  • Write UK as a text value
  • End the statement with ; and write keywords in uppercase
fix-me.sql
-- TODO: four problems hide in these three lines
select CustomerName City
from "Customers"
where Country = "UK"

Expected: One row under the headers customername | city: Around the Horn | London.

Show hint

Check four spots: a missing comma, the quotes around the table name, the kind of quotes around the value, and the end of the statement.

Show solution
fix-me.sql
SELECT CustomerName, City
FROM Customers
WHERE Country = 'UK';

Quick quiz 1 / 3

In PostgreSQL, what happens with WHERE Country = "Mexico"?

Quick quiz 2 / 3

What does SELECT CustomerName City FROM Customers; (no comma) return?

Quick quiz 3 / 3

How do you write the name O'Brien as an SQL text literal?

What to remember

  • A statement is made of clauses and ends with ;. Spaces and line breaks do not change its meaning.
  • Keywords are case-insensitive, and PostgreSQL folds unquoted identifiers to lowercase.
  • 'Single quotes' make text values and "double quotes" make identifiers, unlike MySQL's default.
  • Comments use -- or /* */, and a quote inside text is written ''.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

SQL Syntax | Thuta Learning