SQL Syntax
SQL syntax is the set of predefined rules, keywords, and guidelines used to write queries that a database engine can interpret. Because SQL is a declarative language, your syntax specifies what data you want rather than how to structurally fetch it.
While various relational database systems like MySQL or PostgreSQL have custom extensions, they all follow a universal foundation.
1. General Rules of Code Style
Semicolons (;): Used to terminate a statement. While optional in some modern engines for single queries, it is standard practice.
Case Sensitivity: SQL keywords are not case-sensitive (
SELECTis the same as select). However, writing keywords in UPPERCASE and identifiers (table/column names) in lowercase dramatically improves readability.Whitespace: Indentations and newlines do not affect execution; break complex clauses into multiple lines to keep them readable.
Core Data Manipulation Syntax (DML)
SELECT (Retrieving Data)
Extracts specified column data from one or more target tables.
Syntax
SELECT column1, column2 FROM table_name;
INSERT INTO (Adding Data)
Inserts brand-new records into a structured database table.
Syntax
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
UPDATE (Modifying Data)
Alters pre-existing table cell values. Warning: Always couple this statement with a WHERE condition, or you will accidentally alter every single row in the database!
Syntax
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
DELETE (Removing Data)
Deletes targeted row structures from a database table. Like UPDATE, omitting the WHERE clause wipes out all of your rows.
Syntax
DELETE FROM table_name WHERE condition;
Order of Syntax Execution
When constructing reading queries, your statements must follow a strict lexical sequencing rule.
A common memory aid for this structural sequence is "She Told Father We Got Home Okay" (SELECT, TOP, FROM, WHERE, GROUP BY, HAVING, ORDER BY).
| Clause | Purpose | Example Syntax |
|---|---|---|
| SELECT | Dictates fields to output | SELECT department, AVG(salary) |
| FROM | Points to source tables | FROM employees |
| WHERE | Filters row-level data | WHERE hire_date > '2025-01-01' |
| GROUP BY | Aggregates identical row data | GROUP BY department |
| HAVING | Filters aggregated group records | HAVING AVG(salary) > 50000 |
| ORDER BY | Sorts the final output data set | ORDER BY AVG(salary) DESC |
Basic Data Definition Syntax (DDL)
Used to create or destroy structural elements like tables and databases.
- CREATE TABLE: CREATE TABLE table_name (id INT, name VARCHAR(50));
- ALTER TABLE: ALTER TABLE table_name ADD email VARCHAR(100);
- DROP TABLE: DROP TABLE table_name;