0% found this document useful (0 votes)
100 views24 pages

SQL For Better Study

SQL is a standard language used to access and manage relational database management systems (RDBMS). Some key points covered in the document include: - SQL lets users issue commands to retrieve, insert, update, and delete data stored in RDBMS tables. Common commands include SELECT, UPDATE, DELETE, and INSERT. - To build a dynamic website that pulls data from a database, one needs an RDBMS like MySQL or SQL Server, server-side scripting like PHP, and SQL statements. - The SELECT statement is used to retrieve data from tables. Common clauses include WHERE to filter results and ORDER BY to sort them. - Data is inserted into tables with INSERT, updated with UPDATE

Uploaded by

Vishal Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views24 pages

SQL For Better Study

SQL is a standard language used to access and manage relational database management systems (RDBMS). Some key points covered in the document include: - SQL lets users issue commands to retrieve, insert, update, and delete data stored in RDBMS tables. Common commands include SELECT, UPDATE, DELETE, and INSERT. - To build a dynamic website that pulls data from a database, one needs an RDBMS like MySQL or SQL Server, server-side scripting like PHP, and SQL statements. - The SELECT statement is used to retrieve data from tables. Common clauses include WHERE to filter results and ORDER BY to sort them. - Data is inserted into tables with INSERT, updated with UPDATE

Uploaded by

Vishal Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

1

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

SQL is a Standard - BUT....


Although SQL is an ANSI (American National Standards Institute) standard, there are different
versions of the SQL language.
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.

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:

An RDBMS database program (i.e. MS Access, SQL Server, MySQL)

To use a server-side 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.

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 North wind sample database (included in MS Access and MS SQL Server).
ustom CustomerName
erID

ContactName

Address

City

PostalC Country
ode

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

Ana Trujillo
Emparedados y helados

Ana Trujillo

Avda. de la
Constitucin

Mxico D.F.

05021

Mexico

2
2222
3

Antonio Moreno Taquera

Antonio Moreno

Mataderos
2312

Mxico D.F.

05023

Mexico

Around the Horn

Thomas Hardy

120 Hanover
Sq.

London

WA1
1DP

UK

Berglunds snabbkp

Christina Berglund

Berguvsvgen Lule
8

S-958
22

Sweden

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;

KEep in Mind That...

SQL is NOT case sensitive: select is the same as SELECT In this tutorial we will write all SQL
keywords in upper-case.

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement. 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.

Some of the Most Important SQL Commands

SELECT - extracts data from a database

UPDATE - updates data in a database

DELETE - deletes data from a database

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

The SQL SELECT Statement


The SELECT statement is used to select data from a database.The result is stored in a result table,
called the result-set.

SQL SELECT Syntax


SELECT column_name,column_name
FROM table_name;
and
SELECT * FROM table_name;

SELECT Column Example


The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table:

Example
SELECT CustomerName,City FROM Customers;

SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:

Example
SELECT * FROM Customers;

The SQL SELECT DISTINCT Statement


In a table, a column may contain many duplicate values; and sometimes you only want to list the
different (distinct) values.
The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax


SELECT DISTINCT column_name,column_name
FROM table_name;

SELECT DISTINCT Example


The following SQL statement selects only the distinct values from the "City" columns from the
"Customers" table:

Example
SELECT DISTINCT City FROM Customers;

The SQL WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax


SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

WHERE Clause Example


The following SQL statement selects all the customers from the country "Mexico", in the "Customers"
table:

Example
SELECT * FROM Customers
WHERE Country='Mexico';

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will also allow double
quotes).
However, numeric fields should not be enclosed in quotes:

Example
SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause


The following operators can be used in the 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

The SQL AND & OR Operators

5
The AND operator displays a record if both the first condition AND the second condition are true.The
OR operator displays a record if either the first condition OR the second condition is true.

AND Operator Example


The following SQL statement selects all customers from the country "Germany" AND the city "Berlin",
in the "Customers" table:

Example
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';

OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "Mnchen", in the
"Customers" table:

Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='Mnchen';

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions).The following SQL
statement selects all customers from the country "Germany" AND the city must be equal to "Berlin"
OR "Mnchen", in the "Customers" table:

Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='Mnchen');

The SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by one or more columns.
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.

SQL ORDER BY Syntax


SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;

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;

ORDER BY DESC Example


The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING
by the "Country" column:

Example
SELECT * FROM Customers
ORDER BY Country DESC;

ORDER BY Several Columns Example


The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column:

Example
SELECT * FROM Customers
ORDER BY Country,CustomerName;

The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

SQL INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two forms.
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,...);

INSERT INTO Example


Assume we wish to insert a new row in the "Customers" table.
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');

Insert Data Only in Specified Columns


It is also possible to only insert data in specific columns.

7
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');

The SQL UPDATE Statement


The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax


UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

SQL UPDATE Example


Assume we wish to update the customer "Alfreds Futterkiste" with a new contact person and city.
We use the following SQL statement:

Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';

The SQL DELETE Statement


The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax


DELETE FROM table_name
WHERE some_column=some_value;

SQL DELETE Example


Assume we wish to delete the customer "Alfreds Futterkiste" from the "Customers" table.
We use the following SQL statement:

Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';

Delete All Data


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

8
DELETE FROM table_name;
or
DELETE * FROM table_name;

SQL in Web Pages


In the previous chapters, you have learned to retrieve (and update) database data, using SQL.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 statement,
via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.

SQL Injection Based on 1=1 is Always True


Look at the example above, one more time.
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:

9
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1

SQL Injection Based on ""="" is Always True


Here is a common construction, used to verify user login to a web site:
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.

The SQL SELECT TOP Clause


The SELECT TOP clause is used to specify the number of records to return.
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.

SQL Server / MS Access Syntax


SELECT TOP number|percent column_name(s)
FROM table_name;

SQL SELECT TOP Equivalent in MySQL and Oracle


MySQL Syntax
SELECT column_name(s)
FROM table_name
LIMIT number;

10

Example
SELECT *
FROM Persons
LIMIT 5;

Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;

SQL SELECT TOP Example


The following SQL statement selects the two first records from the "Customers" table:

Example
SELECT TOP 2 * FROM Customers;

SQL SELECT TOP PERCENT Example


The following SQL statement selects the first 50% of the records from the "Customers" table:

Example
SELECT TOP 50 PERCENT * FROM Customers;

The SQL LIKE Operator


The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

SQL LIKE Operator Examples


The following SQL statement selects all customers with a City starting with the letter "s":

Example
SELECT * FROM Customers
WHERE City LIKE 's%';
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":

11

Example
SELECT * FROM Customers
WHERE City LIKE '%s';
The following SQL statement selects all customers with a Country containing the pattern "land":

Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Using the NOT keyword allows you to select records that does NOT match the pattern.
The following SQL statement selects all customers with a Country NOT containing the pattern "land":

Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';

SQL Wildcard Characters


In SQL, wildcard characters are used with the SQL LIKE operator. 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]

Using the SQL % Wildcard


The following SQL statement selects all customers with a City starting with "ber":

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%';

12

Using the SQL _ Wildcard


The following SQL statement selects all customers with a City starting with any character, followed by
"erlin":

Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';

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,...);

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');

The SQL BETWEEN Operator


The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.

SQL BETWEEN Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

BETWEEN Operator 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;

NOT BETWEEN Operator Example


To display the products outside the range of the previous example, use NOT BETWEEN:

Example

13
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN Operator with IN Example


The following SQL statement selects all products with a price BETWEEN 10 and 20, but products with
a CategoryID of 1,2, or 3 should not be displayed:

Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);

BETWEEN Operator with Text Value Example


The following SQL statement selects all products with a ProductName beginning with any of the letter
BETWEEN 'C' and 'M':

Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';

NOT BETWEEN Operator with Text Value Example


The following SQL statement selects all products with a ProductName beginning with any of the letter
NOT BETWEEN 'C' and 'M':

Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
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.

SQL Alias Syntax for Columns


SELECT column_name AS alias_name
FROM table_name;

SQL Alias Syntax for Tables


SELECT column_name(s)
FROM table_name AS alias_name;

Alias Example for Table Columns


The following SQL statement specifies two aliases, one for the CustomerName column and one for
the ContactName column. Tip: It requires double quotation marks or square brackets if the column
name contains spaces:

Example

14
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
In the following SQL statement we combine four columns (Address, City, PostalCode, and Country)
and create an alias named "Address":

Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address
FROM Customers;

Alias Example for Tables


The following SQL statement selects all the orders from the customer with CustomerID=4 (Around
the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and
"o" respectively (Here we have used aliases to make the SQL shorter):

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 same SQL statement without aliases:

Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the Horn" AND
Customers.CustomerID=Orders.CustomerID;

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 return all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
OrderID

CustomerID

OrderDate

10308

1996-09-18

10309

37

1996-09-19

10310

77

1996-09-20

Then, have a look at a selection from the "Customers" table:


CustomerID

CustomerName

ContactName

Country

Alfreds Futterkiste

Maria Anders

Germany

Ana Trujillo Emparedados y helados

Ana Trujillo

Mexico

Antonio Moreno Taquera

Antonio Moreno

Mexico

15
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;
it will produce something like this:
OrderID

CustomerName

OrderDate

10308

Ana Trujillo Emparedados y helados

9/18/1996

10365

Antonio Moreno Taquera

11/27/1996

10383

Around the Horn

12/16/1996

10355

Around the Horn

11/15/1996

10278

Berglunds snabbkp

8/12/1996

NNER 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

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

SQL INNER JOIN Keyword


The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns in both tables.

SQL INNER JOIN Syntax


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;
S! INNER JOIN is the same as JOIN.

16

Demo Database
In this tutorial we will use the well-known Northwind sample database.Below is a selection from the
"Customers" table:
C us id

CustomerName

ContactName Address

City

PostalCode Count

Alfreds Futterkiste

Maria Anders

Obere Str.
57

Berlin

12209

Germa

Ana Trujillo Emparedados y


helados

Ana Trujillo

Avda. de la Mxico D.F. 05021


Constitucin
2222

Mexico

Antonio Moreno Taquera

Antonio
Moreno

Mataderos
2312

Mexico

Mxico D.F. 05023

And a selection from the "Orders" table:


OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

1996-09-18

10309

37

1996-09-19

10310

77

1996-09-20

SQL INNER JOIN Example


The following SQL statement will return all customers with orders:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the
right table (table2). The result is NULL in the right side when there is no match.

17

SQL LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:

Customer CustomerName
ID

ContactName

Address

City

PostalCode Cou

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Ger

Ana Trujillo
Emparedados y
helados

Ana Trujillo

Avda. de la
Constitucin
2222

Mxico
D.F.

05021

Mex

Antonio Moreno
Taquera

Antonio Moreno

Mataderos 2312

Mxico
D.F.

05023

Mex

And a selection from the "Orders" table:


OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

1996-09-18

18

10309

37

1996-09-19

10310

77

1996-09-20

SQL LEFT JOIN Example


The following SQL statement will return all customers, and any orders they might have:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in
the left table (table1). The result is NULL in the left side when there is no match.

SQL RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

19

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

1996-09-18

10309

37

1996-09-19

10310

77

1996-09-20

And a selection from the "Employees" table:


EmployeeID LastName FirstName BirthDate

Photo

Notes

Davolio

Nancy

12/8/1968

EmpID1.pic

Education includes a BA in psychology..

Fuller

Andrew

2/19/1952

EmpID2.pic

Andrew received his BTS commercial an

Leverling

Janet

8/30/1963

EmpID3.pic

Janet has a BS degree in chemistry....

SQL RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they have placed:

Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;

SQL FULL OUTER JOIN Keyword


The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table
(table2).

20
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

SQL FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.Below is a selection from the
"Customers" table:
CustomerID CustomerName

ContactName Address

City

PostalCod
e

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Ana Trujillo Emparedados y helados Ana Trujillo

Avda. de la
Constitucin
2222

Mxico
D.F.

05021

Antonio Moreno Taquera

Mataderos
2312

Mxico
D.F.

05023

Antonio
Moreno

And a selection from the "Orders" table:


OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

1996-09-18

10309

37

1996-09-19

10310

77

1996-09-20

21

SQL FULL OUTER JOIN Example


The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
A selection from the result set may look like this:
CustomerName

OrderID

Alfreds Futterkiste
Ana Trujillo Emparedados y helados

10308

Antonio Moreno Taquera

10365
10382
10351

Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all
the rows from the right table (Orders). If there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will
be listed as well.

The SQL UNION operator combines the result of two or more SELECT statements.

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The
columns must also have similar data types. Also, the columns in each SELECT statement must be in
the same order.

SQL UNION Syntax


SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the
ALL keyword with UNION.

22

SQL UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID

CustomerName

ContactName Address

City

PostalCode C

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Ana Trujillo Emparedados Ana Trujillo


y helados

Avda. de la
Constitucin 2222

Mxico
D.F.

05021

Antonio Moreno Taquera

Mataderos 2312

Mxico
D.F.

05023

Antonio
Moreno

And a selection from the "Suppliers" table:


SupplierID

SupplierName

ContactName

Address

City

PostalCod
e

Exotic Liquid

Charlotte
Cooper

49 Gilbert St.

Londona

EC1 4SD

New Orleans Cajun


Delights

Shelley Burke

P.O. Box
78934

New
Orleans

70117

Grandma Kelly's
Homestead

Regina Murphy

707 Oxford
Rd.

Ann Arbor

48104

SQL UNION Example


The following SQL statement selects all the different cities (only distinct values) from the
"Customers" and the "Suppliers" tables:

Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Note: UNION cannot be used to list ALL cities from the two tables. If several customers and
suppliers share the same city, each city will only be listed once. UNION selects only distinct values.
Use UNION ALL to also select duplicate values!

23

SQL UNION ALL Example


The following SQL statement uses UNION ALL to select all (duplicate values also) cities from the
"Customers" and "Suppliers" tables:

Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

SQL UNION ALL With WHERE


The following SQL statement uses UNION ALL to select all (duplicate values also) German cities
from the "Customers" and "Suppliers" tables:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

With SQL, you can copy information from one table into another.
The SELECT INTO statement copies data from one table and inserts it into a new table.

The SQL SELECT INTO Statement


The SELECT INTO statement selects data from one table and inserts it into a new table.

SQL SELECT INTO Syntax


We can copy all columns into the new table:
SELECT *
INTO newtable [IN externaldb]
FROM table1;
Or we can copy only the columns we want into the new table:
SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;
The new table will be created with the column-names and types as defined in the SELECT statement.
You can apply new names using the AS clause.

24

SQL SELECT INTO Examples


Create a backup copy of Customers:
SELECT *
INTO CustomersBackup2013
FROM Customers;
Use the IN clause to copy the table into another database:
SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers;
Copy only a few columns into the new table:
SELECT CustomerName, ContactName
INTO CustomersBackup2013
FROM Customers;
Copy only the German customers into the new table:
SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany';
Copy data from more than one table into the new table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2013
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;
Tip: The SELECT INTO statement can also be used to create a new, empty table using the schema of
another. Just add a WHERE clause that causes the query to return no data:
SELECT *
INTO newtable
FROM table1
WHERE 1=0;

You might also like