SQL Syntax

Updated · 9 min read
easyPostgreSQL 18sqlsyntaxbasicsquotes

Every SQL statement is built from the same few parts. Once you can tell a keyword from a name and a name from a value, you can read almost any query, even one you've never seen. This lesson names those parts, shows the rules for case, spacing and quotes, and points out the one rule beginners trip over most: single quotes and double quotes mean different things.

In One Minute

  • A statement is one complete instruction, such as a query. It ends with a semicolon.
  • A statement is made of clauses (SELECT ..., FROM ..., WHERE ...), each starting with a keyword, and the clauses go in a fixed order.
  • Names (identifiers) are your tables and columns. Values (literals) are data, such as 'CA' or 450.00.
  • Keywords and names aren't case-sensitive; data is. 'CA' and 'ca' are different values.
  • Single quotes hold text values. Double quotes hold names. Mixing them up is the most common beginner error.

The Parts of a Statement

Here is a statement you've already met, with every part named. Run it first:

SQL▶ Try it
SELECT first_name, city
FROM students
WHERE state = 'CA'
ORDER BY first_name;
Output
 first_name |     city
------------+---------------
 Advitha    | San Francisco
 Srihitha   | San Francisco
(2 rows)
PartIn this statementWhat it is
KeywordSELECT, FROM, WHERE, ORDER BYA word with a fixed meaning in SQL. You can't use it to mean something else
Identifier (name)first_name, city, students, stateThe name of something in the database: a table or a column
Literal (value)'CA'A piece of data written straight into the statement
Operator=A symbol that compares or calculates
ClauseWHERE state = 'CA'A keyword and everything that belongs to it
Semicolon;The end of the statement
Keywords, names, values, clauses and the semicolon

The clauses go in a fixed order. SELECT, then FROM, then WHERE, then ORDER BY. You'll meet more clauses later, and each one has its place. Put one in the wrong spot and the database stops at the first word it didn't expect:

SQL▶ Try it
SELECT first_name
FROM students
ORDER BY first_name
WHERE state = 'CA';
Output
ERROR:  syntax error at or near "WHERE"

"At or near" points at the word where the database got confused: it expected the statement to end after ORDER BY first_name, and found WHERE instead. Move WHERE above ORDER BY and the query works.

Semicolons

A semicolon marks the end of a statement, so you can run several statements one after another. Each one gets its own result:

SQL▶ Try it
SELECT count(*) FROM students;
SELECT count(*) FROM courses;
Output
 count
-------
     3
(1 row)
 
 count
-------
     6
(1 row)

Try it and psql both run each statement in turn. When you run a single statement in Try it, the semicolon is optional, but psql waits for one before it runs anything. Ending every statement with a semicolon is a habit that works everywhere.

Upper Case, Lower Case

SQL treats keywords and names the same in any case, but not your data.

WhatCase-sensitive?Example
KeywordsNoSELECT, select and Select are the same
Names without quotesNo: they're treated as lowercaseSTUDENTS, Students and students all mean the students table
Text valuesYes'CA' and 'ca' are different values

The last row matters. The states are stored as CA and TX, so asking for 'ca' finds nothing:

SQL▶ Try it
SELECT first_name
FROM students
WHERE state = 'ca';
Output
 first_name
------------
(0 rows)

This course writes keywords in capitals and names in lowercase (SELECT first_name FROM students), so you can see at a glance which words are SQL and which are yours.

Spaces, Lines and Layout

SQL ignores extra spaces and line breaks between words. These two statements are the same query, and return the same result:

SQL▶ Try it
SELECT first_name, city FROM students WHERE state = 'CA' ORDER BY first_name;
Output
 first_name |     city
------------+---------------
 Advitha    | San Francisco
 Srihitha   | San Francisco
(2 rows)
SQL▶ Try it
SELECT
  first_name,
  city
FROM students
WHERE state = 'CA'
ORDER BY first_name;
Output
 first_name |     city
------------+---------------
 Advitha    | San Francisco
 Srihitha   | San Francisco
(2 rows)

The second is easier to read and to change. This course puts each clause on its own line once a query has more than two clauses. Spaces inside quotes are different: 'San Francisco' has one space, and that space is part of the value.

Single Quotes and Double Quotes

QuotesMeanExample
'single'A text value (data)WHERE city = 'Dallas'
"double"A name (a table or column), with its exact capitalsSELECT "first_name" FROM students

You'll rarely need double quotes, because names in lowercase without spaces don't need them. They also keep capitals exactly, which surprises people. The column is called first_name in lowercase, so asking for "First_Name" fails:

SQL▶ Try it
SELECT "First_Name"
FROM students;
Output
ERROR:  column "First_Name" does not exist
HINT:  Perhaps you meant to reference the column "students.first_name".

To put a single quote inside a text value, write it twice. The database reads '' as one quote character. (AS label gives the result column a name; you'll learn it properly in Aliases.)

SQL▶ Try it
SELECT 'Navika''s first course' AS label;
Output
         label
-----------------------
 Navika's first course
(1 row)
Single quotes for values, double quotes for names

Quoting Names in Other Databases

Other databases quote names differently. MySQL also accepts backticks, `first_name`, and SQL Server also accepts square brackets, [first_name]. These are MySQL only and SQL Server only; double quotes are the standard form, and PostgreSQL uses only double quotes. Tabs showing each database's version are coming to this course.

The Main Kinds of Statements

You met the four practical jobs of SQL in What Is SQL. As a reminder, the statements are often grouped into families with short names. Sources sort them a little differently, so focus on what each statement does:

JobFamilyStarts with
Ask for dataDQL (often grouped with DML)SELECT
Change dataDMLINSERT, UPDATE, DELETE
Define structuresDDLCREATE, ALTER, DROP
Manage permissionsDCLGRANT, REVOKE
Group changes into transactionsTCLBEGIN, COMMIT, ROLLBACK

Every statement in this lesson is a SELECT. You'll write the others later in the course, starting with INSERT INTO.

Common Mistakes

Double quotes around text. WHERE state = "CA" fails with column "CA" does not exist, because double quotes make CA a name. Use 'CA'.

Clauses in the wrong order. ORDER BY before WHERE gives syntax error at or near "WHERE". Keep the order SELECT, FROM, WHERE, ORDER BY.

Expecting text to match in any case. WHERE state = 'ca' returns no rows, without any error. Match the case of the stored data, or learn the case-insensitive ways in LIKE and Wildcards later in the course.

A forgotten semicolon in psql. psql waits, showing -# in its prompt, until you type ;.

Practice

Challenge: This query works, but it's hard to read, and it uses double quotes where it shouldn't need any quotes at all. Rewrite it with keywords in capitals, names in lowercase without quotes, and one clause per line. It should return the same result.

SQL
select "title", "fee_usd" from "courses" where fee_usd > 400 order by "title";
Show solution
SQL▶ Try it
SELECT title, fee_usd
FROM courses
WHERE fee_usd > 400
ORDER BY title;
Output
       title       | fee_usd
-------------------+---------
 Java Basics       |  450.00
 Java Collections  |  550.00
 Java OOP          |  500.00
 JavaScript Basics |  450.00
(4 rows)

The original runs too, because "title" and the other names are already lowercase. The quotes just add noise. Four courses cost more than $400.

Quick check: SQL syntax

3 questions
1In WHERE city = 'Dallas', which part is a literal (a value)?
2A query with WHERE state = 'tx' returns 0 rows, but Navika lives in Texas. Why?
3What do double quotes mean in PostgreSQL?

Key Takeaways

You want toWrite
End a statement;
Write a text value'Dallas'
Put a quote inside text'Navika''s course'
Name a column exactly"first_name" (rarely needed)
Keep the clauses in orderSELECT, FROM, WHERE, ORDER BY

Was this tutorial helpful?

Lesson 6 of 115