SQL Syntax
To effectively write SQL queries and commands, understanding the basic syntax rules is essential. SQL syntax defines how you structure commands so the database can interpret them correctly.
✍️ Basic Structure of SQL Statements
A SQL statement usually follows this general format:
COMMAND [columns]
FROM table_name
[WHERE condition]
[GROUP BY column]
[HAVING condition]
[ORDER BY column]
[LIMIT number];- COMMAND: The action you want to perform (
SELECT,INSERT,UPDATE,DELETE, etc.) - Square brackets
[ ]indicate optional parts of the statement.
⚠️ Key SQL Syntax Rules
- SQL Keywords are not case sensitive
select,SELECT, andSelectall work the same, but by convention, keywords are written in uppercase for clarity.
- Statements end with a semicolon (
;)- This marks the end of a command.
- String values must be enclosed in single quotes sqlCopyEdit
WHERE name = 'John' - Identifiers (like table or column names) may require quotes if they contain spaces or special characters
- Typically backticks
`in MySQL, double quotes"in PostgreSQL.
- Typically backticks
- Whitespace (spaces, tabs, new lines) is ignored
- Use whitespace to make code readable.
🧩 Example: Simple SELECT Query Syntax
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales'
ORDER BY last_name ASC;- Retrieves first and last names of employees in the Sales department, sorted by last name ascending.
🛠️ Common SQL Commands Syntax Overview
| Command | Basic Syntax | Purpose |
|---|---|---|
| SELECT | SELECT columns FROM table [WHERE condition]; | Retrieve data |
| INSERT | INSERT INTO table (cols) VALUES (vals); | Add new rows |
| UPDATE | UPDATE table SET col = val [WHERE condition]; | Modify existing data |
| DELETE | DELETE FROM table [WHERE condition]; | Remove data |
| CREATE TABLE | CREATE TABLE table (col datatype, ...); | Define new table structure |
| ALTER TABLE | ALTER TABLE table ADD column datatype; | Modify table structure |
| DROP TABLE | DROP TABLE table; | Delete table |
💡 Tips for Writing SQL Code
- Use uppercase for SQL keywords for readability.
- Always end statements with a semicolon.
- Write clear and meaningful identifiers for tables and columns.
- Format queries with indentation and line breaks to improve clarity.
🧠 Quick Recap
| Rule | Explanation |
|---|---|
| Keywords uppercase | Makes queries easier to read |
| Semicolon at end | Marks end of SQL command |
| Strings in single quotes | Defines literal string values |
| Identifiers quoted if needed | When names have spaces or special chars |
