SQL Introduction
SQL Introduction
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!
1|Page
To use HTML / CSS
RDBMS
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access
and MS SQL Server).
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
The table above contains five records (one for each customer) and seven columns (CustomerID,
CustomerName, ContactName, Address, City, PostalCode, and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
In this tutorial we will teach you all about the different SQL statements.
2|Page
Keep in Mind That...
3|Page
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
Navigation in a Result-set
Most database software systems allow navigation in the result-set with programming functions,
like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
Programming functions like these are not a part of this tutorial. To learn about accessing data with
function calls, please visit our ASP tutorial or our PHP tutorial.
4|Page
SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
5|Page
SQL WHERE Clause
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
6|Page
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;
The AND & OR operators are used to filter records based on more than one condition.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
7|Page
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "München", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
8|Page
The ORDER BY keyword is used to sort the result-set.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
9|Page
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
10 | P a g e
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
Pirkko
87 Wartian Herkku Torikatu 38 Oulu 90110 Finland
Koskitalo
Wellington Rua do Mercado,
88 Paula Parente Resende08737-363 Brazil
Importadora 12
White Clover 305 - 14th Ave. S.
89 Karl Jablonski Seattle 98128 USA
Markets Suite 3B
Matti
90 Wilman Kala Keskuskatu 45 Helsinki21240 Finland
Karttunen
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
The selection from the "Customers" table will now look like this:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
Pirkko
87 Wartian Herkku Torikatu 38 Oulu 90110 Finland
Koskitalo
Wellington Rua do Mercado,
88 Paula Parente Resende 08737-363 Brazil
Importadora 12
White Clover 305 - 14th Ave.
89 Karl Jablonski Seattle 98128 USA
Markets S. Suite 3B
Matti
90 Wilman Kala Keskuskatu 45 Helsinki 21240 Finland
Karttunen
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
11 | P a g e
Tom B.
92 Cardinal Skagen 21 Stavanger4006 Norway
Erichsen
Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is automatically updated with a unique number for each
record in the table.
The selection from the "Customers" table will now look like this:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
Pirkko
87 Wartian Herkku Torikatu 38 Oulu 90110 Finland
Koskitalo
Wellington Rua do Mercado,
88 Paula Parente Resende 08737-363 Brazil
Importadora 12
White Clover 305 - 14th Ave. S.
89 Karl Jablonski Seattle 98128 USA
Markets Suite 3B
90 Matti
Wilman Kala Keskuskatu 45 Helsinki 21240 Finland
Karttunen
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
12 | P a g e
92 Cardinal null null Stavangernull Norway
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
13 | P a g e
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
The selection from the "Customers" table will now look like this:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Alfred SchmidtObere Str. 57 Hamburg 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Update Warning!
Be careful when updating records. If we had omitted the WHERE clause, in the example above,
like this:
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg';
The "Customers" table would have looked like this:
CustomerIDCustomerName ContactNameAddress City PostalCodeCountry
Alfred
1 Alfreds Futterkiste Obere Str. 57 Hamburg12209 Germany
Schmidt
2 Ana Trujillo Alfred Avda. de la Hamburg05021 Mexico
Emparedados y Schmidt Constitución
14 | P a g e
helados 2222
Antonio Moreno Alfred
3 Mataderos 2312 Hamburg05023 Mexico
Taquería Schmidt
4 Alfred
Around the Horn 120 Hanover Sq. HamburgWA1 1DP UK
Schmidt
Alfred
5 Berglunds snabbköp Berguvsvägen 8 HamburgS-958 22 Sweden
Schmidt
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
15 | P a g e
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
SQL Injection
16 | P a g e
SQL in Web Pages
In the previous chapters, you have learned to retrieve (and update) database data, using SQL.
When SQL is used to display data on a web page, it is common to let web users input their own
search values.
Since SQL statements are text only, it is easy, with a little piece of computer code, to dynamically
change SQL statements to provide the user with selected data:
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The example above, creates a select statement by adding a variable (txtUserId) to a select string.
The variable is fetched from the user input (Request) to the page.
The rest of this chapter describes the potential dangers of using user input in SQL statements.
SQL Injection
SQL injection is a technique where malicious users can inject SQL commands into an SQL
statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web
application.
Server Result
SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always
true.
Does the example above seem dangerous? What if the Users table contains names and passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1
A smart hacker might get access to all the user names and passwords in a database by simply
inserting 105 or 1=1 into the input box.
17 | P a g e
SQL Injection Based on ""="" is Always True
Here is a common construction, used to verify user login to a web site:
User Name:
Password:
Server Code
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
A smart hacker might get access to user names and passwords in a database by simply inserting "
or ""=" into the user name or password text box.
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since WHERE ""="" is
always true.
The code at the server would create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers
18 | P a g e
Parameters for Protection
Some web developers use a "blacklist" of words or characters to search for in SQL input, to
prevent SQL injection attacks.
This is not a very good idea. Many of these words (like delete or drop) and characters (like
semicolons and quotation marks), are used in common language, and should be allowed in many
types of input.
(In fact it should be perfectly legal to input an SQL statement in a database field.)
The only proven way to protect a web site from SQL injection attacks, is to use SQL parameters.
SQL parameters are values that are added to an SQL query at execution time, in a controlled
manner.
ASP.NET Razor Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);
Note that parameters are represented in the SQL statement by a @ marker.
The SQL engine checks each parameter to ensure that it is correct for its column and are treated
literally, and not as part of the SQL to be executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
You have just learned to avoid SQL injection. One of the top website vulnerabilities.
Examples
The following examples shows how to build parameterized queries in some common web
languages.
SELECT STATEMENT IN ASP.NET:
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
INSERT INTO STATEMENT IN ASP.NET:
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
19 | P a g e
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
INSERT INTO STATEMENT IN PHP:
$stmt = $dbh->prepare("INSERT INTO Customers (CustomerName,Address,City)
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();
20 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
21 | P a g e
The SQL LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern.
You will learn more about wildcards in the next chapter.
The following SQL statement selects all customers with a City ending with the letter "s":
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
The following SQL statement selects all customers with a Country containing the pattern "land":
22 | P a g e
Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Using the NOT keyword allows you to select records that do NOT match the pattern.
The following SQL statement selects all customers with Country NOT containing the pattern
"land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
SQL Wildcards
A wildcard character can be used to substitute for any other character(s) in a string.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
23 | P a g e
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
24 | P a g e
Using the SQL [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
The following SQL statement selects all customers with a City NOT starting with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
or
SQL IN Operator
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
25 | P a g e
helados 2222 D.F.
Antonio Moreno Antonio México
3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
IN Operator Example
The following SQL statement selects all customers with a City of "Paris" or "London":
Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 1 2 48 - 6 oz jars 22
26 | P a g e
5 Chef Anton's Gumbo Mix 1 2 36 boxes 21.35
27 | P a g e
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Sample Table
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
Notice that the BETWEEN operator can produce different result in different
databases!
In some databases, BETWEEN selects fields that are between and excluding the test
values.
In other databases, BETWEEN selects fields that are between and including the test values.
And in other databases, BETWEEN selects fields between the test values, including the
first test value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator!
SQL Aliases
28 | P a g e
SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM table_name;
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio México
3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
And a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10354 58 8 1996-11-14 3
10355 4 6 1996-11-15 1
10356 86 6 1996-11-18 2
In the following SQL statement we combine four columns (Address, City, PostalCode, and
Country) and create an alias named "Address":
29 | P a g e
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,', ',Country) AS Address
FROM Customers;
SQL Joins
30 | P a g e
SQL joins are used to combine rows from two or more tables.
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN
return all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Then, have a look at a selection from the "Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, if we run the following SQL statement (that contains an INNER JOIN):
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
31 | P a g e
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right
table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left
table
FULL JOIN: Return all rows when there is a match in ONE of the tables
32 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are rows in the "Customers" table that do not have matches in
"Orders", these customers will NOT be listed.
33 | P a g e
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in
the right table (table2). The result is NULL in the right side when there is no match.
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
34 | P a g e
SQL LEFT JOIN Example
The following SQL statement will return all customers, and any orders they might have:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there
are no matches in the right table (Orders).
35 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
And a selection from the "Employees" table:
EmployeeIDLastNameFirstNameBirthDatePhoto Notes
Education includes a BA in
1 Davolio Nancy 12/8/1968 EmpID1.pic
psychology.....
Andrew received his BTS commercial
2 Fuller Andrew 2/19/1952 EmpID2.pic
and....
3 Leverling Janet 8/30/1963 EmpID3.picJanet has a BS degree in chemistry....
Note: The RIGHT JOIN keyword returns all the rows from the right table (Employees), even if
there are no matches in the left table (Orders).
36 | P a g e
SQL FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
37 | P a g e
A selection from the result set may look like this:
CustomerName OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
10382
10351
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and
all the rows from the right table (Orders). If there are rows in "Customers" that do not have
matches in "Orders", or if there are rows in "Orders" that do not have matches in "Customers",
those rows will be listed as well.
The SQL UNION operator combines the result of two or more SELECT statements.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
38 | P a g e
CustomerID CustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Note: UNION cannot be used to list ALL cities from the two tables. If several customers and
suppliers share the same city, each city will only be listed once. UNION selects only distinct
values. Use UNION ALL to also select duplicate values!
39 | P a g e
SQL UNION ALL With WHERE
The following SQL statement uses UNION ALL to select all (duplicate values also) German
cities from the "Customers" and "Suppliers" tables:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
With SQL, you can copy information from one table into another.
The SELECT INTO statement copies data from one table and inserts it into a new table.
40 | P a g e
SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers;
Copy only a few columns into the new table:
SELECT CustomerName, ContactName
INTO CustomersBackup2013
FROM Customers;
Copy only the German customers into the new table:
SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany';
Copy data from more than one table into the new table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2013
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;
Tip: The SELECT INTO statement can also be used to create a new, empty table using the
schema of another. Just add a WHERE clause that causes the query to return no data:
SELECT *
INTO newtable
FROM table1
WHERE 1=0;
With SQL, you can copy information from one table into another.
The INSERT INTO SELECT statement copies data from one table and inserts it into an existing
table.
41 | P a g e
Or we can copy only the columns we want to into another, existing table:
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
42 | P a g e
SQL CREATE DATABASE Statement
43 | P a g e
SQL CREATE TABLE Example
Now we want to create a table called "Persons" that contains five columns: PersonID, LastName,
FirstName, Address, and City.
We use the following CREATE TABLE statement:
Example
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
SQL Constraints
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the
constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or
after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
In SQL, we have the following constraints:
44 | P a g e
NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have an unique identity which helps to find a
particular record in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values
in another table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value when specified none for this column
45 | P a g e
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
46 | P a g e
ALTER TABLE Persons
ADD UNIQUE (P_Id)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
47 | P a g e
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint
on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the
VALUE of the primary key is made up of TWO COLUMNS (P_Id + LastName).
48 | P a g e
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
49 | P a g e
SQL FOREIGN KEY Constraint on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is
created:
MySQL:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint
on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
50 | P a g e
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
51 | P a g e
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)
52 | P a g e
MySQL:
ALTER TABLE Persons
DROP CHECK chk_Person
53 | P a g e
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'SANDNES'
Indexes
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that will
be frequently searched against.
SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
54 | P a g e
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the
syntax for creating indexes in your database.
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
55 | P a g e
The DROP DATABASE Statement
The DROP DATABASE statement is used to delete a database.
DROP DATABASE database_name
56 | P a g e
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons
ADD DateOfBirth date
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold. For a complete reference of all the data
types available in MS Access, MySQL, and SQL Server, go to our complete Data Types
reference.
The "Persons" table will now look like this:
P_Id LastName FirstName Address City DateOfBirth
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
57 | P a g e
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Auto-increment allows a unique number to be generated when a new record is inserted into a
table.
58 | P a g e
The SQL statement above would insert a new record into the "Persons" table. The "ID" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".
59 | P a g e
By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each
new record.
Tip: To specify that the "ID" column should start at value 10 and increment by 5, change the
autoincrement to AUTOINCREMENT(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID"
column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".
SQL Views
60 | P a g e
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
61 | P a g e
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date
you are trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However,
if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most important
built-in functions for working with dates.
62 | P a g e
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
63 | P a g e
Note: The date types are chosen for a column when you create a new table in your database!
For an overview of all data types available, go to our complete Data Types reference.
64 | P a g e
NULL values represent missing unknown data.
By default, a table column can hold NULL values.
This chapter will explain the IS NULL and IS NOT NULL operators.
Note: It is not possible to compare NULL and 0; they are not equivalent.
SQL IS NULL
How do we select only the records with NULL values in the "Address" column?
We will have to use the IS NULL operator:
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL
65 | P a g e
Hansen Ola
Pettersen Kari
66 | P a g e
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a
zero if the value is NULL:
MS Access
SELECT ProductName,UnitPrice*(UnitsInStock+IIF(ISNULL(UnitsOnOrder),0,UnitsOnOrder))
FROM Products
SQL Server
SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products
Oracle
Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve
the same result:
SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products
MySQL
MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's
ISNULL() function.
In MySQL we can use the IFNULL() function, like this:
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
or we can use the COALESCE() function, like this:
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
67 | P a g e
VARCHAR(n) or
CHARACTER Character string. Variable length. Maximum length n
VARYING(n)
BINARY(n) Binary string. Fixed-length n
BOOLEAN Stores TRUE or FALSE values
VARBINARY(n) or
Binary string. Variable length. Maximum length n
BINARY VARYING(n)
INTEGER(p) Integer numerical (no decimal). Precision p
SMALLINT Integer numerical (no decimal). Precision 5
INTEGER Integer numerical (no decimal). Precision 10
BIGINT Integer numerical (no decimal). Precision 19
Exact numerical, precision p, scale s. Example: decimal(5,2) is a number
DECIMAL(p,s)
that has 3 digits before the decimal and 2 digits after the decimal
NUMERIC(p,s) Exact numerical, precision p, scale s. (Same as DECIMAL)
Approximate numerical, mantissa precision p. A floating number in base
FLOAT(p) 10 exponential notation. The size argument for this type consists of a
single number specifying the minimum precision
REAL Approximate numerical, mantissa precision 7
FLOAT Approximate numerical, mantissa precision 16
DOUBLE PRECISION Approximate numerical, mantissa precision 16
DATE Stores year, month, and day values
TIME Stores hour, minute, and second values
TIMESTAMP Stores year, month, day, hour, minute, and second values
Composed of a number of integer fields, representing a period of time,
INTERVAL
depending on the type of interval
ARRAY A set-length and ordered collection of elements
MULTISET A variable-length and unordered collection of elements
XML Stores XML data
68 | P a g e
Data type Access SQLServer Oracle MySQL PostgreSQL
boolean Yes/No Bit Byte N/A Boolean
Number Int Int
integer Int Number
(integer) Integer Integer
Float
float Number (single) Number Float Numeric
Real
currency Currency Money N/A N/A Money
string (fixed) N/A Char Char Char Char
Text (<256) Varchar
string (variable) Varchar Varchar Varchar
Memo (65k+) Varchar2
Binary (fixed up to
OLE Object 8K) Long Blob Binary
binary object
Memo Varbinary (<8K) Raw Text Varbinary
Image (<2GB)
Note: Data types might have different names in different database. And even if
the name is the same, the size and other details may be different! Always check
the documentation!
Data types and ranges for Microsoft Access, MySQL and SQL Server.
69 | P a g e
Double Double precision floating-point. Will handle most decimals 8 bytes
Use for currency. Holds up to 15 digits of whole dollars, plus 4
Currency decimal places. Tip: You can choose which country's currency to 8 bytes
use
AutoNumber fields automatically give each record its own number,
AutoNumber 4 bytes
usually starting at 1
Date/Time Use for dates and times 8 bytes
A logical field can be displayed as Yes/No, True/False, or On/Off.
Yes/No In code, use the constants True and False (equivalent to -1 and 0). 1 bit
Note: Null values are not allowed in Yes/No fields
Can store pictures, audio, video, or other BLOBs (Binary Large up to
Ole Object
OBjects) 1GB
Hyperlink Contain links to other files, including web pages
Let you type a list of options, which can then be chosen from a drop-
Lookup Wizard 4 bytes
down list
70 | P a g e
inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
Similar to ENUM except that SET may contain up to 64 list items and can
SET
store more than one choice
Number types:
Data type Description
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits
TINYINT(size)
may be specified in parenthesis
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of
SMALLINT(size)
digits may be specified in parenthesis
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum
MEDIUMINT(size)
number of digits may be specified in parenthesis
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The
INT(size)
maximum number of digits may be specified in parenthesis
-9223372036854775808 to 9223372036854775807 normal. 0 to
BIGINT(size) 18446744073709551615 UNSIGNED*. The maximum number of digits may
be specified in parenthesis
A small number with a floating decimal point. The maximum number of
FLOAT(size,d) digits may be specified in the size parameter. The maximum number of digits
to the right of the decimal point is specified in the d parameter
A large number with a floating decimal point. The maximum number of digits
DOUBLE(size,d) may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter. The
DECIMAL(size,d)
maximum number of digits to the right of the decimal point is specified in the
d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at
zero instead of a negative number.
Date types:
Data type Description
A date. Format: YYYY-MM-DD
DATE()
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31
71 | P a g e
23:59:59'
*A timestamp. TIMESTAMP values are stored as the number of seconds since
the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD
TIMESTAMP() HH:MI:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC
A time. Format: HH:MI:SS
TIME()
Note: The supported range is from '-838:59:59' to '838:59:59'
A year in two-digit or four-digit format.
YEAR() Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in
two-digit format: 70 to 69, representing years from 1970 to 2069
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and
time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMISS,
YYMMDDHHMISS, YYYYMMDD, or YYMMDD.
72 | P a g e
image Variable width binary string. Maximum 2GB
Number types:
Data type Description Storage
tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Allows whole numbers between -9,223,372,036,854,775,808 and
bigint 8 bytes
9,223,372,036,854,775,807
Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that
decimal(p,s) can be stored (both to the left and to the right of the decimal point). 5-17
p must be a value from 1 to 38. Default is 18. bytes
float(n) The n parameter indicates whether the field should hold 4 or 8 bytes. 4 or 8
float(24) holds a 4-byte field and float(53) holds an 8-byte field. bytes
Default value of n is 53.
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
Date types:
Data type Description Storage
From January 1, 1753 to December 31, 9999 with an accuracy of
datetime 8 bytes
3.33 milliseconds
From January 1, 0001 to December 31, 9999 with an accuracy of
datetime2 6-8 bytes
100 nanoseconds
73 | P a g e
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes
8-10
datetimeoffset The same as datetime2 with the addition of a time zone offset
bytes
Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an internal
timestamp
clock and does not correspond to real time. Each table may have
only one timestamp variable
Other data types:
Data type Description
Stores up to 8,000 bytes of data of various data types, except text, ntext, and
sql_variant
timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML formatted data. Maximum 2GB
cursor Stores a reference to a cursor used for database operations
table Stores a result-set for later processing
74 | P a g e
SQL Functions
Tip: The aggregate functions and the scalar functions will be explained in details in the next
chapters.
75 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
The following SQL statement selects the "ProductName" and "Price" records that have an above
average price:
Example
SELECT ProductName, Price FROM Products
WHERE Price>(SELECT AVG(Price) FROM Products);
The COUNT() function returns the number of rows that matches a specified criteria.
76 | P a g e
SELECT COUNT(column_name) FROM table_name;
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1
77 | P a g e
SQL COUNT(DISTINCT column_name) Example
The following SQL statement counts the number of unique customers in the "Orders" table:
Example
SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;
78 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
79 | P a g e
SQL LAST() Workaround in SQL Server, MySQL and Oracle
SQL Server Syntax
SELECT TOP 1 column_name FROM table_name
ORDER BY column_name DESC;
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
WHERE ROWNUM <=1;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
80 | P a g e
Berglund
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
81 | P a g e
SQL MIN() Function
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
82 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "OrderDetails" table:
OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
83 | P a g e
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
And a selection from the "Shippers" table:
ShipperID ShipperName Phone
1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931
And a selection from the "Employees" table:
EmployeeID LastName FirstName BirthDate Photo Notes
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....
84 | P a g e
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
And a selection from the "Employees" table:
EmployeeID LastName FirstName BirthDate Photo Notes
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....
85 | P a g e
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
Now we want to find if the employees "Davolio" or "Fuller" have registered more than 25 orders.
We add an ordinary WHERE clause to the SQL statement:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
86 | P a g e
Berglund
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
87 | P a g e
SQL LCASE() Example
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table, and converts the "CustomerName" column to lowercase:
Example
SELECT LCASE(CustomerName) AS Customer, City
FROM Customers;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
88 | P a g e
SQL MID() Example
The following SQL statement selects the first four characters from the "City" column from the
"Customers" table:
Example
SELECT MID(City,1,4) AS ShortCity
FROM Customers;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerIDCustomerName ContactName Address City PostalCodeCountry
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
89 | P a g e
SQL ROUND() Function
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
90 | P a g e
SQL NOW() Function
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
91 | P a g e
column_name Required. The field to be formatted.
format Required. Specifies the format.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 21.35
5 Chef Anton's Gumbo Mix 2 2 36 boxes 25
92 | P a g e
or
SELECT column_name
FROM table_name AS table_alias
SELECT column_name(s)
FROM table_name
BETWEEN
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE table_name
(
column_name1 data_type,
CREATE TABLE column_name2 data_type,
column_name3 data_type,
...
)
CREATE INDEX index_name
ON table_name (column_name)
or
CREATE INDEX
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE VIEW view_name AS
SELECT column_name(s)
CREATE VIEW
FROM table_name
WHERE condition
DELETE FROM table_name
WHERE some_column=some_value
or
93 | P a g e
GROUP BY column_name
SELECT column_name, aggregate_function(column_name)
FROM table_name
HAVING WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SELECT column_name(s)
FROM table_name
IN
WHERE column_name
IN (value1,value2,..)
INSERT INTO table_name
VALUES (value1, value2, value3,....)
or
INSERT INTO
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
SELECT column_name(s)
FROM table_name1
INNER JOIN
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SELECT column_name(s)
FROM table_name1
LEFT JOIN
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SELECT column_name(s)
FROM table_name1
RIGHT JOIN
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SELECT column_name(s)
FROM table_name1
FULL JOIN
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SELECT column_name(s)
LIKE FROM table_name
WHERE column_name LIKE pattern
SELECT column_name(s)
ORDER BY FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT column_name(s)
SELECT
FROM table_name
SELECT *
SELECT *
FROM table_name
SELECT DISTINCT column_name(s)
SELECT DISTINCT
FROM table_name
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name
or
SELECT INTO
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
94 | P a g e
SELECT TOP number|percent column_name(s)
SELECT TOP
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
SELECT column_name(s) FROM table_name1
UNION UNION
SELECT column_name(s) FROM table_name2
SELECT column_name(s) FROM table_name1
UNION ALL UNION ALL
SELECT column_name(s) FROM table_name2
UPDATE table_name
UPDATE SET column1=value, column2=value,...
WHERE some_column=some_value
SELECT column_name(s)
WHERE FROM table_name
WHERE column_name operator value
SQL Hosting
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server
should have access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look for SQL
hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.
MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web sites with high
traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Oracle
Oracle is also a popular database software for database-driven web sites with high traffic.
Oracle is a very powerful, robust and full featured SQL database system.
MySQL
MySQL is also a popular database software for web sites.
MySQL is a very powerful, robust and full featured SQL database system.
MySQL is an inexpensive alternative to the expensive Microsoft and Oracle solutions.
95 | P a g e
Access
When a web site requires only a simple database, Microsoft Access can be a solution.
Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server, or
Oracle.
96 | P a g e