sql hand notes
sql hand notes
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National
Standards Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987
SQL Statements
Most of the actions you need to perform on a database are
done with SQL statements.
SQL statements consist of keywords that are easy to
understand.
The following SQL statement returns all records from a table
named "Customers":
Example
Select all records from the Customers table:
SELECT * FROM Customers;
Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the
table you want to select data from.
The table_name represents the name of the table you
want to select data from.
Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Example Without DISTINCT
If you omit the DISTINCT keyword, the SQL statement
returns the "Country" value from all the records of the
"Customers" table:
Example
SELECT Country FROM Customers;
Count Distinct
By using the DISTINCT keyword in a function called COUNT,
we can return the number of different countries.
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Note: The COUNT(DISTINCT column_name) is not
supported in Microsoft Access databases.
Here is a workaround for MS Access:
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used
in SELECT statements, it is also used in UPDATE, DELETE,
etc.!
Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
DESC
The ORDER BY keyword sorts the records in ascending
order by default. To sort the records in descending order,
use the DESC keyword.
Example
Sort the products from highest to lowest price:
SELECT * FROM Products
ORDER BY Price DESC;
Order Alphabetically
For string values the ORDER BY keyword will order
alphabetically:
Example
Sort the products alphabetically by ProductName:
SELECT * FROM Products
ORDER BY ProductName;
Alphabetically DESC
To sort the table reverse alphabetically, use
the DESC keyword:
Example
Sort the products by ProductName in reverse order:
SELECT * FROM Products
ORDER BY ProductName DESC;
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
AND vs OR
The AND operator displays a record if all the conditions are
TRUE.
The OR operator displays a record if any of the conditions
are TRUE.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
OR vs AND
The OR operator displays a record if any of the conditions
are TRUE.
The AND operator displays a record if all the conditions are
TRUE.
At Least One Condition Must Be True
The following SQL statement selects all fields from
Customers where either City is
"Berlin", CustomerName starts with the letter "G"
or Country is "Norway":
Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G
%' OR Country = 'Norway';
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
NOT LIKE
Example
Select customers that does not start with the letter 'A':
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'A%';
NOT BETWEEN
Example
Select customers with a customerID not between 10 and
60:
SELECT * FROM Customers
WHERE CustomerID NOT BETWEEN 10 AND 60;
NOT IN
Example
Select customers that are not from Paris or London:
SELECT * FROM Customers
WHERE City NOT IN ('Paris', 'London');
UPDATE Table
The following SQL statement updates the first customer
(CustomerID = 1) with a new contact person and a new
city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
Update Warning!
Be careful when updating records. If you omit
the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET ContactName='Juan';
Delete a Table
To delete the table completely, use the DROP
TABLE statement:
Example
Remove the Customers table:
DROP TABLE Customers;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
Older Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
LIMIT
The following SQL statement shows the equivalent
example for MySQL:
Example
Select the first 3 records of the Customers table:
SELECT * FROM Customers
LIMIT 3;
Try it Yourself »
FETCH FIRST
The following SQL statement shows the equivalent
example for Oracle:
Example
Select the first 3 records of the Customers table:
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
MAX Example
Find the highest price in the Price column:
SELECT MAX(Price)
FROM Products;
Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Specify Column
You can specify a column name instead of the asterix
symbol (*).
If you specify a column name instead of (*), NULL values
will not be counted.
Example
Find the number of products where the ProductName is
not null:
SELECT COUNT(ProductName)
FROM Products;
Ignore Duplicates
You can ignore duplicates by using the DISTINCT keyword
in the COUNT() function.
If DISTINCT is specified, rows with the same value for the
specified column will be counted as one.
Example
How many different prices are there in the Products table:
SELECT COUNT(DISTINCT Price)
FROM Products;
Use an Alias
Give the counted column a name by using the AS keyword.
Example
Name the column "Number of records":
SELECT COUNT(*) AS [Number of records]
FROM Products;
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Use an Alias
Give the summarized column a name by using
the AS keyword.
Example
Name the column "total":
SELECT SUM(Quantity) AS total
FROM OrderDetails;
Use an Alias
Give the summarized column a name by using
the AS keyword.
Example
Name the column "total":
SELECT SUM(Quantity) AS total
FROM OrderDetails;
Use an Alias
Give the AVG column a name by using the AS keyword.
Example
Name the column "average price":
SELECT AVG(Price) AS [average price]
FROM Products;
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
The _ Wildcard
The _ wildcard represents a single character.
It can be any character or number, but each _ represents
one, and only one, character.
Example
Return all customers from a city that starts with 'L'
followed by one wildcard character, then 'nd' and then two
wildcard characters:
SELECT * FROM Customers
WHERE city LIKE 'L_nd__';
The % Wildcard
The % wildcard represents any number of characters, even
zero characters.
Example
Return all customers from a city that contains the letter 'L':
SELECT * FROM Customers
WHERE city LIKE '%L%';
Try it Yourself »
Starts With
To return records that starts with a specific letter or
phrase, add the % at the end of the letter or phrase.
Example
Return all customers that starts with 'La':
SELECT * FROM Customers
WHERE CustomerName LIKE 'La%';
Try it Yourself »
Tip: You can also combine any number of conditions
using AND or OR operators.
Example
Return all customers that starts with 'a' or starts with 'b':
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%' OR CustomerName LIKE '
b%';
Try it Yourself »
Ends With
To return records that ends with a specific letter or phrase,
add the % at the beginning of the letter or phrase.
Example
Return all customers that ends with 'a':
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Try it Yourself »
Tip: You can also combine "starts with" and "ends with":
Example
Return all customers that starts with "b" and ends with "s":
SELECT * FROM Customers
WHERE CustomerName LIKE 'b%s';
Contains
To return records that contains a specific letter or phrase,
add the % both before and after the letter or phrase.
Example
Return all customers that contains the phrase 'or'
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Combine Wildcards
Any wildcard, like % and _ , can be used in combination
with other wildcards.
Example
Return all customers that starts with "a" and are at least 3
characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Example
Return all customers that have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Without Wildcard
If no wildcard is specified, the phrase has to have an exact
match to return a result.
Example
Return all customers from Spain:
SELECT * FROM Customers
WHERE Country LIKE 'Spain';
SQL Wildcards
Example
Return all customers with a City starting with "L", followed
by any 3 characters, ending with "on":
SELECT * FROM Customers
WHERE City LIKE 'L___on';
Combine Wildcards
Any wildcard, like % and _ , can be used in combination
with other wildcards.
Example
Return all customers that starts with "a" and are at least 3
characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Example
Return all customers that have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Without Wildcard
If no wildcard is specified, the phrase has to have an exact
match to return a result.
Example
Return all customers from Spain:
SELECT * FROM Customers
WHERE Country LIKE 'Spain';
SQL IN Operator
NOT IN
By using the NOT keyword in front of the IN operator, you
return all records that are NOT any of the values in the list.
Example
Return all customers that are NOT from 'Germany',
'France', or 'UK':
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
NOT BETWEEN
To display the products outside the range of the previous
example, use NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Try it Yourself »
BETWEEN with IN
The following SQL statement selects all products with a
price between 10 and 20. In addition, the CategoryID must
be either 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID IN (1,2,3);
Try it Yourself »
BETWEEN Dates
The following SQL statement selects all orders with an
OrderDate between '01-July-1996' and '31-July-1996':
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1
996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-
31';
NOT BETWEEN
To display the products outside the range of the previous
example, use NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Try it Yourself »
BETWEEN with IN
The following SQL statement selects all products with a
price between 10 and 20. In addition, the CategoryID must
be either 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID IN (1,2,3);
Try it Yourself »
Concatenate Columns
The following SQL statement creates an alias named
"Address" that combine four columns (Address,
PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' +
City + ', ' + Country AS Address
FROM Customers;
Try it Yourself »
Note: To get the SQL statement above to work in MySQL
use the following:
MySQL Example
SELECT CustomerName, CONCAT(Address,', ',PostalCode,',
',City,', ',Country) AS Address
FROM Customers;
Try it Yourself »
Note: To get the SQL statement above to work in Oracle
use the following:
Oracle Example
SELECT CustomerName, (Address || ', ' || PostalCode || '
' || City || ', ' || Country) AS Address
FROM Customers;
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more
tables, based on a related column between them.
Let's look at a selection from the "Orders" table:
INNER JOIN
The INNER JOIN keyword selects records that have
matching values in both tables.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
ADVERTISEMENT
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products W
HERE Products.SupplierID = Suppliers.supplierID AND Price
= 22);
SQL Views