Clauses in SQL
Sure! Here’s a detailed overview of SQL Clauses — the fundamental building blocks of SQL queries:
? Common SQL Clauses
1. SELECT
Specifies the columns or expressions to retrieve.
Example:
SELECT column1, column2 FROM table_name;
2. FROM
Specifies the table(s) to query data from.
Example:
SELECT * FROM employees;
3. WHERE
Filters rows based on conditions.
Example:
SELECT * FROM employees WHERE salary > 50000;
4. GROUP BY
Groups rows sharing the same values in specified columns.
Used with aggregate functions like COUNT, SUM.
Example:
SELECT department, COUNT(*) FROM employees GROUP BY department;
5. HAVING
Filters groups formed by
GROUP BYbased on conditions.Example:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
6. ORDER BY
Sorts the result set by one or more columns.
Default is ascending order; use
DESCfor descending.Example:
SELECT * FROM employees ORDER BY salary DESC;
7. JOIN (INNER, LEFT, RIGHT, FULL)
Combines rows from two or more tables based on related columns.
Example:
SELECT e.name, d.department_nameFROM employees eJOIN departments d ON e.department_id = d.id;
8. LIMIT / TOP
Restricts the number of rows returned.
LIMITused in MySQL, PostgreSQL;TOPin SQL Server.Example:
SELECT * FROM employees LIMIT 10;or
SELECT TOP 10 * FROM employees;
9. INSERT INTO
Adds new rows to a table.
Example:
INSERT INTO employees (name, salary) VALUES ('John Doe', 60000);
10. UPDATE
Modifies existing rows.
Example:
UPDATE employees SET salary = 70000 WHERE name = 'John Doe';
11. DELETE
Removes rows from a table.
Example:
DELETE FROM employees WHERE salary < 30000;
12. ALTER TABLE
Modifies table structure (add, drop columns, change datatype).
Example:
ALTER TABLE employees ADD COLUMN hire_date DATE;
13. CREATE TABLE
Creates a new table.
Example:
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), salary DECIMAL(10,2));
Summary
Clauses are keywords/parts of SQL statements that specify what to do and how.
You combine clauses to create powerful queries.
Some clauses filter data (
WHERE,HAVING), some control output (ORDER BY,LIMIT), others manage schema (ALTER TABLE,CREATE TABLE).
If you want, I can explain any clause with examples or show how to combine them!