SQL DATABASE
Source: https://www.w3schools.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
Introduction to SQL
What Can SQL do?
● SQL can execute queries against a database
● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
● SQL can create new databases
● SQL can create new tables in a database
● SQL can create stored procedures in a database
● SQL can create views in a database
● SQL can set permissions on tables, procedures, and views
Introduction to SQL
SQL is a Standard - BUT....
Although SQL is an ANSI/ISO 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.
Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL
standard!
Using SQL in Your Web Site
To build a website 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 to style the page
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or
"Orders"). Tables contain records (rows) with data.
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).
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:
SELECT * FROM Customers;
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:
SELECT * FROM Customers;
SQL Syntax
Keep in Mind That...
● SQL keywords are NOT case sensitive: select is the same as SELECT
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.
SQL Syntax
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
SQL Statements
Select
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all
the fields available in the table, use the following syntax:
SELECT * FROM table_name;
SQL Statements
Select
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
SQL Statements
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, …
FROM table_name;
SQL Statements
Database Tables
Below is a selection from the "Customers" table in the Northwind sample database:
SQL Statements
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from the "Country" column in the
"Customers" table: SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
SQL Statements
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the "Customers"
table: SELECT DISTINCT Country FROM Customers;
SQL Statements
SELECT DISTINCT Examples
The following SQL statement lists the number of different (distinct) customer countries:
SELECT COUNT(DISTINCT Country) FROM Customers;
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.
Here is the workaround for MS Access:
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
SQL Statements
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the column names in the
SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
SQL Statements
INSERT INTO Example
The following SQL statement inserts a new record in the "Customers" table:
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.
SQL Statements
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
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):
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
SQL Statements
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
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!
SQL Statements
UPDATE Table
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new
city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
SQL Statements
UPDATE Multiple Records
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the ContactName to "Juan" for all records where country is "Mexico":
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
SQL Statements
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:
SQL Statements
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The
WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the
table will be deleted!
SQL Statements
Below is a selection from the "Customers" table in the Northwind sample database:
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The "Customers" table will now look like this:
SQL Statements
Delete All Records
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:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
Example
DELETE FROM Customers;
SQL Statements
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of
customers in each country".
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);
SQL Statements
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
SQL Statements
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country, sorted high to low:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
SQL Statements
GROUP BY With JOIN Example
The following SQL statement lists the number of orders sent by each shipper:
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
Clauses
The SQL WHERE Clause
The WHERE clause is used to filter records.
It 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 statements, it is also used in UPDATE, DELETE, etc.!
Clauses
WHERE Clause Example
The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table:
SELECT * FROM Customers
WHERE Country='Mexico';
Clauses
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:
SELECT * FROM Customers
WHERE CustomerID=1;
Clauses
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
Clauses
The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.
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 FETCH FIRST n ROWS ONLY and ROWNUM.
Clauses
Clauses
Clauses
SQL TOP, LIMIT and FETCH FIRST Examples
The following SQL statement selects the first three records from the "Customers" table (for SQL Server/MS Access):
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example for MySQL:
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
The Result:
Clauses
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the records from the "Customers" table (for SQL Server/MS Access):
SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
Clauses
ADD a WHERE CLAUSE
The following SQL statement selects the first three records from the "Customers" table, where the country is "Germany" (for SQL
Server/MS Access):
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example for MySQL:
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
AND, OR, and NOT Operators
The SQL AND, OR and NOT Operators
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, OR, and NOT Operators
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;
AND, OR, and NOT Operators
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';
AND, OR, and NOT Operators
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';
AND, OR, and NOT Operators
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
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":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
AND, OR, and NOT Operators
OR Example
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
AND, OR, and NOT Operators
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
The result will show all data but not the data that has Germany in the Country.
AND, OR, and NOT Operators
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
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):
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
AND, OR, and NOT Operators
The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and NOT
"USA":
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
Order Keyword
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
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;
Order Keyword
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column:
SELECT * FROM Customers
ORDER BY Country;
Order Keyword
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
Order Keyword
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" and the
"CustomerName" column. This means that it orders by Country, but if some rows have the same Country, it
orders them by CustomerName:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Order Keyword
ORDER BY Several Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Null Values
What is a NULL Value?
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to
this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is
one that has been left blank during record creation!
Null Values
How to Test for NULL Values?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
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;
IS NOT NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Order Keyword
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Tip: Always use IS NULL to look for NULL values.
Order Keyword
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Min() and Max(), Count(), Avg(), and Sum() Functions
The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
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;
Min() and Max(), Count(), Avg(), and Sum() Functions
MIN() Example
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
SELECT MAX(Price) AS LargestPrice
FROM Products;
Min() and Max(), Count(), Avg(), and Sum() Functions
The SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Min() and Max(), Count(), Avg(), and Sum() Functions
The SQL COUNT(), AVG() and SUM() Functions
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Min() and Max(), Count(), Avg(), and Sum() Functions
COUNT() Example
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not counted.
AVG() Example
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
Min() and Max(), Count(), Avg(), and Sum() Functions
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Quantity)
FROM OrderDetails;
Note: NULL values are ignored.
Like, In, and Between Operator
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
● The percent sign (%) represents zero, one, or multiple characters
● The underscore sign (_) represents one, single character
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.
Like, In, and Between Operator
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName that have "or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName that have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3
characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
Like, In, and Between Operator
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName that does NOT start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
Like, In, and Between Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
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);
Like, In, and Between Operator
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Like, In, and Between Operator
IN Operator Examples
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
Like, In, and Between Operator
The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
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;
Like, In, and Between Operator
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Like, In, and Between Operator
NOT BETWEEN Example
To display the products outside the range of the previous example, use NOT BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Like, In, and Between Operator
BETWEEN with IN Example
The following SQL statement selects all products with a price between 10 and 20. In addition; do not show
products with a CategoryID of 1,2, or 3:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
Like, In, and Between Operator
BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Mozzarella
di Giovanni:
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Like, In, and Between Operator
BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Chef
Anton's Cajun Seasoning:
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
Like, In, and Between Operator
NOT BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName not between Carnarvon Tigers and
Mozzarella di Giovanni:
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Like, In, and Between Operator
BETWEEN Dates Example
The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-1996':
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
Like, In, and Between Operator
BETWEEN Dates Example
OR:
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
Join Keyword
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:
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.
Join Keyword
SQL JOIN
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have
matching values in both tables:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:
Join Keyword
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Inner Join
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Inner Join
SQL INNER JOIN Keyword
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
Inner Join
SQL INNER JOIN Example
The following SQL statement selects all orders with customer information:
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!
Inner Join
JOIN Three Tables
The following SQL statement selects all orders with customer and shipper information:
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);
Left Join
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the
right table (table2). The result is 0 records from the right side, if there is no match.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
Left Join
SQL LEFT JOIN Keyword
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Left Join
SQL LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might have:
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).
Right Join
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the
left table (table1). The result is 0 records from the left side, if there is no match.
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
Right Join
SQL RIGHT JOIN Keyword
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
Right Join
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they might have placed:
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).
Full Outer Join
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table
records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Note: FULL OUTER JOIN can potentially return very large result-sets!
Full Outer Join
SQL FULL OUTER JOIN Keyword
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Full Outer Join
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:
Self Join
SQL Self Join
A self join is a regular join, but the table is joined with itself.
Self Join Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
T1 and T2 are different table aliases for the same table.
Self Join
SQL Self Join
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Self Join
SQL Self Join Example
The following SQL statement matches customers that are from the same city:
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
Union Operator
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
● Every SELECT statement within UNION must have the same number of columns
● The columns must also have similar data types
● The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Union Operator
The SQL UNION Operator
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Union Operator
SQL UNION Example
The following SQL statement returns the cities (only distinct values) from both the "Customers" and the
"Suppliers" table:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
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!
Union Operator
SQL UNION ALL Example
The following SQL statement returns the cities (duplicate values also) from both the "Customers" and the
"Suppliers" table:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Union Operator
SQL UNION With WHERE
The following SQL statement returns the German cities (only distinct values) from both the "Customers" and
the "Suppliers" table:
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Union Operator
SQL UNION ALL With WHERE
The following SQL statement returns the German cities (duplicate values also) from both the "Customers" and
the "Suppliers" table:
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Union Operator
Another UNION Example
The following SQL statement lists all customers and suppliers:
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".
Getting a host and a domain name
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server should have
access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.
MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web sites with high traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Getting a host and a domain name
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.
MySQL is an inexpensive alternative to the expensive Microsoft and Oracle solutions.
MS Access
When a web site requires only a simple database, Microsoft Access can be a solution.
MS Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server, or Oracle.
Source:
https://www.w3schools.com/css/default.asp
Thank you!