Académique Documents
Professionnel Documents
Culture Documents
Contents
What is SQL? .................................................................................................................................... 13
What Can SQL do? ........................................................................................................................... 13
SQL is a Standard - BUT.... .............................................................................................................. 13
Using SQL in Your Web Site............................................................................................................ 14
RDBMS ............................................................................................................................................. 14
Database Tables ................................................................................................................................ 14
SQL Statements ................................................................................................................................. 15
Example............................................................................................................................................. 15
Keep in Mind That... ......................................................................................................................... 15
Semicolon after SQL Statements?..................................................................................................... 16
Some of The Most Important SQL Commands................................................................................. 16
The SQL SELECT Statement ........................................................................................................... 16
SQL SELECT Syntax.................................................................................................................... 17
Demo Database ................................................................................................................................. 17
SELECT Column Example ............................................................................................................... 18
Example............................................................................................................................................. 18
SELECT * Example .......................................................................................................................... 18
Example............................................................................................................................................. 18
Navigation in a Result-set ................................................................................................................. 18
The SQL SELECT DISTINCT Statement ........................................................................................ 19
SQL SELECT DISTINCT Syntax ................................................................................................ 19
Demo Database ................................................................................................................................. 19
SELECT DISTINCT Example .......................................................................................................... 20
Example............................................................................................................................................. 20
The SQL WHERE Clause ................................................................................................................. 20
SQL WHERE Syntax .................................................................................................................... 20
Demo Database ................................................................................................................................. 20
WHERE Clause Example.................................................................................................................. 21
Example............................................................................................................................................. 21
Text Fields vs. Numeric Fields ......................................................................................................... 21
Example............................................................................................................................................. 22
Operators in The WHERE Clause..................................................................................................... 22
Page 1 of 131
Page 2 of 131
Page 3 of 131
Page 4 of 131
Page 5 of 131
Example ............................................................................................................................................. 66
SQL UNION ALL With WHERE ............................................................................................................ 67
Example ............................................................................................................................................. 67
The SQL SELECT INTO Statement ...................................................................................................... 67
SQL SELECT INTO Syntax................................................................................................................ 67
SQL SELECT INTO Examples ............................................................................................................... 68
The SQL INSERT INTO SELECT Statement .......................................................................................... 69
SQL INSERT INTO SELECT Syntax ................................................................................................... 69
Demo Database ................................................................................................................................. 69
SQL INSERT INTO SELECT Examples .................................................................................................. 70
Example ............................................................................................................................................. 70
Example ............................................................................................................................................. 70
The SQL CREATE DATABASE Statement ............................................................................................ 70
SQL CREATE DATABASE Syntax ..................................................................................................... 70
SQL CREATE DATABASE Example ...................................................................................................... 71
The SQL CREATE TABLE Statement ................................................................................................... 71
SQL CREATE TABLE Syntax ............................................................................................................. 71
SQL CREATE TABLE Example.............................................................................................................. 71
Example ............................................................................................................................................. 71
SQL Constraints ................................................................................................................................. 72
SQL CREATE TABLE + CONSTRAINT Syntax .................................................................................... 72
SQL NOT NULL Constraint ................................................................................................................. 73
Example ............................................................................................................................................. 73
SQL UNIQUE Constraint..................................................................................................................... 74
SQL UNIQUE Constraint on CREATE TABLE ....................................................................................... 74
SQL UNIQUE Constraint on ALTER TABLE.......................................................................................... 75
To DROP a UNIQUE Constraint .......................................................................................................... 75
SQL PRIMARY KEY Constraint ............................................................................................................ 75
SQL PRIMARY KEY Constraint on CREATE TABLE............................................................................... 76
SQL PRIMARY KEY Constraint on ALTER TABLE ................................................................................. 77
To DROP a PRIMARY KEY Constraint ................................................................................................. 77
SQL FOREIGN KEY Constraint ............................................................................................................ 77
SQL FOREIGN KEY Constraint on CREATE TABLE ............................................................................... 78
SQL FOREIGN KEY Constraint on ALTER TABLE ................................................................................. 79
To DROP a FOREIGN KEY Constraint ................................................................................................. 79
SQL CHECK Constraint ....................................................................................................................... 80
Page 6 of 131
Page 7 of 131
Page 8 of 131
SQL FIRST() Workaround in SQL Server, MySQL and Oracle ........................................................... 111
SQL Server Syntax........................................................................................................................ 111
Example ....................................................................................................................................... 111
MySQL Syntax .............................................................................................................................. 111
Example ....................................................................................................................................... 111
Oracle Syntax............................................................................................................................... 111
Example ....................................................................................................................................... 111
Demo Database ............................................................................................................................... 111
SQL FIRST() Example ........................................................................................................................ 112
Example ........................................................................................................................................... 112
The LAST() Function......................................................................................................................... 112
SQL LAST() Syntax ........................................................................................................................ 112
SQL LAST() Workaround in SQL Server, MySQL and Oracle ............................................................ 112
SQL Server Syntax........................................................................................................................ 112
Example ....................................................................................................................................... 112
MySQL Syntax .............................................................................................................................. 112
Example ....................................................................................................................................... 112
Oracle Syntax............................................................................................................................... 113
Example ....................................................................................................................................... 113
Demo Database ............................................................................................................................... 113
SQL LAST() Example ......................................................................................................................... 113
Example ........................................................................................................................................... 113
The MAX() Function......................................................................................................................... 114
SQL MAX() Syntax ........................................................................................................................ 114
Demo Database ............................................................................................................................... 114
SQL MAX() Example ......................................................................................................................... 114
Example ........................................................................................................................................... 114
The MIN() Function ......................................................................................................................... 114
SQL MIN() Syntax......................................................................................................................... 115
Demo Database ............................................................................................................................... 115
SQL MIN() Example.......................................................................................................................... 115
Example ........................................................................................................................................... 115
The SUM() Function......................................................................................................................... 115
SQL SUM() Syntax ........................................................................................................................ 115
Demo Database ............................................................................................................................... 116
SQL SUM() Example ......................................................................................................................... 116
Page 9 of 131
Page 10 of 131
Page 11 of 131
SQL BASIC
Page 12 of 131
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
Page 13 of 131
Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!
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.
The data in RDBMS is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows.
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).
Page 14 of 131
Alfreds
Futterkiste
Ana Trujillo
2
3
4
Emparedados y
Address
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
Germany
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
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;
Try it yourself
In this tutorial we will teach you all about the different SQL statements.
Page 15 of 131
Page 16 of 131
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
1
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
Page 17 of 131
Try it yourself
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
Try it yourself
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 ADO tutorial or our PHP tutorial.
Page 18 of 131
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
1
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
05021
Mexico
05023
Mexico
Page 19 of 131
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
Lule
S-958 22
Sweden
Try it yourself
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 20 of 131
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
Try it yourself
Page 21 of 131
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;
Try it yourself
Description
Equal
Not equal. Note: In some versions of SQL this operator may be written as
!=
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
IN
Page 22 of 131
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
1
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
Page 23 of 131
Try it yourself
OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "Mnchen", in
the "Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='Mnchen';
Try it yourself
Page 24 of 131
The following SQL statement selects all customers from the country "Germany" AND the city
must be equal to "Berlin" OR "Mnchen", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='Mnchen');
Try it yourself
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Page 25 of 131
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
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;
Try it yourself
Page 26 of 131
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;
Try it yourself
Try it yourself
Page 27 of 131
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
87
88
89
90
91
Wartian Herkku
Wellington
Importadora
White Clover
Markets
Pirkko
Koskitalo
Paula Parente
Karl Jablonski
Matti
Wilman Kala
Wolski
Karttunen
Zbyszek
Address
Torikatu 38
Rua do
Mercado, 12
305 - 14th Ave.
S. Suite 3B
90110
Finland
Seattle 98128
USA
Finland
Poland
01-012
Page 28 of 131
Try it yourself
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName
87
88
89
90
91
92
Wartian Herkku
Wellington
Importadora
White Clover
Markets
Wilman Kala
Pirkko
Koskitalo
Paula Parente
Address
Torikatu 38
Rua do
Mercado, 12
City
Oulu
PostalCode Country
90110
Finland
305 - 14th
Karl Jablonski Ave. S. Suite Seattle
98128
USA
3B
Matti
Keskuskatu
Karttunen
45
Wolski
Zbyszek
Cardinal
Tom B.
ul. Filtrowa
68
Skagen 21
Helsinki 21240
Finland
Walla
Poland
01-012
Stavanger 4006
Norway
Page 29 of 131
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.
Try it yourself
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName
87
88
89
Wartian Herkku
Wellington
Importadora
White Clover
Pirkko
Koskitalo
Paula Parente
Address
Torikatu 38
Rua do
Mercado, 12
City
Oulu
PostalCode Country
90110
Finland
98128
USA
Page 30 of 131
Markets
Ave. S. Suite
3B
90
91
92
Wilman Kala
Matti
Keskuskatu
Karttunen
45
Wolski
Zbyszek
Cardinal
null
ul. Filtrowa
68
null
Helsinki 21240
Finland
Walla
Poland
01-012
Stavanger null
Norway
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 31 of 131
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
Try it yourself
The selection from the "Customers" table will now look like this:
Page 32 of 131
Alfreds
Alfred
Futterkiste
Schmidt
Ana Trujillo
2
Emparedados y
Address
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
PostalCode Country
Ana Trujillo
City
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
Germany
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
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:
CustomerID CustomerName ContactName
1
Alfreds
Alfred
Futterkiste
Schmidt
Ana Trujillo
2
Emparedados y
helados
Alfred
Schmidt
Address
City
PostalCode Country
Germany
Avda. de la
Constitucin
Hamburg 05021
Mexico
2222
Page 33 of 131
Mataderos
Taquera
Schmidt
2312
Alfred
120 Hanover
Schmidt
Sq.
Berglunds
Alfred
Berguvsvgen
snabbkp
Schmidt
Hamburg 05023
Mexico
Hamburg S-958 22
Sweden
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Page 34 of 131
Alfreds
Address
Germany
Futterkiste
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
Constitucin
Mxico
D.F.
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
05021
Mexico
05023
Mexico
Lule
S-958 22
Sweden
Try it yourself
The "Customers" table will now look like this:
CustomerID CustomerName ContactName
2
Ana Trujillo
Ana Trujillo
Address
Avda. de la
Mexico
Page 35 of 131
Emparedados y
Constitucin
helados
2222
Mataderos
Mxico
Taquera
2312
D.F.
Moreno
120 Hanover
Sq.
Berglunds
Christina
Berguvsvgen
snabbkp
Berglund
D.F.
05023
Mexico
Lule
S-958 22
Sweden
or
SQL Injection
An SQL Injection can destroy your database.
Page 36 of 131
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
statements, via web page input.
Injected SQL commands can alter SQL statement and compromises the security of a web
application.
Page 37 of 131
UserId:
105 or 1=1
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.
Password:
Server Code
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
Page 38 of 131
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
Page 39 of 131
Page 40 of 131
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.
ASP.NET SELECT
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
ASP.NET INSERT INTO
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
PHP INSERT INTO
Page 41 of 131
Page 42 of 131
SQL ADVANCED
Page 43 of 131
Example
SELECT *
FROM Persons
LIMIT 5;
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;
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
PostalCode Country
Page 44 of 131
Alfreds Futterkiste
Maria Anders
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
helados
3
4
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
Obere Str. 57
Constitucin
2222
Berlin
Mxico
D.F.
Mxico
D.F.
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT TOP 2 * FROM Customers;
Try it yourself
Example
SELECT TOP 50 PERCENT * FROM Customers;
Try it yourself
Page 45 of 131
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT * FROM Customers
WHERE City LIKE 's%';
Try it yourself
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.
Page 46 of 131
The following SQL statement selects all customers with a City ending with the letter "s":
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
Try it yourself
The following SQL statement selects all customers with a Country containing the pattern "land":
Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Try it yourself
Using the NOT keyword allows you to select records that does NOT match the pattern.
The following SQL statement selects all customers with a Country NOT containing the pattern
"land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
Try it yourself
SQL Wildcards
A wildcard character can be used to substitute for any other character(s) in a
string.
Description
Page 47 of 131
[charlist]
[^charlist]
or
[!charlist]
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
Try it yourself
The following SQL statement selects all customers with a City containing the pattern "es":
Page 48 of 131
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Try it yourself
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
Try it yourself
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';
Try it yourself
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
Try it yourself
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
Page 49 of 131
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Try it yourself
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:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
helados
3
4
Antonio Moreno
Taquera
Around the Horn
Address
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
UK
Page 50 of 131
Berglunds snabbkp
Christina
Berguvsvgen 8
Berglund
Lule
S-958 22
Sweden
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');
Try it yourself
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
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
Page 51 of 131
48 - 6 oz jars
22
36 boxes
21.35
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Try it yourself
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Try it yourself
Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
Try it yourself
Page 52 of 131
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
Try it yourself
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Try it yourself
Sample Table
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10248
90
7/4/1996
10249
81
7/5/1996
10250
34
7/8/1996
10251
84
7/9/1996
10252
76
7/10/1996
Page 53 of 131
The following SQL statement selects all orders with an OrderDate BETWEEN '04-July-1996' and '09July-1996':
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
Try it yourself
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
SQL aliases are used to temporarily rename a table or a column heading.
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.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 54 of 131
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Mxico
Constitucin
D.F.
2222
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
CustomerID
EmployeeID
OrderDate
ShipperID
10643
1997-08-25
10644
88
1997-08-25
10645
34
1997-08-26
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
Try it yourself
In the following SQL statement we combine four columns (Address, City, PostalCode, and Country)
and create an alias named "Address":
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS
Address
FROM Customers;
Try it yourself
Page 55 of 131
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Alfreds Futterkiste';
Try it yourself
The same SQL statement without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Alfreds Futterkiste';
Try it yourself
Aliases can be useful when:
SQL Joins
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.
Page 56 of 131
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
10308
CustomerID
1996-09-18
OrderDate
10309
37
1996-09-19
10310
77
1996-09-20
ContactName
Maria Anders
Country
Germany
Ana Trujillo
Mexico
Antonio Moreno
Mexico
Notice that the "CustomerID" column in the "Orders" table refers to the customer 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;
Try it yourself
it will produce something like this:
OrderID
10308
CustomerName
Ana Trujillo Emparedados y helados
OrderDate
9/18/1996
10365
11/27/1996
10383
12/16/1996
10355
11/15/1996
10278
Berglunds snabbkp
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
Page 57 of 131
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
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Address
Obere Str. 57
City
Berlin
PostalCode Country
12209
Germany
Page 58 of 131
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
helados
3
Constitucin
2222
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
Mxico
D.F.
Mxico
D.F.
05021
Mexico
05023
Mexico
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Try it yourself
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.
Page 59 of 131
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Obere Str. 57
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
City
Berlin
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
Page 60 of 131
10310
77
1996-09-20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Try it yourself
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).
Page 61 of 131
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
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
Photo
Notes
Education includes a BA in
Davolio
Nancy
12/8/1968 EmpID1.pic
Fuller
Andrew
2/19/1952 EmpID2.pic
Leverling
Janet
psychology.....
Andrew received his BTS commercial
and....
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
Page 62 of 131
Try it yourself
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).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
helados
Address
Obere Str. 57
Avda. de la
Ana Trujillo
Constitucin
2222
City
Berlin
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
Page 63 of 131
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
Mxico
D.F.
05023
Mexico
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados
10308
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:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Obere Str. 57
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
City
Berlin
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Page 65 of 131
SupplierID
1
SupplierName
Exotic Liquid
New Orleans Cajun
Delights
Grandma Kelly's
Homestead
ContactName
Address
Charlotte
49 Gilbert
Cooper
St.
Shelley Burke
Regina Murphy
City
Londona
EC1 4SD
UK
70117
USA
USA
P.O. Box
New
78934
Orleans
707 Oxford
Rd.
PostalCode Country
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Try it yourself
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!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Try it yourself
Page 66 of 131
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Try it yourself
Page 67 of 131
Tip: The new table will be created with the column-names and types as defined in the
SELECT statement. You can apply new names using the AS clause.
Page 68 of 131
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Obere Str. 57
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Antonio Moreno
Antonio
Taquera
Moreno
Mataderos 2312
City
Berlin
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Page 69 of 131
SupplierID
SupplierName
Exotic Liquid
New Orleans Cajun
Delights
Grandma Kelly's
Homestead
ContactName Address
Charlotte
49 Gilbert
Cooper
St.
Shelley Burke
Regina Murphy
City
P.O. Box
New
78934
Orleans
Postal
Country
Code
Arbor
70117
USA
48104
USA
Phone
(171)
555-2222
(100)
555-4822
(313)
555-5735
Example
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;
Try it yourself
Copy only the German suppliers into "Customers":
Example
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
Try it yourself
Page 70 of 131
Example
Page 71 of 131
LastName
FirstName
Address
City
Tip: The empty table can be filled with data with the INSERT INTO statement.
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).
Page 72 of 131
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
DEFAULT - Specifies a default value when specified none for this column
Example
CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Try it yourself
Page 74 of 131
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
Page 75 of 131
Page 76 of 131
Page 77 of 131
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
OrderNo
P_Id
77895
44678
22456
24562
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
Page 78 of 131
Page 79 of 131
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders
SQL Server / Oracle / MS Access:
ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders
Page 80 of 131
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')
)
Page 81 of 131
Page 82 of 131
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.
Page 83 of 131
Page 84 of 131
Page 85 of 131
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
My SQL / Oracle:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
DateOfBirth
Page 86 of 131
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Page 87 of 131
Very often we would like the value of the primary key field to be created automatically every time a
new record is inserted.
We would like to create an auto-increment field in a table.
Page 88 of 131
Page 89 of 131
SQL Views
A view is a virtual table.
This chapter shows how to create, update, and delete a view.
Page 91 of 131
Page 92 of 131
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.
Description
NOW()
CURDATE()
CURTIME()
DATE()
EXTRACT()
DATE_ADD()
DATE_SUB()
DATEDIFF()
DATE_FORMAT()
Description
GETDATE()
DATEPART()
DATEADD()
DATEDIFF()
Page 93 of 131
CONVERT()
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
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.
ProductName
OrderDate
Geitost
2008-11-11
Camembert Pierrot
2008-11-09
Mozzarella di Giovanni
2008-11-11
Mascarpone Fabioli
2008-10-29
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
We use the following SELECT statement:
Page 94 of 131
ProductName
OrderDate
Geitost
2008-11-11
Mozzarella di Giovanni
2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
OrderId
ProductName
OrderDate
Geitost
2008-11-11 13:23:44
Camembert Pierrot
2008-11-09 15:45:21
Mozzarella di Giovanni
2008-11-11 11:12:01
Mascarpone Fabioli
2008-10-29 14:56:59
Page 95 of 131
LastName
Hansen
FirstName
Ola
Address
City
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Stavanger
Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a
record with no value for the "Address" column, the "Address" column will be saved with a NULL
value.
How can we test for NULL values?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
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
The result-set will look like this:
LastName
Hansen
FirstName
Ola
Pettersen
Kari
Address
Page 96 of 131
FirstName
Tove
Address
Borgvn 23
In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.
ProductName
Jarlsberg
UnitPrice
10.45
UnitsInStock
16
Mascarpone
32.56
23
Gorgonzola
15.67
UnitsOnOrder
15
20
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
We have the following SELECT statement:
SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products
In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL.
Microsoft's ISNULL() function is used to specify how we want to treat NULL values.
The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
In this case we want NULL values to be zero.
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if
the value is NULL:
Page 97 of 131
Description
Character string. Fixed-length n
VARCHAR(n) or
CHARACTER
VARYING(n)
BINARY(n)
Page 98 of 131
BOOLEAN
VARBINARY(n) or
BINARY VARYING(n)
INTEGER(p)
SMALLINT
INTEGER
BIGINT
DECIMAL(p,s)
that has 3 digits before the decimal and 2 digits after the decimal
NUMERIC(p,s)
FLOAT(p)
REAL
FLOAT
DOUBLE PRECISION
DATE
TIME
TIMESTAMP
INTERVAL
ARRAY
MULTISET
XML
Access
Yes/No
Number
(integer)
Bit
SQLServer
Oracle
Byte
Int
Number
Float
MySQL
N/A
PostgreSQL
Boolean
Int
Int
Integer
Integer
Number
Float
Numeric
float
Number (single)
currency
Currency
Money
N/A
N/A
Money
string (fixed)
N/A
Char
Char
Char
Char
Varchar
Varchar
string (variable)
Text (<256)
Memo (65k+)
Real
Varchar
Varchar
Varchar2
Page 99 of 131
Binary (fixed up to
binary object
OLE Object
8K)
Long
Blob
Binary
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!
Description
Use for text or combinations of text and numbers. 255 characters
Storage
maximum
Memo is used for larger amounts of text. Stores up to 65,536
Memo
characters. Note: You cannot sort a memo field. However, they are
searchable
Byte
1 byte
Integer
2 bytes
Long
4 bytes
Single
4 bytes
Double
8 bytes
Currency
AutoNumber
Date/Time
8 bytes
4 bytes
8 bytes
code, use the constants True and False (equivalent to -1 and 0).
1 bit
up to
OBjects)
1GB
4 bytes
Description
Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255
characters
Holds a variable length string (can contain letters, numbers, and special
VARCHAR(size)
TINYTEXT
TEXT
BLOB
MEDIUMTEXT
MEDIUMBLOB
LONGTEXT
LONGBLOB
ENUM(x,y,z,etc.)
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 store
SET
Number types:
Data type
TINYINT(size)
SMALLINT(size)
MEDIUMINT(size)
INT(size)
BIGINT(size)
Description
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of
digits may be specified in parenthesis
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
-9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
A small number with a floating decimal point. The maximum number of digits
FLOAT(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 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
DECIMAL(size,d)
*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'
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS
DATETIME()
TIMESTAMP()
HH:MM: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:MM: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()
*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 YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD,
or YYMMDD.
Description
Fixed width character string. Maximum 8,000 characters
varchar(n)
varchar(max)
2 bytes + number
of chars
2 bytes + number
characters
of chars
text
nchar
nvarchar
nvarchar(max)
Storage
Defined width
4 bytes + number
of chars
Defined width x 2
ntext
bit
Allows 0, 1, or NULL
binary(n)
varbinary
varbinary(max)
image
Number types:
Data type
tinyint
Description
Allows whole numbers from 0 to 255
Storage
1 byte
smallint
2 bytes
int
4 bytes
bigint
8 bytes
can be stored (both to the left and to the right of the decimal point).
p must be a value from 1 to 38. Default is 18.
5-17
bytes
5-17
bytes
4 bytes
8 bytes
922,337,203,685,477.5807
Floating precision number data from -1.79E + 308 to 1.79E + 308.
float(n)
4 or 8
bytes
4 bytes
Description
From January 1, 1753 to December 31, 9999 with an accuracy of
Storage
Date types:
Data type
datetime
datetime2
3.33 milliseconds
From January 1, 0001 to December 31, 9999 with an accuracy of 100
nanoseconds
8 bytes
6-8 bytes
smalldatetime
4 bytes
date
3 bytes
time
3-5 bytes
datetimeoffset
8-10
bytes
Stores a unique number that gets updated every time a row gets
timestamp
Description
Stores up to 8,000 bytes of data of various data types, except text, ntext, and
timestamp
uniqueidentifier
xml
cursor
table
SQL FUNCTION
SQL Functions
SQL has many built-in functions for performing calculations on data.
Tip: The aggregate functions and the scalar functions will be explained in details in the next
chapters.
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
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT AVG(Price) AS PriceAverage FROM Products;
Try it yourself
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);
Try it yourself
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
1996-07-25
10266
87
1996-07-26
10267
25
1996-07-29
The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders"
table:
Example
SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7;
Try it yourself
Example
SELECT COUNT(*) AS NumberOfOrders FROM Orders;
Try it yourself
Example
SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;
Try it yourself
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID ASC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
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:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
helados
3
4
Antonio Moreno
Taquera
Around the Horn
Address
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
UK
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958 22
Sweden
Example
SELECT FIRST(CustomerName) AS FirstCustomer FROM Customers;
Try it yourself
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:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT LAST(CustomerName) AS LastCustomer FROM Customers;
Try it yourself
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
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT MAX(Price) AS HighestPrice FROM Products;
Try it yourself
The MIN() function returns the smallest value of the selected column.
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
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT MIN(Price) AS SmallestOrderPrice FROM Products;
Try it yourself
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
10248
11
12
10248
42
10
10248
72
10249
14
10249
51
40
Example
SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
Try it yourself
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
1996-07-04
10249
81
1996-07-05
10250
34
1996-07-08
ShipperName
Phone
Speedy Express
(503) 555-9831
United Package
(503) 555-3199
Federal Shipping
(503) 555-9931
BirthDate
Photo
Notes
Davolio
Nancy
Fuller
Andrew
Leverling
Janet
Example
Example
SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;
Try it yourself
Demo Database
In this tutorial we will use the well-known Northwind sample database.
CustomerID
EmployeeID
OrderDate
ShipperID
10248
90
1996-07-04
10249
81
1996-07-05
10250
34
1996-07-08
BirthDate
Photo
Notes
Davolio
Nancy
Fuller
Andrew
Leverling
Janet
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;
Try it yourself
Now we want to find the if the employees "Davolio" or "Fuller" have 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
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table, and converts the "CustomerName" column to uppercase:
Example
SELECT UCASE(CustomerName) AS Customer, City
FROM Customers;
Try it yourself
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Ana Trujillo
2
Emparedados y
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
City
Obere Str. 57
Berlin
Avda. de la
Ana Trujillo
helados
3
Address
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
PostalCode Country
12209
Germany
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT LCASE(CustomerName) AS Customer, City
FROM Customers;
Try it yourself
Parameter
Description
column_name
start
length
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
2
CustomerName
ContactName
Address
City
PostalCode Country
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
Ana Trujillo
Ana Trujillo
Avda. de la
Mxico 05021
Emparedados y
Constitucin
12209
Germany
Mexico
helados
3
4
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
2222
Antonio Moreno Mataderos 2312
D.F.
Mxico
D.F.
05023
Berguvsvgen 8
Lule
S-958 22
Mexico
UK
Sweden
Example
SELECT MID(City,1,4) AS ShortCity
FROM Customers;
Try it yourself
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
1
CustomerName
Alfreds Futterkiste
ContactName
Maria Anders
Address
City
Obere Str. 57
Berlin
PostalCode Country
12209
Germany
Ana Trujillo
2
Emparedados y
Avda. de la
Ana Trujillo
helados
3
4
Antonio Moreno
Taquera
Around the Horn
Berglunds snabbkp
Constitucin
2222
Mxico
D.F.
Mxico
D.F.
05021
Mexico
05023
Mexico
Berguvsvgen 8
Lule
S-958 22
UK
Sweden
Example
SELECT CustomerName,LEN(Address) as LengthOfAddress
FROM Customers;
Try it yourself
Parameter
Description
column_name
decimals
Demo Database
ProductName
SupplierID CategoryID
Unit
Price
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT ProductName, ROUND(Price,0) AS RoundedPrice
FROM Products;
Try it yourself
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
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT ProductName, Price, Now() AS PerDate
FROM Products;
Try it yourself
Parameter
Description
column_name
format
Demo Database
In this tutorial we will use the well-known Northwind sample database.
ProductName
SupplierID CategoryID
Unit
Price
Chais
10 boxes x 20 bags 18
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
21.35
36 boxes
25
Example
SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate
FROM Products;
Try it yourself
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE
AS (alias)
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE
CREATE TABLE
CREATE INDEX
CREATE VIEW
DELETE
WHERE some_column=some_value
or
DELETE FROM table_name
(Note: Deletes the entire table!!)
DELETE * FROM table_name
(Note: Deletes the entire table!!)
DROP DATABASE
DROP INDEX
DROP TABLE
GROUP BY
HAVING
IN
SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO
INNER JOIN
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LEFT JOIN
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
RIGHT JOIN
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FULL JOIN
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT
SELECT column_name(s)
FROM table_name
SELECT *
SELECT *
FROM table_name
SELECT DISTINCT
SELECT INTO
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP
TRUNCATE TABLE
UNION
UNION ALL
UPDATE
UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Source : http://www.w3schools.com/sql/sql_quickref.asp
SQL Hosting
SQL Hosting
If you want your web site to be able to store and display data from a database, your web server
should have access to a database system that uses the SQL language.
If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for
SQL hosting plans.
The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access.
You can have SQL databases on both Windows and Linux/UNIX operating systems.
Below is an overview of which database system that runs on which OS.
MS SQL Server
Runs only on Windows OS.
MySQL
Runs on Windows, Mac OS X, and Linux/UNIX operating systems.
MS Access (recommended only for small websites)
Runs only on Windows OS.
To learn more about web hosting, please visit our Hosting tutorial.