SQL Tutorial: Examples in Each Chapter
SQL Tutorial: Examples in Each Chapter
SQL Tutorial
« W3Schools Home Next Chapter »
SQL is a standard language for accessing databases.
Our SQL tutorial will teach you how to use SQL to access and
SQL manipulate data in: MySQL, SQL Server, Access, Oracle, Sybase,
DB2, and other database systems.
Example
SELECT * FROM Customers;
Try it yourself »
Click on the "Try it yourself" button to see how it works.
Start learning SQL now!
1/3
4/7/2016 SQL Tutorial
Start SQL Quiz!
SQL Quick Reference
SQL Data Types
W3Schools Exam
More than 10 000 certificates already issued!
Get Your Certificate »
2/3
4/7/2016 SQL Tutorial
The HTML Certificate documents your knowledge of HTML.
The HTML5 Certificate documents your knowledge of advanced HTML5.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The jQuery Certificate documents your knowledge of jQuery.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The Bootstrap Certificate documents your knowledge of the Bootstrap framework.
« W3Schools Home Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL Introduction
Introduction to SQL
« Previous Next Chapter »
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 is an ANSI (American National Standards Institute) standard
However, to be compliant with the ANSI standard, they all support at least the major
1/2
4/7/2016 SQL Introduction
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!
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
To use a serverside scripting language, like PHP or ASP
To use SQL to get the data you want
To use HTML / CSS
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.
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
2/2
4/7/2016 SQL Syntax
SQL Syntax
« Previous Next Chapter »
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 wellknown Northwind sample database (included in MS
Access and MS SQL Server).
Below is a selection from the "Customers" table:
The table above contains five records (one for each customer) and seven columns
(CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).
1/3
4/7/2016 SQL Syntax
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 write all SQL keywords in uppercase.
Semicolon is the standard way to separate each SQL statement in database systems
that allow more than one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.
2/3
4/7/2016 SQL Syntax
INSERT INTO inserts new data into a database
CREATE DATABASE creates a new database
ALTER DATABASE modifies a database
CREATE TABLE creates a new table
ALTER TABLE modifies a table
DROP TABLE deletes a table
CREATE INDEX creates an index (search key)
DROP INDEX deletes an index
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the resultset.
SELECT column_name,column_name
FROM table_name;
and
SELECT * FROM table_name;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
1/3
4/7/2016 SQL SELECT Statement
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 »
2/3
4/7/2016 SQL SELECT Statement
Navigation in a Result‐set
Most database software systems allow navigation in the resultset with programming
functions, like: MoveToFirstRecord, GetRecordContent, MoveToNextRecord, etc.
Programming functions like these are not a part of this tutorial. To learn about accessing
data with function calls, please visit our ASP tutorial or our PHP tutorial.
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different)
values.
The DISTINCT keyword can be used to return only distinct (different) values.
SELECT DISTINCT column_name,column_name
FROM table_name;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
Example
SELECT DISTINCT City FROM Customers;
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
2/2
4/7/2016 SQL WHERE Clause
The WHERE clause is used to filter records.
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
1/3
4/7/2016 SQL WHERE Clause
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Try it yourself »
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Try it yourself »
2/3
4/7/2016 SQL WHERE Clause
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may
be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL AND & OR Operators
The AND & OR operators are used to filter records based on more than one
condition.
The OR operator displays a record if either the first condition OR the second condition is
true.
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
Try it yourself »
OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "München",
in the "Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
Try it yourself »
2/3
4/7/2016 SQL AND & OR Operators
The following SQL statement selects all customers from the country "Germany" AND the
city must be equal to "Berlin" OR "München", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the resultset.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in a descending order, you can use the DESC keyword.
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
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 »
2/3
4/7/2016 SQL ORDER BY Keyword
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Try it yourself »
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
The first form does not specify the column names where the data will be inserted, only
their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
1/4
4/7/2016 SQL INSERT INTO Statement
We can use the following SQL statement:
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:
Did you notice that we did not insert any number into the
CustomerID field?
The CustomerID column is automatically updated with a unique number
for each record in the table.
The following SQL statement will insert a new row, but only insert data in the
"CustomerName", "City", and "Country" columns (and the CustomerID field will of
course also be updated automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
Try it yourself »
3/4
4/7/2016 SQL INSERT INTO Statement
The selection from the "Customers" table will now look like this:
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
4/4
4/7/2016 SQL UPDATE Statement
The UPDATE statement is used to update records in a table.
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Notice the WHERE clause in the SQL UPDATE statement!
The WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be updated!
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
helados 2222
We use the following SQL statement:
Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
Try it yourself »
The selection from the "Customers" table will now look like this:
Update Warning!
Be careful when updating records. If we had omitted the WHERE clause, in the example
above, like this:
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg';
The "Customers" table would have looked like this:
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL DELETE Statement
The DELETE statement is used to delete records in a table.
DELETE FROM table_name
WHERE some_column=some_value;
Notice the WHERE clause in the SQL DELETE statement!
The WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be deleted!
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
We use the following SQL statement:
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria
Anders';
Try it yourself »
The "Customers" table will now look like this:
2/3
4/7/2016 SQL DELETE Statement
DELETE FROM table_name;
or
DELETE * FROM table_name;
Note: Be very careful when deleting records. You cannot undo this statement!
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL Injection
SQL Injection
« Previous Next Chapter »
An SQL Injection can destroy your database.
When SQL is used to display data on a web page, it is common to let web users input
their own search values.
Since SQL statements are text only, it is easy, with a little piece of computer code, to
dynamically change SQL statements to provide the user with selected data:
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The example above, creates a select statement by adding a variable (txtUserId) to a
select string. The variable is fetched from the user input (Request) to the page.
The rest of this chapter describes the potential dangers of using user input in SQL
statements.
SQL Injection
SQL injection is a technique where malicious users can inject SQL commands into an SQL
1/7
4/7/2016 SQL Injection
statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web
application.
Let's say that the original purpose of the code was to create an SQL statement to select
a user with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can enter
some "smart" input like this:
UserId:
105 or 1=1
Server Result
SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is
always true.
Does the example above seem dangerous? What if the Users table contains names and
passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1
A smart hacker might get access to all the user names and passwords in a database by
simply inserting 105 or 1=1 into the input box.
2/7
4/7/2016 SQL Injection
User Name:
Password:
Server Code
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='"
+ uPass + "'"
A smart hacker might get access to user names and passwords in a database by simply
inserting " or ""=" into the user name or password text box.
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since WHERE ""="" is
always true.
3/7
4/7/2016 SQL Injection
Example
SELECT * FROM Users; DROP TABLE Suppliers
The SQL above will return all rows in the Users table, and then delete the table called
Suppliers.
If we had the following server code:
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
And the following input:
User id:
105; DROP TABLE Suppliers
The code at the server would create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers
This is not a very good idea. Many of these words (like delete or drop) and characters
(like semicolons and quotation marks), are used in common language, and should be
allowed in many types of input.
4/7
4/7/2016 SQL Injection
(In fact it should be perfectly legal to input an SQL statement in a database field.)
The only proven way to protect a web site from SQL injection attacks, is to use SQL
parameters.
SQL parameters are values that are added to an SQL query at execution time, in a
controlled manner.
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);
Note that parameters are represented in the SQL statement by a @ marker.
The SQL engine checks each parameter to ensure that it is correct for its column and are
treated literally, and not as part of the SQL to be executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
You have just learned to avoid SQL injection. One of the top website
vulnerabilities.
Examples
The following examples shows how to build parameterized queries in some common
web languages.
5/7
4/7/2016 SQL Injection
SELECT STATEMENT IN ASP.NET:
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
INSERT INTO STATEMENT IN ASP.NET:
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
INSERT INTO STATEMENT IN PHP:
$stmt = $dbh‐>prepare("INSERT INTO Customers
(CustomerName,Address,City)
VALUES (:nam, :add, :cit)");
$stmt‐>bindParam(':nam', $txtNam);
$stmt‐>bindParam(':add', $txtAdd);
$stmt‐>bindParam(':cit', $txtCit);
$stmt‐>execute();
« Previous Next Chapter »
6/7
4/7/2016 SQL Injection
Copyright 19992015 by Refsnes Data. All Rights Reserved.
7/7
4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM
The SELECT TOP clause can be very useful on large tables with thousands of records.
Returning a large number of records can impact on performance.
Note: Not all database systems support the SELECT TOP clause.
SELECT TOP number|percent column_name(s)
FROM table_name;
SELECT column_name(s)
FROM table_name
LIMIT number;
Example
SELECT *
FROM Persons
LIMIT 5;
1/3
4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
2/3
4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM
Example
SELECT TOP 2 * FROM Customers;
Try it yourself »
Example
SELECT TOP 50 PERCENT * FROM Customers;
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
Example
SELECT * FROM Customers
WHERE City LIKE 's%';
Try it yourself »
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the
pattern. You will learn more about wildcards in the next chapter.
The following SQL statement selects all customers with a City ending with the letter "s":
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
Try it yourself »
The following SQL statement selects all customers with a Country containing the pattern
"land":
2/3
4/7/2016 SQL LIKE Operator
Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Try it yourself »
Using the NOT keyword allows you to select records that do NOT match the pattern.
The following SQL statement selects all customers with Country NOT containing the
pattern "land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL Wildcards
SQL Wildcards
« Previous Next Chapter »
A wildcard character can be used to substitute for any other character(s) in a
string.
SQL wildcards are used to search for data within a table.
With SQL, the wildcards are:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] Matches only a character NOT specified within the brackets
or
[!charlist]
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
1/5
4/7/2016 SQL Wildcards
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%';
2/5
4/7/2016 SQL Wildcards
Try it yourself »
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
Try it yourself »
The following SQL statement selects all customers with a City starting with "L", followed
by any character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Try it yourself »
Example
3/5
4/7/2016 SQL Wildcards
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 »
The following SQL statement selects all customers with a City NOT starting with "b", "s",
or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
or
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
4/5
4/7/2016 SQL Wildcards
5/5
4/7/2016 SQL IN Operator
SQL IN Operator
« Previous Next Chapter »
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
1/2
4/7/2016 SQL IN Operator
IN Operator Example
The following SQL statement selects all customers with a City of "Paris" or "London":
Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
Try it yourself »
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
2/2
4/7/2016 SQL BETWEEN Operator
The BETWEEN operator is used to select values within a range.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Products" table:
1 Chais 1 1 10 18
boxes x
20 bags
2 Chang 1 1 24 12 19
oz
bottles
1/5
4/7/2016 SQL BETWEEN Operator
3 Aniseed Syrup 1 2 12 550 10
ml
bottles
4 Chef Anton's Cajun 1 2 48 6 22
Seasoning oz jars
5 Chef Anton's 1 2 36 21.35
Gumbo Mix boxes
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 »
2/5
4/7/2016 SQL BETWEEN Operator
Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
Try it yourself »
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
Try it yourself »
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Try it yourself »
Sample Table
Below is a selection from the "Orders" table:
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
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
4/5
4/7/2016 SQL BETWEEN Operator
Try it yourself »
Notice that the BETWEEN operator can produce different result in
different databases!
In some databases, BETWEEN selects fields that are between and
excluding the test values.
In other databases, BETWEEN selects fields that are between and
including the test values.
And in other databases, BETWEEN selects fields between the test
values, including the first test value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator!
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
5/5
4/7/2016 SQL Aliases
SQL Aliases
« Previous Next Chapter »
SQL aliases are used to temporarily rename a table or a column heading.
SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
SELECT column_name AS alias_name
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Orders" table:
10354 58 8 19961114 3
10355 4 6 19961115 1
10356 86 6 19961118 2
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
Try it yourself »
In the following SQL statement we combine four columns (Address, City, PostalCode,
and Country) and create an alias named "Address":
2/4
4/7/2016 SQL Aliases
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country
AS Address
FROM Customers;
Try it yourself »
Note: To get the SQL statement above to work in MySQL use the following:
SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,',
',Country) AS Address
FROM Customers;
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 same SQL statement without aliases:
3/4
4/7/2016 SQL 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 »
Aliases can be useful when:
There are more than one table involved in a query
Functions are used in the query
Column names are big or not very readable
Two or more columns are combined together
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
4/4
4/7/2016 SQL Joins
SQL Joins
« Previous Next Chapter »
SQL joins are used to combine rows from two or more tables.
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based on a
common field between them.
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER
JOIN returns all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
10308 2 19960918
10309 37 19960919
10310 77 19960920
Then, have a look at a selection from the "Customers" table:
1/3
4/7/2016 SQL Joins
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in
the "Customers" table. The relationship between the two tables above is the
"CustomerID" column.
Then, if we run the following SQL statement (that contains an INNER JOIN):
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
Try it yourself »
it will produce something like this:
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the
right table
2/3
4/7/2016 SQL Joins
RIGHT JOIN: Return all rows from the right table, and the matched rows from the
left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3
4/7/2016 SQL INNER JOIN Keyword
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
PS! INNER JOIN is the same as JOIN.
1/3
4/7/2016 SQL INNER JOIN Keyword
Demo Database
In this tutorial we will use the wellknown Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Orders" table:
10308 2 7 19960918 3
10309 37 3 19960919 1
10310 77 8 19960920 2
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
2/3
4/7/2016 SQL INNER JOIN Keyword
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Try it yourself »
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns. If there are rows in the "Customers" table that do not
have matches in "Orders", these customers will NOT be listed.
« Previous Next Chapter »
Copyright 19992015 by Refsnes Data. All Rights Reserved.
3/3