Introduction To
Introduction To
SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987
However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Example
SELECT * FROM Customers;
Try it Yourself »
Every table is broken up into smaller entities called fields. The fields in the
Customers table consist of CustomerID, CustomerName, ContactName,
Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For
example, there are 91 records in the above Customers table. A record is a
horizontal entity in a table.
SQL Syntax
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).
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp 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;
Try it Yourself »
RUN SQL
In this tutorial we will teach you all about the different SQL statements.
SQL SELECT Statement
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select
data from. If you want to select all the fields available in the table, use the
following syntax:
SELECT * FROM table_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT CustomerName, City FROM Customers;
Try it Yourself »
SELECT * Example
The following SQL statement selects all the columns from the "Customers"
table:
Example
SELECT * FROM Customers;
Try it Yourself »
RUN SQL
SQL SELECT DISTINCT Statement
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different)
values.
Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Try it Yourself »
Example
SELECT DISTINCT Country FROM Customers;
Try it Yourself »
RUN SQL
The following SQL statement lists the number of different (distinct) customer
countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Try it Yourself »
Try it Yourself »
SQL WHERE Clause
The SQL WHERE Clause
The WHERE clause is used to filter records.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Try it Yourself »
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Try it Yourself »
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
= Equal Try it
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
CustomerI CustomerNa ContactName Address City PostalCod Country
D me e
75 Split Rail Beer Art P.O. Box 555 Lander 82520 USA
& Ale Braunschweig
er
AND Example
The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
Try it Yourself »
OR Example
The following SQL statement selects all fields from "Customers" where city is
"Berlin" OR "München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
Try it Yourself »
The following SQL statement selects all fields from "Customers" where country
is "Germany" OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
Try it Yourself »
NOT Example
The following SQL statement selects all fields from "Customers" where country
is NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
Try it Yourself »
The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city must be "Berlin" OR "München" (use parenthesis to form
complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Try it Yourself »
The following SQL statement selects all fields from "Customers" where country
is NOT "Germany" and NOT "USA":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
Try it Yourself »
SQL ORDER BY Keyword
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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 »
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Try it Yourself »
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Try it Yourself »
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Try it Yourself »
SQL INSERT INTO Statement
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order of
the values is in the same order as the columns in the table. Here, the INSERT
INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
Try it Yourself »
The selection from the "Customers" table will now look like this:
89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B
Did you notice that we did not insert any number into the CustomerID
field?
The CustomerID column is an auto-increment field and will be generated
automatically when a new record is inserted into the table.
The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
Try it Yourself »
The selection from the "Customers" table will now look like this:
89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B
SQL NULL Values
What is a NULL Value?
A field with a NULL value is a field with no value.
Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during record
creation!
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
CustomerID CustomerName ContactName Address City PostalCod Country
e
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Try it Yourself »
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Try it Yourself »
SQL UPDATE Statement
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
Try it Yourself »
The selection from the "Customers" table will now look like this:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund
The following SQL statement will update the ContactName to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
Try it Yourself »
The selection from the "Customers" table will now look like this:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will
be updated!
Example
UPDATE Customers
SET ContactName='Juan';
Try it Yourself »
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
SQL DELETE Statement
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Try it Yourself »
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without
deleting the table:
Example
DELETE FROM Customers;
Try it Yourself »
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT TOP 3 * FROM Customers;
Try it Yourself »
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
LIMIT 3;
Try it Yourself »
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the records from the
"Customers" table (for SQL Server/MS Access):
Example
SELECT TOP 50 PERCENT * FROM Customers;
Try it Yourself »
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
Try it Yourself »
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
Try it Yourself »
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
Try it Yourself »
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
Try it Yourself »
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
2 Chang 1 1 24 - 12 oz bottles 19
Example
SELECT COUNT(ProductID)
FROM Products;
Try it Yourself »
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Try it Yourself »
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
Try it Yourself »
SQL LIKE Operator
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a
question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
LIKE Operator Description
WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 2
'a_%' characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3
'a__%' characters in length
WHERE ContactName LIKE 'a Finds any values that start with "a" and ends with "o"
%o'
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
45 Let's Stop N Jaime Yorres 87 Polk St. Suite San 94117 USA
Shop 5 Francisco
51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent
55 Old World Rene Phillips 2743 Bering St. Anchorage 99508 USA
Delicatessen
62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891
75 Split Rail Beer & Art P.O. Box 555 Lander 82520 USA
Ale Braunschweiger
78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.
89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName ending
with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that
have "or" in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that
have "r" in the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that
starts with "a" and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Try it Yourself »
The following SQL statement selects all customers with a ContactName that
starts with "a" and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that
does NOT start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
Try it Yourself »
SQL Wildcards
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.
* Represents zero or more characters bl* finds bl, black, blue, and blob
[] Represents any single character h[oa]t finds hot and hat, but not hit
within the brackets
! Represents any character not in the h[!oa]t finds hit, but not hot and hat
brackets
% Represents zero or more characters bl% finds bl, black, blue, and
blob
[] Represents any single character within the h[oa]t finds hot and hat, but
brackets not hit
^ Represents any character not in the h[^oa]t finds hit, but not hot
brackets and hat
- Represents any single character within the c[a-b]t finds cat and cbt
specified range
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
WHERE CustomerName LIKE Finds any values that ends with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a__%' characters in length
WHERE ContactName LIKE 'a Finds any values that starts with "a" and ends with "o"
%o'
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent
55 Old World Rene Phillips 2743 Bering St. Anchorage 99508 USA
Delicatessen
62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891
89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B
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":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Try it Yourself »
Using the _ Wildcard
The following SQL statement selects all customers with a City starting with any
character, followed by "ondon":
Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';
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 »
Using the [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]%';
Try it Yourself »
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]%';
Try it Yourself »
Using the [!charlist] Wildcard
The two following SQL statements select all customers with a City NOT starting
with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Try it Yourself »
Or:
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
Try it Yourself »
SQL IN Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
7 Blondel père et fils Frédérique 24, place Kléber Strasbo 67000 Franc
Citeaux urg e
9 Bon app' Laurence 12, rue des Bouchers Marseill 13008 Franc
Lebihans e e
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São 05432-043 Brazil
Paulo
18 Du monde entier Janine 67, rue des Cinquante Nantes 44000 Franc
Labrune Otages e
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
32 Great Lakes Food Howard 2732 Baker Blvd. Eugene 97403 USA
Market Snyder
36 Hungry Coyote Yoshi Latimer City Center Plaza 516 Elgin 97827 USA
Import Store Main St.
38 Island Trading Helen Bennett Garden House Crowther Cowes PO31 7PJ UK
Way
42 Laughing Bacchus Yoshi 1900 Oak St. Vancou V3F 2K1 Cana
Wine Cellars Tannamuri ver da
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San 94117 USA
Francisc
o
46 LILA-Supermercado Carlos Carrera 52 con Ave. Barquisi 3508 Vene
González Bolívar #65-98 Llano meto zuela
Largo
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montré H1J 1C3 Cana
al da
55 Old World Rene Phillips 2743 Bering St. Anchor 99508 USA
Delicatessen age
58 Pericles Comidas Guillermo Calle Dr. Jorge Cash 321 México 05033 Mexi
clásicas Fernández D.F. co
64 Rancho grande Sergio Av. del Libertador 900 Buenos 1010 Arge
Gutiérrez Aires ntina
65 Rattlesnake Canyon Paula Wilson 2817 Milton Dr. Albuqu 87110 USA
Grocery erque
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
75 Split Rail Beer & Ale Art P.O. Box 555 Lander 82520 USA
Braunschweig
er
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portlan 97201 USA
d
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgar 70563 Germ
t any
89 White Clover Karl Jablonski 305 - 14th Ave. S. Suite Seattle 98128 USA
Markets 3B
IN Operator Examples
The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Try it Yourself »
The following SQL statement selects all customers that are NOT located in
"Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
Try it Yourself »
The following SQL statement selects all customers that are from the same
countries as the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
SQL BETWEEN Operator
The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
2 Chang 1 1 24 - 12 oz bottles 19
BETWEEN Example
The following SQL statement selects all products with a price between 10 and
20:
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 CategoryID NOT IN (1,2,3);
Try it Yourself »
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Try it Yourself »
The following SQL statement selects all products with a ProductName between
Carnarvon Tigers and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;
Try it Yourself »
NOT BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName not
between Carnarvon Tigers and Mozzarella di Giovanni:
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
Try it Yourself »
Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:
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
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
Try it Yourself »
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
Try it Yourself »
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
10354 58 8 1996-11-14 3
10355 4 6 1996-11-15 1
10356 86 6 1996-11-18 2
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Try it Yourself »
The following SQL statement creates two aliases, one for the CustomerName
column and one for the ContactName column. Note: It requires double
quotation marks or square brackets if the alias name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
Try it Yourself »
The following SQL statement creates an alias named "Address" that combine
four columns (Address, PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers;
Try it Yourself »
Note: To get the SQL statement above to work in MySQL use the following:
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
Try it Yourself »
The following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;
Try it Yourself »
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
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, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Try it Yourself »
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
SQL INNER JOIN Keyword
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both
tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
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 records in the "Orders" table that
do not have matches in "Customers", these orders will not be shown!
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
SQL LEFT JOIN Keyword
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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 records from the left table (Customers),
even if there are no matches in the right table (Orders).
SQL RIGHT JOIN Keyword
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the
left side, if there is no match.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Try it Yourself »
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
CustomerName OrderID
SQL Self Join
SQL Self Join
A self join is a regular join, but the table is joined with itself.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
SQL UNION Operator
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or
more SELECT statements.
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column
names in the first SELECT statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
2 New Orleans Cajun Shelley Burke P.O. Box New 70117 USA
Delights 78934 Orleans
3 Grandma Kelly's Regina Murphy 707 Oxford Ann Arbor 48104 USA
Homestead Rd.
Try it Yourself »
Note: If some customers or suppliers have the same city, each city will only be
listed once, because 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 »
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Try it Yourself »
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 »
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Try it Yourself »
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table
or a column a temporary name. An alias only exists for the duration of the
query. So, here we have created a temporary column named "Type", that list
whether the contact person is a "Customer" or a "Supplier".
SQL GROUP BY Statement
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Try it Yourself »
The following SQL statement lists the number of customers in each country,
sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Try it Yourself »
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
Try it Yourself »
SQL HAVING Clause
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Try it Yourself »
The following SQL statement lists the number of customers in each country,
sorted high to low (Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Try it Yourself »
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
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 »
The following SQL statement lists if the employees "Davolio" or "Fuller" have
registered more than 25 orders:
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;
Try it Yourself »
SQL EXISTS Operator
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
ProductID ProductName SupplierID CategoryID Unit Price
2 Chang 1 1 24 - 12 oz bottles 19
2 New Orleans Cajun Shelley Burke P.O. Box 78934 New 70117 USA
Delights Orleans
3 Grandma Kelly's Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
Homestead
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID
= Suppliers.supplierID AND Price < 20);
Try it Yourself »
The following SQL statement returns TRUE and lists the suppliers with a product
price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID
= Suppliers.supplierID AND Price = 22);
ANY means that the condition will be true if the operation is true for any of the
values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
ALL means that the condition will be true only if the operation is true for all
values in the range.
2 Chang 1 1 24 - 12 oz bottles 19
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
7 10250 51 35
8 10250 65 15
9 10251 22 6
10 10251 57 15
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
Try it Yourself »
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 99 (this will return TRUE because
the Quantity column has some values larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
Try it Yourself »
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 1000 (this will return FALSE
because the Quantity column has no values larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
Try it Yourself »
Try it Yourself »
The following SQL statement lists the ProductName if ALL the records in the
OrderDetails table has Quantity equal to 10. This will of course return FALSE
because the Quantity column has many different values (not only the value of
10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
Try it Yourself »
SQL SELECT INTO Statement
The SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in
the old table. You can create new column names using the AS clause.
SELECT * INTO CustomersBackup2017
FROM Customers;
The following SQL statement uses the IN clause to copy the table into a new
table in another database:
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;
The following SQL statement copies only a few columns into a new table:
SELECT CustomerName, ContactName INTO CustomersBackup2017
FROM Customers;
The following SQL statement copies only the German customers into a new
table:
SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = 'Germany';
The following SQL statement copies data from more than one table into a new
table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Tip: SELECT INTO 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 oldtable
WHERE 1 = 0;
SQL INSERT INTO
SELECT Statement
The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data from one table and inserts it into
another table.
The INSERT INTO SELECT statement requires that the data types in source and
target tables matches.
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
Demo Database
In this tutorial we will use the well-known Northwind sample database.
2 New Orleans Cajun Shelley Burke P.O. Box New 70117 USA
Delights 78934 Orleans
3 Grandma Kelly's Regina Murphy 707 Oxford Ann Arbor 48104 USA
Homestead Rd.
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
Try it Yourself »
The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
SELECT SupplierName, ContactName, Address, City,
PostalCode, Country FROM Suppliers;
Try it Yourself »
The following SQL statement copies only the German suppliers into
"Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
Try it Yourself »
SQL CASE Statement
The SQL CASE Statement
The CASE statement goes through conditions and returns a value when the first
condition is met (like an if-then-else statement). So, once a condition is true, it
will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
SQL CASE Examples
The following SQL goes through conditions and returns a value when the first
condition is met:
Example
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
Try it Yourself »
The following SQL will order the customers by City. However, if City is NULL,
then order by Country:
Example
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
SQL NULL Functions
SQL IFNULL(), ISNULL(), COALESCE(), and
NVL() Functions
Look at the following "Products" table:
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL
values.
In the example above, if any of the "UnitsOnOrder" values are NULL, the result
will be NULL.
Solutions
MySQL
SQL Server
MS Access
Oracle
The Oracle NVL() function achieves the same result:
So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Example
EXEC SelectAllCustomers;
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Example
EXEC SelectAllCustomers @City = 'London';
The following SQL statement creates a stored procedure that selects Customers
from a particular City with a particular PostalCode from the "Customers" table:
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
Example
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';
SQL Comments
SQL Comments
Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
Note: The examples in this chapter will not work in Firefox and
Microsoft Edge!
Any text between -- and the end of the line will be ignored (will not be
executed).
Example
--Select all:
SELECT * FROM Customers;
Try it Yourself »
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
Try it Yourself »
Try it Yourself »
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Try it Yourself »
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Try it Yourself »
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
Try it Yourself »
The following example uses a comment to ignore part of a statement:
Example
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;
SQL Operators
SQL Arithmetic Operators
+ Add Try it
- Subtract Try it
* Multiply Try it
/ Divide Try it
% Modulo Try it
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
= Equal to Try it
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
ALL TRUE if all of the subquery values meet the condition Try it
AND TRUE if all the conditions separated by AND is TRUE Try it
ANY TRUE if any of the subquery values meet the condition Try it
SOME TRUE if any of the subquery values meet the condition Try it
SQL CREATE
DATABASE Statement
The SQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
CREATE DATABASE Example
The following SQL statement creates a database called "testDB":
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
SQL DROP DATABASE Statement
The SQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax
DROP DATABASE databasename;
Example
DROP DATABASE testDB;
Tip: Make sure you have admin privilege before dropping any database. Once a
database is dropped, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
SQL BACKUP DATABASE for SQL
Server
The SQL BACKUP DATABASE Statement
The BACKUP DATABASE statement is used in SQL Server to create a full back up of
an existing SQL database.
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Tip: Always back up the database to a different drive than the actual database.
Then, if you get a disk crash, you will not lose your backup file along with the
database.
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are
backed up).
SQL CREATE TABLE Statement
The SQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Try it Yourself »
The LastName, FirstName, Address, and City columns are of type varchar and
will hold characters, and the maximum length for these fields is 255 characters.
Tip: The empty "Persons" table can now be filled with data with the
SQL INSERT INTO statement.
The new table gets the same column definitions. All columns or specific columns
can be selected.
If you create a new table using an existing table, the new table will be filled
with the existing values from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of
the "Customers" table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
Try it Yourself »
SQL DROP TABLE Statement
The SQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of
complete information stored in the table!
Example
DROP TABLE Shippers;
Try it Yourself »
Syntax
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
ALTER TABLE table_name
ADD column_name datatype;
Example
ALTER TABLE Customers
ADD Email varchar(255);
Try it Yourself »
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
Try it Yourself »
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
ALTER TABLE table_name
MODIFY column_name datatype;
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.
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a
year in a two- or four-digit format.
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
SQL NOT NULL Constraint
SQL NOT NULL Constraint
By default, a column can hold NULL values.
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
Try it Yourself »
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created, use the following SQL:
ALTER TABLE Persons
MODIFY Age int NOT NULL;
SQL UNIQUE Constraint
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
ALTER TABLE Persons
ADD UNIQUE (ID);
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
DROP INDEX UC_Person;
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
SQL PRIMARY KEY Constraint
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
Note: If you use ALTER TABLE to add a primary key, the primary key column(s)
must have been declared to not contain NULL values (when the table was first
created).
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY;
ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
SQL FOREIGN KEY Constraint
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Look at the following two tables:
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the
parent table.
MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
SQL CHECK Constraint
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a column it will allow only certain values for
this column.
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
ALTER TABLE Persons
ADD CHECK (Age>=18);
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;
MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
SQL DEFAULT Constraint
SQL DEFAULT Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';
SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;
MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';
Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
SQL CREATE INDEX Statement
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database more quickly than
otherwise. 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, only create indexes on
columns that will be frequently searched against.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
CREATE INDEX idx_lastname
ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);
MS Access:
DROP INDEX index_name ON table_name;
SQL Server:
DROP INDEX table_name.index_name;
DB2/Oracle:
DROP INDEX index_name;
MySQL:
ALTER TABLE table_name
DROP INDEX index_name;
SQL AUTO INCREMENT Field
AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a
new record is inserted into a table.
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
ALTER TABLE Persons AUTO_INCREMENT=100;
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" 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 "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
In the example above, the starting value for IDENTITY is 1, and it will increment
by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and
increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" 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 "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
Syntax for Access
The following SQL statement defines the "Personid" column to be an auto-
increment primary key field in the "Persons" table:
CREATE TABLE Persons (
Personid AUTOINCREMENT PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Tip: To specify that the "Personid" 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 "Personid" 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 "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
You will have to create an auto-increment field with the sequence object (this
object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
The code above creates a sequence object called seq_person, that starts with 1
and will increment by 1. It will also cache up to 10 values for performance. The
cache option specifies how many sequence values will be stored in memory for
faster access.
To insert a new record into the "Persons" table, we will have to use the nextval
function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (Personid,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned the next number from the seq_person
sequence. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".
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 more complicated.
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!
Orders Table
1 Geitost 2008-11-11
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
1 Geitost 2008-11-11
Now, assume that the "Orders" table looks like this (notice the added time-
component in the "OrderDate" column):
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
we will get no result! This is because the query is looking only for dates with no
time portion.
Tip: To keep your queries simple and easy to maintain, do not use time-
components in your dates, unless you have to!
SQL Views
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 statements and functions to a view and present the data as if
the data were coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates the
view, every time a user queries it.
SQL CREATE VIEW Examples
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Try it Yourself »
Example
SELECT * FROM [Brazil Customers];
Try it Yourself »
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Try it Yourself »
Example
SELECT * FROM [Products Above Average Price];
Try it Yourself »
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Try it Yourself »
Example
DROP VIEW [Brazil Customers];
Try it Yourself »
SQL Injection
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is the placement of malicious code in SQL statements, via web
page input.
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user input in
SQL statements.
If there is nothing to prevent a user from entering "wrong" input, the user can
enter some "smart" input like this:
105 OR 1=1
UserId:
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
The SQL above is valid and will return ALL rows from the "Users" table,
since OR 1=1 is always TRUE.
Does the example above look dangerous? What if the "Users" table contains
names and passwords?
A hacker might get access to all the user names and passwords in a database,
by simply inserting 105 OR 1=1 into the input field.
Username:
John Doe
Password:
myPass
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
User Name:
Password:
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR
""="" is always TRUE.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
105; DROP
User id:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
SQL parameters are values that are added to an SQL query at execution time,
in a controlled manner.
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);
Examples
The following examples shows how to build parameterized queries in some
common web languages.
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserId);
command.ExecuteReader();
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();
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.
MS Access
When a web site requires only a simple database, Microsoft Access can be a
solution.
MS Access is not well suited for very high-traffic, and not as powerful as MySQL,
SQL Server, or Oracle.
An SQL developer must decide what type of data that will be stored inside each
column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
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!
CHAR(size) A FIXED length string (can contain letters, numbers, and special characters).
The size parameter specifies the column length in characters - can be from 0 to
255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters).
The size parameter specifies the maximum column length in characters - can be
from 0 to 65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the
column length in bytes. Default is 1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies
the maximum column length in bytes.
TINYBLOB For BLOBs (Binary Large Objects). Max length: 255 bytes
BLOB(size) For BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large Objects). Holds up to 16,777,215 bytes of data
LONGBLOB For BLOBs (Binary Large Objects). Holds up to 4,294,967,295 bytes of data
ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of possible
values. You can list up to 65535 values in an ENUM list. If a value is inserted
that is not in the list, a blank value will be inserted. The values are sorted in the
order you enter them
SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of possible
values. You can list up to 64 values in a SET list
Numeric Data Types
BIT(size) A bit-value type. The number of bits per value is specified in size.
The size parameter can hold a value from 1 to 64. The default value for size is
1.
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from
0 to 255. The size parameter specifies the maximum display width (which is
255)
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from
0 to 65535. The size parameter specifies the maximum display width (which is
255)
FLOAT(size, d) A floating point number. The total number of digits is specified in size. The
number of digits after the decimal point is specified in the d parameter. This
syntax is deprecated in MySQL 8.0.17, and it will be removed in future MySQL
versions
FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use
FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data
type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()
DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified
in size. The number of digits after the decimal point is specified in
the d parameter
DOUBLE PRECISION(size, d)
DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d parameter.
The maximum number for size is 65. The maximum number for d is 30. The
default value for size is 10. The default value for d is 0.
5-17 bytes
decimal(p,s) Fixed precision and scale numbers.
The p parameter indicates the maximum total number of digits that 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.
The p parameter indicates the maximum total number of digits that 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.
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8 bytes
nanoseconds
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
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes
timestamp Stores a unique number that gets updated every time a row gets created or
modified. The timestamp value is based upon an internal clock and does not
correspond to real time. Each table may have only one timestamp variable
sql_variant Stores up to 8,000 bytes of data of various data types, except text,
ntext, and timestamp
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal 8 bytes
places. Tip: You can choose which country's currency to use
AutoNumber AutoNumber fields automatically give each record its own number, usually 4 bytes
starting at 1
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large Objects) up to 1GB
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down list 4 bytes
SQL Keywords
Keyword Description
FULL OUTER JOIN Returns all rows when there is a match in either left
table or right table
INNER JOIN Returns rows that have matching values in both tables
INSERT INTO SELECT Copies data from one table into another table
LEFT JOIN Returns all rows from the left table, and the matching
rows from the right table
OUTER JOIN Returns all rows when there is a match in either left
table or right table
RIGHT JOIN Returns all rows from the right table, and the
matching rows from the left table
SELECT INTO Copies data from one table into a new table
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
MySQL Functions
MySQL has many built-in functions.
This reference contains string, numeric, date, and some advanced functions
in MySQL.
MySQL String Functions
Function Description
Function Description
Function Description
LAST_DAY Extracts the last day of the month for a given date
QUARTER Returns the quarter of the year for a given date value
Function Description
CASE Goes through conditions and return a value when the first
condition is met
CURRENT_USER Returns the user name and host name for the MySQL account
that the server used to authenticate the current client
LAST_INSERT_ID Returns the AUTO_INCREMENT id of the last row that has been
inserted or updated in a table
NULLIF Compares two expressions and returns NULL if they are equal.
Otherwise, the first expression is returned
SESSION_USER Returns the current MySQL user name and host name
SYSTEM_USER Returns the current MySQL user name and host name
USER Returns the current MySQL user name and host name
SQL Server Functions
SQL Server has many built-in functions.
Function Description
STUFF Deletes a part of a string and then inserts another part into the
string, starting at a specified position
UNICODE Returns the Unicode value for the first character of the input
expression
Function Description
Function Description
DATEADD Adds a time/date interval to a date and then returns the date
DATEFROMPARTS Returns a date from the specified parts (year, month, and
day values)
GETUTCDATE Returns the current database system UTC date and time
MONTH Returns the month part for a specified date (a number from
1 to 12)
Function Description
CAST Converts a value (of any type) into a specified datatype
CURRENT_USER Returns the name of the current user in the SQL Server
database
SESSION_USER Returns the name of the current user in the SQL Server
database
MS Access Functions
MS Access has many built-in functions.
This reference contains the string, numeric, and date functions in MS Access.
Function Description
Chr Returns the character for the specified ASCII number code
Function Description
Val Reads a string and returns the numbers found in the string
MS Access Date Functions
Function Description
DateAdd Adds a time/date interval to a date and then returns the date
DateSerial Returns a date from the specified parts (year, month, and day
values)
Now Returns the current date and time based on the computer's
system date and time
TimeSerial Returns a time from the specified parts (hour, minute, and
second value)
Function Description
SQL Quick Reference from
W3Schools
SQL Statement Syntax
or
or
SELECT column_name
FROM table_name AS table_alias
or
or
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
or
SELECT * SELECT *
FROM table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name