--The SELECT statement is used to select data from a database.
--SQL SELECT Syntax:
SELECT column_name,column_name
FROM table_name;
--or:
SELECT * FROM table_name;
--SELECT Column Example
SELECT CustomerName,City FROM Customers;
--SELECT * Example
SELECT * FROM Customers;
--The SQL SELECT DISTINCT Statement
--The SELECT DISTINCT statement is used to return only distinct (different) values.
--SQL SELECT DISTINCT Syntax:
SELECT DISTINCT column_name,column_name
FROM table_name;
--SELECT DISTINCT Example
SELECT DISTINCT City FROM Customers;
--The SQL WHERE Clause
--The WHERE clause is used to filter records.
--SQL WHERE Syntax
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
--Example:
SELECT * FROM Customers
WHERE Country='Mexico';
--Text Fields vs. Numeric Fields
--SQL requires single quotes around text values (most database systems will also allow double quotes).
--However, numeric fields should not be enclosed in quotes:
--Example:
SELECT * FROM Customers
WHERE CustomerID=1;
--Operators in The WHERE Clause
/*
The following operators can be used in the WHERE clause:
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
*/
--SQL AND & OR Operators
--The AND & OR operators are used to filter records based on more than one condition.
--AND Example:
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
--OR Example:
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
--Combining AND and OR Example:
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
--ORDER BY
--The ORDER BY keyword is used to sort the result-set.
--SQL ORDER BY Syntax:
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;
--Example:
SELECT * FROM Customers
ORDER BY Country;
--ORDER BY DESC Example:
SELECT * FROM Customers
ORDER BY Country DESC;
--ORDER BY Several Columns Examples:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;