SELECT Statements
The SELECT
statement is used to query the database and retrieve data that matches specified criteria.
Basic SELECT Syntax
The most basic SELECT
statement retrieves all columns and all rows from a table:
SELECT *
FROM TableName;
Selecting Specific Columns
You can specify which columns you want to retrieve by listing them after the SELECT
keyword, separated by commas:
SELECT Column1, Column2, Column3
FROM TableName;
Filtering Data with WHERE Clause
The WHERE
clause is used to extract only those records that fulfill a specified condition.
SELECT Column1, Column2
FROM TableName
WHERE Column1 = 'SomeValue';
Common WHERE Operators:
Operator | Description |
---|---|
= |
Equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
<> or != |
Not equal |
BETWEEN |
Between an inclusive range |
LIKE |
Search for a pattern |
IN |
Specifies multiple possible values |
Sorting Data with ORDER BY Clause
The ORDER BY
clause is used to sort the result-set in ascending or descending order.
Default sort order is ascending (ASC
).
SELECT Column1, Column2
FROM TableName
ORDER BY Column1 ASC;
SELECT Column1, Column2
FROM TableName
ORDER BY Column1 DESC;
Using DISTINCT Keyword
The DISTINCT
keyword is used to return only unique values.
SELECT DISTINCT Column1
FROM TableName;
Limiting Results
The LIMIT
clause (syntax may vary slightly between different SQL dialects, e.g., TOP
in SQL Server) restricts the number of rows returned.
-- Standard SQL / MySQL / PostgreSQL
SELECT Column1, Column2
FROM TableName
LIMIT 10;
-- SQL Server
SELECT TOP 10 Column1, Column2
FROM TableName;
Aggregate Functions
SELECT
can be used with aggregate functions to perform calculations on a set of rows.
COUNT()
: Returns the number of rows.AVG()
: Returns the average value of a column.SUM()
: Returns the total sum of a numeric column.MIN()
: Returns the minimum value in a column.MAX()
: Returns the maximum value in a column.
SELECT COUNT(CustomerID)
FROM Customers;
SELECT AVG(Price)
FROM Products;
GROUP BY Clause
The GROUP BY
clause groups rows that have the same values in specified columns into summary rows, like "find the number of customers in each country".
SELECT Country, COUNT(CustomerID) AS NumberOfCustomers
FROM Customers
GROUP BY Country
ORDER BY NumberOfCustomers DESC;