SQL Queries: SELECT, WHERE, GROUP BY, ORDER BY, JOINs
SQL (Structured Query Language) allows us to interact with relational databases. These commands help extract, filter, group, sort, and combine data from one or more tables.
1. SELECT Statement
Purpose:
Used to retrieve data from a database table.
Â
Syntax:
2. WHERE Clause
Purpose:
Used to filter rows based on a condition.
Â
Syntax:
3. GROUP BY Clause
Purpose:
Groups rows that have the same values in specified columns, often used with aggregate functions like COUNT
, SUM
, AVG
, etc.
Â
Syntax:
4. ORDER BY Clause
Purpose:
Sorts the result-set by one or more columns in ascending (ASC) or descending (DESC) order.
Â
Syntax:
5. JOINs (INNER, LEFT, RIGHT, FULL)
Purpose:
JOINs are used to combine rows from two or more tables based on a related column.
a) INNER JOIN
Returns records that have matching values in both tables.
b) LEFT JOIN (LEFT OUTER JOIN)
Returns all records from the left table, and matched records from the right table. If there’s no match, the result is NULL on the right side.
c) RIGHT JOIN (RIGHT OUTER JOIN)
Returns all records from the right table, and matched records from the left table.
d) FULL JOIN (FULL OUTER JOIN)
Returns all records when there is a match in either left or right table.
Â
Note: Some databases like MySQL don’t support FULL JOIN directly.
Quick Summary Table
Command | Purpose | Example Use |
---|---|---|
SELECT | Retrieve columns from a table | SELECT name FROM Students; |
WHERE | Filter rows based on a condition | WHERE age > 18 |
GROUP BY | Group rows for aggregation | GROUP BY department |
ORDER BY | Sort the result | ORDER BY age DESC |
JOINs | Combine rows from multiple tables | INNER JOIN, LEFT JOIN etc. |