ADVERTISEMENT

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

  1. SQL Keywords are not case sensitive
    • select, SELECT, and Select all work the same, but by convention, keywords are written in uppercase for clarity.
  2. Statements end with a semicolon (;)
    • This marks the end of a command.
  3. String values must be enclosed in single quotes sqlCopyEditWHERE name = 'John'
  4. Identifiers (like table or column names) may require quotes if they contain spaces or special characters
    • Typically backticks ` in MySQL, double quotes " in PostgreSQL.
  5. 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

CommandBasic SyntaxPurpose
SELECTSELECT columns FROM table [WHERE condition];Retrieve data
INSERTINSERT INTO table (cols) VALUES (vals);Add new rows
UPDATEUPDATE table SET col = val [WHERE condition];Modify existing data
DELETEDELETE FROM table [WHERE condition];Remove data
CREATE TABLECREATE TABLE table (col datatype, ...);Define new table structure
ALTER TABLEALTER TABLE table ADD column datatype;Modify table structure
DROP TABLEDROP 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

RuleExplanation
Keywords uppercaseMakes queries easier to read
Semicolon at endMarks end of SQL command
Strings in single quotesDefines literal string values
Identifiers quoted if neededWhen names have spaces or special chars

ADVERTISEMENT