SQL Syntax
SQL syntax is the set of rules that decides how a valid SQL statement is written. Once you know a handful of these rules, every other chapter becomes easy to read.
A statement is one complete instruction to the database, such as "select these rows" or "delete that row". Statements are made of keywords (SELECT, FROM, WHERE), names of tables and columns, values, and operators.
Basic SQL Statement Structure
Most statements are built from clauses. In the query below SELECT names the columns, FROM names the table, and WHERE filters the rows. Clauses must appear in a fixed order.
SELECT CustomerName, City
FROM Customers
WHERE Country = 'UK';CustomerName | City -------------+----------- Cedar Market | London Fresh Mart | Manchester (2 rows)
Important Syntax Rules
- Keywords are not case sensitive: SELECT, select and Select all work, but writing keywords in UPPERCASE is the common convention
- Text values go in single quotes: 'London'. Numbers do not need quotes: 12.5
- A semicolon ends a statement. It is required when you run several statements together
- Spaces and line breaks are ignored, so you can split long queries over many lines
- Table and column names may be case sensitive on some systems (for example MySQL on Linux), so always match the real name
SQL Comments
Comments explain a query and are ignored by the database. Use two dashes for a single-line comment, or /* ... */ for a comment over several lines.
-- List cheap products
SELECT ProductName, Price /* price in USD */
FROM Products
WHERE Price < 10;ProductName | Price ---------------+------ Green Tea | 6 Dark Chocolate | 4.25 Wheat Flour | 8 (3 rows)
Running Several Statements
You can send more than one statement at once if each ends with a semicolon. In this playground the result of every SELECT is shown in order.
SELECT COUNT(*) AS customer_count FROM Customers;
SELECT COUNT(*) AS product_count FROM Products;customer_count -------------- 10 (1 row) product_count ------------- 8 (1 row)
The Most Important SQL Commands
- SELECT reads data
- INSERT INTO adds new rows
- UPDATE changes existing rows
- DELETE removes rows
- CREATE TABLE makes a new table
- ALTER TABLE changes a table
- DROP TABLE deletes a table
- CREATE INDEX speeds up searches
Frequently asked questions
Is SQL case sensitive?
SQL keywords are not case sensitive. Whether table names and text comparisons are case sensitive depends on the database and its settings; for example SQLite compares text with = in a case-sensitive way by default, while MySQL usually does not.
Do I need a semicolon at the end of an SQL query?
For a single statement many tools accept it without one, but the SQL standard ends statements with a semicolon and it is required when running several statements together. Adding it always is a good habit.
Should I use single or double quotes in SQL?
Use single quotes for text values. In standard SQL double quotes are for identifiers such as column names, although MySQL also accepts them for strings.