SQL (W3School)
SQL (W3School)
Introduction to SQL
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
However, to be compliant with the ANSI standard, they all support at least
the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a
similar manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Every table is broken up into smaller entities called fields. The fields in the
Customers table consist of CustomerID, CustomerName, ContactName,
Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For
example, there are 91 records in the above Customers table. A record is a
horizontal entity in a table.
SQL Syntax
SQL Statements
SQL statements consists of keywords.
The following SQL statement returns all records from a table named
"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.
SQL SELECT
DISTINCT Statement
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different)
values.
Count Distinct
By using the DISTINCT keyword in a function called COUNT, we can return the
number of different countries.
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.!
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be
written as !=
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:
Example
Sort the products alphabetically by ProductName:
Alphabetically DESC
To sort the table reverse alphabetically, use the DESC keyword:
Example
Sort the products by ProductName in reverse order:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Using Both ASC and DESC
The following SQL statement selects all customers from the "Customers"
table, sorted ascending by the "Country" and descending by the
"CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
The AND operator is used to filter records based on more than one condition,
like if you want to return all customers from Spain that starts with the letter
'G':
Example
Select all customers from Spain that starts with the letter 'G':
SELECT *
FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';
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.
Example
SELECT * FROM Customers
WHERE Country = 'Germany'
AND City = 'Berlin'
AND PostalCode > 12000;
The following SQL statement selects all customers from Spain that starts with
a "G" or an "R".
Example
Select all Spanish customers that starts with either "G" or "R":
Without parenthesis, the select statement will return all customers from
Spain that starts with a "G", plus all customers that starts with an "R",
regardless of the country value:
Example
Select all customers that either:
are from Spain and starts with either "G", or
starts with the letter "R":
SQL OR Operator
The SQL OR Operator
The WHERE clause can contain one or more OR operators.
The OR operator is used to filter records based on more than one condition,
like if you want to return all customers from Germany but also those from
Spain:
Example
Select all customers from Germany or Spain:
SELECT *
FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';
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.
Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country = 'Norway';
The following SQL statement selects all customers from Spain that starts with
a "G" or an "R".
Example
Select all Spanish customers that starts with either "G" or "R":
Without parenthesis, the select statement will return all customers from
Spain that starts with a "G", plus all customers that starts with an "R",
regardless of the country value:
Example
Select all customers that either:
are from Spain and starts with either "G", or
starts with the letter "R":
SELECT * FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G
%' OR CustomerName LIKE 'R%';
In the select statement below we want to return all customers that are NOT
from Spain:
Example
Select only the customers that are NOT from Spain:
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:
NOT IN
Example
Select customers that are not from Paris or London:
Note: There is a not-greater-than operator: !> that would give you the same
result.
NOT Less Than
Example
Select customers with a CustomerID not less than 50:
Note: There is a not-less-than operator: !< that would give you the same
result.
2. If you are adding values for all the columns of the table, you do not need
to specify the column names in the SQL query. However, make sure the
order of the values is in the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:
Did you notice that we did not insert any number into the
CustomerID field?
The CustomerID column is an auto-increment field and will be generated
automatically when a new record is inserted into the table.
The following SQL statement will insert a new record, but only insert data in
the "CustomerName", "City", and "Country" columns (CustomerID will be
updated automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
To insert multiple rows of data, we use the same INSERT INTO statement, but
with multiple values:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien
15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1
0AA', 'UK');
Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during
record creation!
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
The following SQL lists all customers with a NULL value in the "Address"
field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should
be updated. If you omit the WHERE clause, all records in the table will be
updated!
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1)
with a new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The following SQL statement will update the ContactName to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
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 Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:
Example
DELETE FROM Customers;
Delete a Table
To delete the table completely, use the DROP TABLE statement:
Example
Remove the Customers table:
The SELECT TOP clause is useful on large tables with thousands of records.
Returning a large number of records can impact performance.
Example
Select only the first 3 records of the Customers table:
Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while Oracle
uses FETCH FIRST n ROWS ONLY and ROWNUM.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
LIMIT
The following SQL statement shows the equivalent example for MySQL:
Example
Select the first 3 records of the Customers table:
FETCH FIRST
The following SQL statement shows the equivalent example for Oracle:
Example
Select the first 3 records of the Customers table:
Example
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
ADD a WHERE CLAUSE
The following SQL statement selects the first three records from the
"Customers" table, where the country is "Germany"
Example
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;
The MAX() function returns the largest value of the selected column.
MIN Example
Find the lowest price in the Price column:
SELECT MIN(Price)
FROM Products;
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;
Set Column Name (Alias)
When you use MIN() or MAX(), the returned column will not have a
descriptive name. To give the column a descriptive name, use
the AS keyword:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
Example
SELECT MIN(Price) AS SmallestPrice, CategoryID
FROM Products
GROUP BY CategoryID;
Example
Find the total number of rows in the Products table:
SELECT COUNT(*)
FROM Products;
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;
Example
Find the number of products where Price is higher than 20:
SELECT COUNT(ProductID)
FROM Products
WHERE Price > 20;
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:
Use an Alias
Give the counted column a name by using the AS keyword.
Example
Name the column "Number of records":
Example
SELECT COUNT(*) AS [Number of records], CategoryID
FROM Products
GROUP BY CategoryID;
SELECT SUM(Quantity)
FROM OrderDetails;
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example
Return the sum of the Quantity field for the product with ProductID 11:
SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
Use an Alias
Give the summarized column a name by using the AS keyword.
Example
Name the column "total":
Example
SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;
Example
Use an expression inside the SUM() function:
We can also join the OrderDetails table to the Products table to find the actual
amount, instead of assuming it is 10 dollars:
Example
Join OrderDetails with Products, and use SUM() to find the total amount:
Example
Find the average price of all products:
SELECT AVG(Price)
FROM Products;
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example
Return the average price of products in category 1:
SELECT AVG(Price)
FROM Products
WHERE CategoryID = 1;
Use an Alias
Give the AVG column a name by using the AS keyword.
Example
Name the column "average price":
Example
Return all products with a higher price than the average price:
Example
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign % represents zero, one, or multiple characters
The underscore sign _ represents one, single character
Example
Select all customers that starts with the letter "a":
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:
The % Wildcard
The % wildcard represents any number of characters, even zero characters.
Example
Return all customers from a city that contains the letter 'L':
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':
Example
Return all customers that starts with 'a' or starts with 'b':
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':
Example
Return all customers that starts with "b" and ends with "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'
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:
Example
Return all customers that have "r" in the second position:
Example
Return all customers from Spain:
SQL Wildcards
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the LIKE operator. The LIKE operator is
used in a WHERE clause to search for a specified pattern in a column.
Example
Return all customers that starts with the letter 'a':
Wildcard Characters
Symbol Description
Example
Return all customers that ends with the pattern 'es':
Example
Return all customers that contains the pattern 'mer':
It can be any character or number, but each _ represents one, and only one,
character.
Example
Return all customers with a City starting with any character, followed by
"ondon":
Example
Return all customers with a City starting with "L", followed by any 3
characters, ending with "on":
Example
Return all customers starting with either "b", "s", or "p":
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:
Example
Return all customers that have "r" in the second position:
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:
Example
Return all customers from 'Germany', 'France', or 'UK'
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
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':
IN (SELECT)
You can also use IN with a subquery in the WHERE clause.
With a subquery you can return all records from the main query that are
present in the result of the subquery.
Example
Return all customers that have an order in the Orders table:
NOT IN (SELECT)
The result in the example above returned 74 records, that means that there
are 17 customers that haven't placed any orders.
Example
Return all customers that have NOT placed any orders in the Orders table:
The BETWEEN operator is inclusive: begin and end values are included.
Example
Selects all products with a price between 10 and 20:
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;
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);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName
between Carnarvon Tigers and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
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/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary
name.
Example
SELECT CustomerID AS ID
FROM Customers;
AS is Optional
Actually, in most database languages, you can skip the AS keyword and get
the same result:
Example
SELECT CustomerID ID
FROM Customers;
Syntax
When alias is used on column:
SELECT column_name(s)
FROM table_name AS alias_name;
Alias for Columns
The following SQL statement creates two aliases, one for the CustomerID
column and one for the CustomerName column:
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Example
Using [square brackets] for aliases with space characters:
Example
Using "double quotes" for aliases with space characters:
Note: Some database systems allows both [] and "", and some only allows
one of them.
Concatenate Columns
The following SQL statement creates an alias named "Address" that combine
four columns (Address, PostalCode, City and Country):
Example
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;
Example
Refer to the Customers table as Persons instead:
It might seem useless to use aliases on tables, but when you are using more
than one table in your queries, it can make the SQL statements shorter.
The following SQL statement selects all the orders from the customer with
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders"
tables, and give them the table aliases of "c" and "o" respectively (Here we
use aliases to make the SQL shorter):
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
The following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.