SQL-TUTORIAL
SQL-TUTORIAL
COM)
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!
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.
In this tutorial we will use the well-known Northwind sample database (included
in MS Access and MS SQL Server).
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.
In this tutorial, we will use semicolon at the end of each SQL statement.
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:
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
Example
SQL Tutorial 5 / 163
Source: https://www.w3schools.com/sql/default.asp
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 »
With Exercises
Exercise:
Insert the missing statement to get all the columns from the Customers table.
* FROM Customers;
Inside a table, a column often contains many duplicate values; and sometimes you only want to list
the different (distinct) values.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
SELECT Country FROM Customers;
Try it Yourself »
Example
SELECT DISTINCT Country FROM Customers;
Try it Yourself »
The following SQL statement lists the number of different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Try it Yourself »
Note: The example above will not work in Firefox! Because COUNT(DISTINCT column_name)
is not supported in Microsoft Access databases. Firefox is using Microsoft Access in our examples.
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
Try it Yourself »
Exercises
Exercise:
SQL Tutorial 8 / 163
Source: https://www.w3schools.com/sql/default.asp
Select all the different values from the Country column in the Customers table.
Submit Answer »
The WHERE clause is used to extract only those records that fulfill a specified
condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statement, it is also used
in UPDATE, DELETE statement, etc.!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Try it Yourself »
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Try it Yourself »
Exercise:
Select all records where the City column has the value "Berlin".
Submit Answer »
The AND and OR operators are used to filter records based on more than one
condition:
• The AND operator displays a record if all the conditions separated by AND
are TRUE.
• The OR operator displays a record if any of the conditions separated by
OR is TRUE.
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:
AND Example
The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city is "Berlin":
Example
SQL Tutorial 16 / 163
Source: https://www.w3schools.com/sql/default.asp
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):
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 »
Exercises
Exercise:
Select all records where the City column has the value 'Berlin' and
the PostalCode column has the value 12209.
* FROM Customers
City = 'Berlin'
= 12209;
The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
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:
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" column:
Example
Try it Yourself »
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Exercise:
SQL Tutorial 20 / 163
Source: https://www.w3schools.com/sql/default.asp
Select all records from the Customers table, sort the result alphabetically by the
column City.
The first way specifies both the column names and the values to be inserted:
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. The INSERT INTO
syntax would be as follows:
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
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 »
Exercises
Exercise:
Insert a new record in the Customers table.
Customers
CustomerName,
Address,
City,
PostalCode,
Country
'Hekkan Burger',
'Gateveien 15',
'Sandnes',
'4306',
'Norway' ;
Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during record
creation!
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Exercise:
SQL Tutorial 25 / 163
Source: https://www.w3schools.com/sql/default.asp
Select all records from the Customers where the PostalCode column is empty.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should
be updated. If you omit the WHERE clause, all records in the table will be
updated!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
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:
The following SQL statement will update the contactname to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records
will be updated!
Example
UPDATE Customers
SET ContactName='Juan';
Try it Yourself »
The selection from the "Customers" table will now look like this:
Exercise:
Update the City column of all records in the Customers 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:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The following SQL statement deletes all rows in the "Customers" table, without
deleting the table:
Example
DELETE FROM Customers;
Try it Yourself »
Exercise:
SQL Tutorial 30 / 163
Source: https://www.w3schools.com/sql/default.asp
Delete all the records from the Customers table where the Country value is 'Norway'.
Customers
Country = 'Norway';
The SELECT TOP clause is useful on large tables with thousands of records.
Returning a large number of records can impact performance.
Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while Oracle
uses ROWNUM.
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT TOP 3 * FROM Customers;
Try it Yourself »
The following SQL statement shows the equivalent example using the LIMIT
clause (for MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
Try it Yourself »
The following SQL statement shows the equivalent example using ROWNUM (for
Oracle):
Example
SELECT TOP 50 PERCENT * FROM Customers;
Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example using the LIMIT
clause (for MySQL):
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM (for
Oracle):
Example
The MAX() function returns the largest 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:
MIN() Example
The following SQL statement finds the price of the cheapest product:
SQL Tutorial 34 / 163
Source: https://www.w3schools.com/sql/default.asp
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
Exercise:
Use the MIN function to select the record with the smallest value of the Price column.
SELECT
FROM Products;
Submit Answer »
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
COUNT() Example
The following SQL statement finds the number of products:
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 »
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
Exercise:
Use the correct function to return the number of records that have
the Price value set to 18.
SELECT (*)
FROM Products
Price = 18;
There are two wildcards often used in conjunction with the LIKE operator:
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;
Tip: You can also combine any number of conditions using AND or OR
operators.
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending
with "a":
The following SQL statement selects all customers with a CustomerName that
have "or" in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
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%';
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__%';
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';
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%';
Submit Answer »
Wildcard characters are used with the SQL LIKE operator. The LIKE operator is
used in a WHERE clause to search for a specified pattern in a column.
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the
pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
The following SQL statement selects all customers with a City starting with "L",
followed by any character, followed by "n", followed by any character, followed
by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a",
"b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Example
Or:
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
Try it Yourself »
Exercise:
Select all records where the second letter of the City is an "a".
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);
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":
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)
Exercise:
Use the IN operator to select all the records where Country is either "Norway" or
"France".
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
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;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName BETWEEN
Carnarvon Tigers and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #01/07/1996# AND #31/07/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
Exercise:
Use the BETWEEN operator to select all the records where the value of the Price column
is between 10 and 20.
Submit Answer »
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
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;
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;
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;
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;
SELECT CustomerName,
Address,
PostalCode
FROM Customers;
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;
Exercises
Exercise:
Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,
using the CustomerID field in both tables as the relationship between the two tables.
SELECT *
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
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)
SELECT *
FROM Orders
ON Orders.CustomerID=Customers.CustomerID;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
Exercise:
Choose the correct JOIN clause to select all the records from the Customers table plus
all the matches in the Orders table.
SELECT *
FROM Orders
ON Orders.CustomerID=Customers.CustomerID;
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
CustomerName OrderID
Alfreds Futterkiste Null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Note: The FULL OUTER JOIN keyword returns all matching records from both
tables whether the other table matches or not. So, 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.
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
• Each SELECT statement within UNION must have the same number of
columns
• The columns must also have similar data types
• The columns in each SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
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 in the UNION.
Demo Database
SQL Tutorial 76 / 163
Source: https://www.w3schools.com/sql/default.asp
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
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;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
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".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
SQL Tutorial 79 / 163
Source: https://www.w3schools.com/sql/default.asp
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Ana Trujillo Avda. de la Constitución México 05021 Mexico
Emparedados y helados 2222 D.F.
3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
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
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
Exercise:
List the number of customers in each country.
SELECT (CustomerID),
Country
FROM Customers
;
HAVING Syntax
SELECT column_name(s)
FROM table_name
SQL Tutorial 81 / 163
Source: https://www.w3schools.com/sql/default.asp
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:
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
SQL Tutorial 82 / 163
Source: https://www.w3schools.com/sql/default.asp
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
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;
The following SQL statement lists if the employees "Davolio" or "Fuller" have
registered more than 25 orders:
Example
The EXISTS operator returns true if the subquery returns one or more records.
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:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
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);
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
The following SQL statement returns TRUE and lists the product names if it finds
ANY records in the OrderDetails table that quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
The following SQL statement returns TRUE and lists the product names if it finds
ANY records in the OrderDetails table that quantity > 99:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
> 99);
The following SQL statement returns TRUE and lists the product names if ALL
the records in the OrderDetails table has quantity = 10 (so, this example will
return FALSE, because not ALL records in the OrderDetails table has quantity =
10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
SELECT *
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.
The following SQL statement uses the IN clause to copy the table into a new
table in another database:
The following SQL statement copies only a few columns into a new table:
The following SQL statement copies data from more than one table into a new
table:
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:
• INSERT INTO SELECT requires that data types in source and target tables
match
• The existing records in the target table are unaffected
Copy only some columns from one table into another table:
Demo Database
In this tutorial we will use the well-known Northwind sample database.
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;
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';
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
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;
The following SQL will order the customers by City. However, if City is NULL,
then order by Country:
Example
SQL Tutorial 92 / 163
Source: https://www.w3schools.com/sql/default.asp
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
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
SQL Server
The SQL Server ISNULL() function lets you return an alternative value when an
expression is NULL:
MS Access
The MS Access IsNull() function returns TRUE (-1) if the expression is a null
value, otherwise FALSE (0):
Oracle
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:
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';
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;
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
Example
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;
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
SQL Operators
SQL Arithmetic Operators
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulo
Syntax
CREATE DATABASE databasename;
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;
Exercise:
Write the correct SQL statement to create a new database called testDB.
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;
ercises
Exercise:
Write the correct SQL statement to delete a database named testDB.
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
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).
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.).
Tip: For an overview of the available data types, go to our complete Data Types
Reference.
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
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;
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
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;
Syntax
TRUNCATE TABLE table_name;
Exercise:
Write the correct SQL statement to delete a table called Persons.
Persons;
The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
Example
ALTER TABLE Customers
DROP COLUMN Email;
Notice that the "DateOfBirth" column is now of type year and is going to hold a
year in a two- or four-digit format.
Persons
;
SQL Constraints
SQL constraints are used to specify rules for data in a table.
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.
The NOT NULL constraint enforces a column to NOT accept 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
);
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
MySQL:
MySQL:
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:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
MySQL:
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
"Persons" table:
"Orders" table:
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 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.
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL:
If you define a CHECK constraint on a single column it allows only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
MySQL:
MySQL:
The default value will be added to all new records IF no other value is specified.
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
MySQL:
SQL Server:
MS Access:
Oracle:
MySQL:
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.
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.
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):
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".
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):
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):
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).
SQL Tutorial 130 / 163
Source: https://www.w3schools.com/sql/default.asp
Use the following CREATE SEQUENCE syntax:
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):
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".
SQL Dates
The most difficult part when working with dates is to be sure that the format of
the date you are trying to insert, matches the format of the date column in the
database.
As long as your data contains only the date portion, your queries will work as
expected. However, if a time portion is involved, it gets 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!
Now we want to select the records with an OrderDate of "2008-11-11" from the
table above.
Now, assume that the "Orders" table looks like this (notice the time component
in the "OrderDate" column):
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 allow time
components in your dates!
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 functions, WHERE, and JOIN statements to a view and present
the data as if the data were coming from one single table.
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Example
SELECT * FROM [Brazil Customers];
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);
Example
SELECT * FROM [Products Above Average Price];
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';
Example
DROP VIEW [Brazil Customers];
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:
SQL Tutorial 136 / 163
Source: https://www.w3schools.com/sql/default.asp
UserId:
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?
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
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:
Password:
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Result
SQL Tutorial 137 / 163
Source: https://www.w3schools.com/sql/default.asp
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.
The SQL statement below will return all rows from the "Users" table, then delete
the "Suppliers" table.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Example
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.
The SQL engine checks each parameter to ensure that it is correct for its
column and are treated literally, and not as part of the SQL to be executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
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();
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.
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!
Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also adds
the UNSIGNED attribute to the column.
sql_variant Stores up to 8,000 bytes of data of various data types, except text,
ntext, and timestamp
SQL Keywords
Keyword Description
ADD Adds a column in an existing table
ADD CONSTRAINT Adds a constraint after a table is already created
ALTER Adds, deletes, or modifies columns in a table, or changes the
data type of a column in a table
ALTER COLUMN Changes the data type of a column in a table
ALTER TABLE Adds, deletes, or modifies columns in a table
ALL Returns true if all of the subquery values meet the condition
AND Only includes rows where both conditions is true
ANY Returns true if any of the subquery values meet the condition
AS Renames a column or table with an alias
ASC Sorts the result set in ascending order
BACKUP DATABASE Creates a back up of an existing database
BETWEEN Selects values within a given range
CASE Creates different outputs based on conditions
This reference contains string, numeric, date, and some advanced functions
in MySQL.
This reference contains the string, numeric, and date functions in MS Access.
Source : https://www.w3schools.com/sql/sql_quickref.asp