SQL Clauses
SQL clauses are an essential part of SQL queries and help to filter, sort, and limit the data returned from a database. Some of the most commonly used SQL clauses are:
WHERE
The WHERE clause is used to filter records that meet certain conditions.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
GROUP BY
The SQL GROUP BY statement is used to arrange identical data into groups.
- The
GROUP BYstatement is used with the SQLSELECTstatement. - The
GROUP BYstatement follows theWHEREclause in aSELECTstatement and precedes theORDER BYclause. - The
GROUP BYstatement is often used with aggregation functions (likeCOUNT(),SUM(),AVG(), etc.).
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
ORDER BY column_name;HAVING
- The HAVING clause is used to specify a search condition for a group or an aggregate.
- HAVING is used in a
GROUP BYclause. If you are not usingGROUP BYclause, then you can use the HAVING function like aWHEREclause.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
ORDER BY
- The ORDER BY clause sorts the result-set in ascending or descending order.
- It sorts the records in ascending order by default. The
DESCkeyword is used to sort the records in descending order.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1, column2 ... ASC | DESC;