Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to SQL Notes
Topic #104

SQL Syntax Basics

SQL statements follow a predictable clause order. Once you know the order, reading unfamiliar queries gets much easier.

The Standard Clause Order

SELECT   columns
FROM     table
WHERE    row-level condition
GROUP BY grouping columns
HAVING   group-level condition
ORDER BY sort order
LIMIT    row count;

You don't need every clause every time — but the ones you do use must appear in this order, or the query fails.

Full Example

SELECT department, COUNT(*) AS total_employees
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) > 5
ORDER BY total_employees DESC
LIMIT 3;

This reads as: from active employees, group by department, keep only departments with more than 5 people, sort by headcount, and show the top 3.

Keywords Are Case-Insensitive — Your Data Isn't Always

SELECT, select, and Select all work identically — keywords are case-insensitive. But whether 'Aman' = 'aman' matches depends on the column's collation (MySQL is usually case-insensitive by default; PostgreSQL string comparison is case-sensitive by default). Writing keywords in UPPERCASE is a convention, not a rule — it just makes queries easier to scan.

Statement Termination

Each statement ends with a semicolon ;. Most tools tolerate a missing semicolon on a single statement, but it's required when running multiple statements together.

Common Mistakes

  • Writing WHERE after GROUP BY — always WHERE before GROUP BY, before HAVING
  • Trying to filter an aggregate with WHERE instead of HAVING (see WHERE vs HAVING)
  • Forgetting that LIMIT always goes last

Interview Relevance

A frequent whiteboard question: "In what order does SQL actually execute these clauses?" The written order and the logical execution order differ — SQL evaluates FROMWHEREGROUP BYHAVINGSELECTORDER BYLIMIT, even though you type SELECT first. This is why you can't reference a column alias (defined in SELECT) inside a WHERE clause in most databases — WHERE runs before SELECT does.

Practice Question

Rewrite this incorrect query so it's syntactically valid: SELECT dept, COUNT(*) FROM employees GROUP BY dept WHERE salary > 40000 ORDER BY dept;

Related SQL Notes

Want to go beyond the notes?

Join CodingNow's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →