Select From: Try It Yourself
Select From: Try It Yourself
SQL is a standard language for storing, manipulating and retrieving data in databases.
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other
database systems.
Example
SELECT * FROM Customers;
Introduction to SQL
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of
columns and rows.
Look at the "Customers" table:
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.
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables
contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS SQL Server).
Below is a selection from the "Customers" table:
2 Ana Trujillo Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
Emparedados y helados
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName, ContactName,
Address, City, PostalCode, and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
In this tutorial we will teach you all about the different SQL statements.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
Try it Yourself »
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Operator Description
= Equal
> Greater than
<> Not equal. Note: In some versions of SQL this operator may be written as !=
The WHERE clause can be combined with AND, OR, and NOT operators.
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.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
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';
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
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';
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';
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
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';
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;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The selection from the "Customers" table will now look like this:
CustomerI CustomerName ContactName Address City PostalCode Country
D
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';
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados y helados Juan Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Juan Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
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
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
MIN() Example
The following SQL statement finds the price of the cheapest product:
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;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not counted.
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
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
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
Note: NULL values are ignored.
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:
SQL Wildcards
* 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 not hit
brackets
! Represents any character not in the brackets h[!oa]t finds hit, but not hot and hat
% Represents zero or more characters bl% finds bl, black, blue, and blob
[] Represents any single character within the brackets h[oa]t finds hot and hat, but not hit
^ Represents any character not in the brackets h[^oa]t finds hit, but not hot and hat
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_ Finds any values that starts with "a" and are at least 3 characters in
%' length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
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');
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');
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);
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;
Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of the query.
Alias Column Syntax
SELECT column_name AS alias_name
FROM table_name;
Alias Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
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
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
Let's look at a selection from the "Orders" table:
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;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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.
Below is a selection from the "Orders" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
CustomerName OrderID
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.
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Tokyo 100 Japan
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
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
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
OrderDetailI OrderI ProductI Quantit
D D D y
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
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.
Look at the following SELECT statement:
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;
In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.
Solutions
MySQL
The MySQL IFNULL() function lets you return an alternative value if an expression is NULL:
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
or we can use the COALESCE() function, like this:
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;
SQL Server
The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products;
MS Access
The MS Access IsNull() function returns TRUE (-1) if the expression is a null value, otherwise FALSE (0):
SELECT ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))
FROM Products;
Oracle
The Oracle NVL() function achieves the same result:
SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))
FROM Products;
SQL Stored Procedures for SQL Server
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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!
Comments are not supported in Microsoft Access databases. Firefox and Microsoft Edge are using Microsoft Access database in
our examples.
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
The following example uses a multi-line comment as an explanation:
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Try it Yourself »
The following example uses a multi-line comment to ignore many statements:
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Try it Yourself »
To ignore just a part of a statement, also use the /* */ comment.
The following example uses a comment to ignore part of a line:
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
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulo
Operato Description
r
| Bitwise OR
^ Bitwise exclusive OR
Operato Description
r
= Equal to
Operato Description
r
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
Operator Description