SQL Clauses
📙 Welcome to SQL Clauses!
Hey there, SQL beginner! Clauses are the essential parts of an SQL query that tell the database what data to retrieve and how to process it. Think of them as the steps in a recipe—each clause has a specific job, and they must be written in a strict order to work correctly. We’ll use a simple students table (with columns like id, name, age, marks, and city) to explain everything with clear examples. Let’s dive in step by step, following the correct order of clauses in a SELECT query!

📘 What Are Clauses?
Clauses are components of SQL statements that perform tasks like selecting columns, filtering rows, or sorting results. In a SELECT query, they must appear in this order: SELECT → FROM → JOIN → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. However, the database executes them differently: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Understanding both orders helps you write correct and efficient queries.
Pro Tip: Always write clauses in the syntactic order (SELECT first, LIMIT last), but think about execution order when optimizing performance!
📘 SELECT Clause (Choosing What to Show!)
The SELECT clause is where you pick what data to display—columns, calculations, or even subqueries. Use * for all columns, list specific ones, or add aliases with AS. You can also use functions like COUNT or DISTINCT to shape your results.
Examples:
- Basic SELECT
- Basic Output
- DISTINCT
- DISTINCT Output
- Aggregate
- Aggregate Output
- Subquery
- Subquery Output
SELECT name AS student_name, age
FROM students;
| student_name | age |
|---|---|
| Alice | 20 |
| Bob | 22 |
| Carol | 19 |
SELECT DISTINCT city
FROM students;
| city |
|---|
| Mumbai |
| Delhi |
SELECT COUNT(id) AS total_students, AVG(marks) AS avg_marks
FROM students;
| total_students | avg_marks |
|---|---|
| 3 | 84.0 |
SELECT name, marks,
(SELECT AVG(marks) FROM students) AS avg_all_marks
FROM students;
| name | marks | avg_all_marks |
|---|---|---|
| Alice | 85 | 84.0 |
| Bob | 92 | 84.0 |
| Carol | 75 | 84.0 |
What NOT to Do:
- Don’t use SELECT without FROM—it’ll error in most databases!
- Avoid SELECT * in production—it’s inefficient; list only needed columns.
- Don’t use column aliases in WHERE or GROUP BY—aliases are for output only.