SQL Tutorial 2024
SQL Tutorial 2024
SQL Tutorial 2024
Contents:
SQL Tutorial
Contents:
Introduction to SQL
SQL Syntax
SQL SELECT Statement
SQL SELECT DISTINCT Statement
SQL WHERE Clause
SQL ORDER BY Keyword
SQL AND Operator
SQL OR Operator
SQL NOT Operator
SQL INSERT INTO Statement
SQL NULL Values
SQL UPDATE Statement
SQL DELETE Statement
SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause
SQL Aggregate Functions
SQL MIN() and MAX() Functions
SQL COUNT() Function
SQL SUM() Function
SQL AVG() Function
SQL LIKE Operator
SQL Wildcards
SQL IN Operator
SQL BETWEEN Operator
SQL Aliases
SQL Joins
SQL INNER JOIN
SQL LEFT JOIN Keyword
SQL RIGHT JOIN Keyword
SQL FULL OUTER JOIN Keyword
SQL Self Join
SQL UNION Operator
SQL GROUP BY Statement
SQL HAVING Clause
SQL EXISTS Operator
SQL ANY and ALL Operators
SQL SELECT INTO Statement
SQL INSERT INTO SELECT Statement
SQL CASE Expression
SQL NULL Functions
SQL Stored Procedures for SQL Server
SQL Comments
SQL Operators
SQL DATABASE
SQL CREATE DATABASE Statement
SQL DROP DATABASE Statement
SQL BACKUP DATABASE for SQL Server
SQL CREATE TABLE Statement
SQL DROP TABLE Statement
SQL ALTER TABLE Statement
SQL Constraints
SQL NOT NULL Constraint
SQL UNIQUE Constraint
SQL PRIMARY KEY Constraint
SQL FOREIGN KEY Constraint
SQL CHECK Constraint
SQL DEFAULT Constraint
SQL CREATE INDEX Statement
SQL AUTO INCREMENT Field
SQL Working With Dates
SQL Views
SQL Injection
SQL Hosting
SQL Data Types for MySQL, SQL Server, and MS Access
SQL Keywords Reference
SQL ADD Keyword
SQL ADD CONSTRAINT Keyword
SQL ALL Keyword
SQL ALTER Keyword
SQL ALTER COLUMN Keyword
SQL ALTER TABLE Keyword
SQL AND Keyword
SQL ANY Keyword
SQL AS Keyword
SQL ASC Keyword
SQL BACKUP DATABASE Keyword
SQL BETWEEN Keyword
SQL CASE Keyword
SQL CHECK Keyword
SQL COLUMN Keyword
SQL CONSTRAINT Keyword
SQL CREATE Keyword
SQL CREATE DATABASE Keyword
SQL CREATE INDEX Keyword
SQL CREATE OR REPLACE VIEW Keyword
SQL CREATE TABLE Keyword
SQL CREATE PROCEDURE Keyword
SQL CREATE UNIQUE INDEX Keyword
SQL CREATE VIEW Keyword
SQL DATABASE Keyword
SQL DEFAULT Keyword
SQL DELETE Keyword
SQL DESC Keyword
SQL SELECT DISTINCT Keyword
SQL DROP Keyword
SQL DROP COLUMN Keyword
SQL DROP CONSTRAINT Keyword
SQL DROP DATABASE Keyword
SQL DROP DEFAULT Keyword
SQL DROP INDEX Keyword
SQL DROP TABLE and TRUNCATE TABLE Keywords
SQL DROP VIEW Keyword
SQL EXEC Keyword
SQL EXISTS Keyword
SQL FOREIGN KEY Keyword
SQL FROM Keyword
SQL FULL OUTER JOIN Keyword
SQL GROUP BY Keyword
SQL HAVING Keyword
SQL IN Keyword
SQL INDEX Keyword
SQL INNER JOIN Keyword
SQL INSERT INTO Keyword
SQL INSERT INTO SELECT Keyword
SQL IS NULL Keyword
SQL IS NOT NULL Keyword
SQL JOIN Keyword
SQL LEFT JOIN Keyword
SQL LIKE Keyword
SQL SELECT TOP, LIMIT and ROWNUM Keywords
SQL SELECT TOP, LIMIT and ROWNUM Keywords
SQL NOT NULL Keyword
SQL OR Keyword
SQL ORDER BY Keyword
SQL FULL OUTER JOIN Keyword
SQL PRIMARY KEY Keyword
SQL CREATE PROCEDURE Keyword
SQL RIGHT JOIN Keyword
SQL SELECT TOP, LIMIT and ROWNUM Keywords
SQL SELECT Keyword
SQL SELECT DISTINCT Keyword
SQL SELECT INTO Keyword
SQL SELECT TOP, LIMIT and ROWNUM Keywords
SQL SET Keyword
SQL TABLE Keyword
SQL SELECT TOP, LIMIT and ROWNUM Keywords
SQL DROP TABLE and TRUNCATE TABLE Keywords
SQL UNION Keyword
SQL UNION ALL Keyword
SQL UNIQUE Keyword
SQL UPDATE Keyword
SQL VALUES Keyword
SQL VIEW Keyword
SQL WHERE Keyword
MySQL Functions
SQL Server Functions
MS Access Functions
SQL Quick Reference from W3Schools
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS
Access, Oracle, Sybase, Informix, Postgres, and other database systems.
Introduction to SQL
However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Example
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields in the
Customers table consist of CustomerID, CustomerName, ContactName,
Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For
example, there are 91 records in the above Customers table. A record is a
horizontal entity in a table.
SQL Syntax
SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements.
Example
Select all records from the Customers table:
In this tutorial we will teach you all about the different SQL statements.
Database Tables
A database most often contains one or more tables. Each table is identified by a
name (e.g. "Customers" or "Orders"), and contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included
in MS Access and MS SQL Server).
The table above contains five records (one for each customer) and seven
columns (CustomerID, CustomerName, ContactName, Address, City,
PostalCode, and Country).
In this tutorial, we will use semicolon at the end of each SQL statement.
Example
Return data from the Customers table:
Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select
data from.
The table_name represents the name of the table you want to select data from.
Demo Database
Below is a selection from the Customers table used in the examples:
CustomerI CustomerNa ContactNa Address City PostalCo Countr
D me me de y
Example
Return all the columns from the Customers table:
Submit Answer »
Example
Select all the different countries from the "Customers" table:
Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.
Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Demo Database
Below is a selection from the Customers table used in the examples:
Example
SELECT Country FROM Customers;
Count Distinct
By using the DISTINCT keyword in a function called COUNT, we can return the
number of different countries.
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
You will learn about the COUNT function later in this tutorial.
Submit Answer »
Example
Select all customers from Mexico:
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.!
Demo Database
Below is a selection from the Customers table used in the examples:
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Example
Select all customers with a CustomerID greater than 80:
Operator Description
= Equal
Submit Answer »
Example
Sort the products by price:
Demo Database
Below is a selection from the Products table used in the examples:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
Example
Sort the products from highest to lowest price:
Order Alphabetically
For string values the ORDER BY keyword will order alphabetically:
Example
Sort the products alphabetically by ProductName:
Alphabetically DESC
To sort the table reverse alphabetically, use the DESC keyword:
Example
Sort the products by ProductName in reverse order:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Submit Answer »
SQL AND Operator
The AND operator is used to filter records based on more than one condition, like
if you want to return all customers from Spain that starts with the letter 'G':
Example
Select all customers from Spain that starts with the letter 'G':
SELECT *
FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
AND vs OR
The AND operator displays a record if all the conditions are TRUE.
Demo Database
Below is a selection from the Customers table used in the examples:
CustomerI CustomerNa ContactNa Address City PostalCo Countr
D me me de y
Example
SELECT * FROM Customers
WHERE Country = 'Germany'
AND City = 'Berlin'
AND PostalCode > 12000;
Combining AND and OR
You can combine the AND and OR operators.
The following SQL statement selects all customers from Spain that starts with a
"G" or an "R".
Example
Select all Spanish customers that starts with either "G" or "R":
Without parenthesis, the select statement will return all customers from Spain
that starts with a "G", plus all customers that starts with an "R", regardless of
the country value:
Example
Select all customers that either:
are from Spain and starts with either "G", or
starts with the letter "R":
Submit Answer »
SQL OR Operator
The OR operator is used to filter records based on more than one condition, like
if you want to return all customers from Germany but also those from Spain:
Example
Select all customers from Germany or Spain:
SELECT *
FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
OR vs AND
The OR operator displays a record if any of the conditions are TRUE.
The AND operator displays a record if all the conditions are TRUE.
Demo Database
Below is a selection from the Customers table used in the examples:
Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country = 'Norway';
The following SQL statement selects all customers from Spain that starts with a
"G" or an "R".
Example
Select all Spanish customers that starts with either "G" or "R":
Without parenthesis, the select statement will return all customers from Spain
that starts with a "G", plus all customers that starts with an "R", regardless of
the country value:
Example
Select all customers that either:
are from Spain and starts with either "G", or
starts with the letter "R":
_____________._____________ = '_____________';
Submit Answer »
In the select statement below we want to return all customers that are NOT
from Spain:
Example
Select only the customers that are NOT from Spain:
SELECT * FROM Customers
WHERE NOT Country = 'Spain';
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Demo Database
Below is a selection from the Customers table used in the examples:
NOT LIKE
Example
Select customers that does not start with the letter 'A':
NOT BETWEEN
Example
Select customers with a customerID not between 10 and 60:
NOT IN
Example
Select customers that are not from Paris or London:
Note: There is a not-greater-than operator: !> that would give you the same
result.
Note: There is a not-less-than operator: !< that would give you the same
result.
Submit Answer »
SQL INSERT INTO Statement
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:
Demo Database
Below is a selection from the Customers table used in the examples:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
Did you notice that we did not insert any number into the CustomerID
field?
The CustomerID column is an auto-increment field and will be generated
automatically when a new record is inserted into the table.
The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
To insert multiple rows of data, we use the same INSERT INTO statement, but with
multiple values:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien
15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1
0AA', 'UK');
The selection from the "Customers" table will now look like this:
Submit Answer »
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the Customers table used in the examples:
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Submit Answer »
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be
updated. If you omit the WHERE clause, all records in the table will be updated!
Demo Database
Below is a selection from the Customers table used in the examples:
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with
a new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
Example
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
_____________ Customers
_____________ City = 'Oslo';
Submit Answer »
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!
Demo Database
Below is a selection from the Customers table used in the examples:
CustomerI CustomerNa ContactNa Address City PostalCo Countr
D me me de y
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The following SQL statement deletes all rows in the "Customers" table, without
deleting the table:
Example
DELETE FROM Customers;
Delete a Table
To delete the table completely, use the DROP TABLE statement:
Example
Remove the Customers table:
_____________ Customers
_____________ Country = 'Norway';
Submit Answer »
The SELECT TOP clause is useful on large tables with thousands of records.
Returning a large number of records can impact performance.
Example
Select only the first 3 records of the Customers table:
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.
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s)
)
WHERE ROWNUM <= number;
Demo Database
Below is a selection from the Customers table used in the examples:
CustomerI CustomerNa ContactNa Address City PostalCo Countr
D me me de y
LIMIT
The following SQL statement shows the equivalent example for MySQL:
Example
Select the first 3 records of the Customers table:
Example
Select the first 3 records of the Customers table:
Example
SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
Example
Sort the result reverse alphabetically by CustomerName, and return the first 3
records:
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
ORDER BY CustomerName DESC
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;
MIN Example
Find the lowest price in the Price column:
SELECT MIN(Price)
FROM Products;
MAX Example
Find the highest price in the Price column:
SELECT MAX(Price)
FROM Products;
Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the Products table used in the examples:
1 Chais 1 1 10 boxes 18
x 20 bags
2 Chang 1 1 24 - 12 19
oz bottles
4 Chef Anton's 2 2 48 - 6 oz 22
Cajun jars
Seasoning
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
You will learn more about the GROUP BY clause later in this tutorial.
SELECT _____________
FROM Products;
Submit Answer »
Example
Find the total number of rows in the Products table:
SELECT COUNT(*)
FROM Products;
Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the Products table used in the examples:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
If you specify a column name instead of (*), NULL values will not be counted.
Example
Find the number of products where the ProductName is not null:
SELECT COUNT(ProductName)
FROM Products;
Example
Find the number of products where Price is higher than 20:
SELECT COUNT(ProductID)
FROM Products
WHERE Price > 20;
Ignore Duplicates
You can ignore duplicates by using the DISTINCT keyword in the COUNT() function.
If DISTINCT is specified, rows with the same value for the specified column will be
counted as one.
Example
How many different prices are there in the Products table:
SELECT COUNT(DISTINCT Price)
FROM Products;
Use an Alias
Give the counted column a name by using the AS keyword.
Example
Name the column "Number of records":
Example
SELECT COUNT(*) AS [Number of records], CategoryID
FROM Products
GROUP BY CategoryID;
You will learn more about the GROUP BY clause later in this tutorial.
Example
Return the sum of all Quantity fields in the OrderDetails table:
SELECT SUM(Quantity)
FROM OrderDetails;
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the OrderDetails table used in the examples:
OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
Example
Return the sum of the Quantity field for the product with ProductID 11:
SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
Use an Alias
Give the summarized column a name by using the AS keyword.
Example
Name the column "total":
Example
SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;
You will learn more about the GROUP BY clause later in this tutorial.
Example
Use an expression inside the SUM() function:
Example
Join OrderDetails with Products, and use SUM() to find the total amount:
SELECT _____________
FROM Products;
Submit Answer »
SELECT AVG(Price)
FROM Products;
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the Products table used in the examples:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
Example
Return the average price of products in category 1:
SELECT AVG(Price)
FROM Products
WHERE CategoryID = 1;
Use an Alias
Give the AVG column a name by using the AS keyword.
Example
Name the column "average price":
Example
Return all products with a higher price than the average price:
SELECT * FROM Products
WHERE price > (SELECT AVG(price) FROM Products);
Example
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;
You will learn more about the GROUP BY clause later in this tutorial.
SELECT _____________
FROM Products;
Submit Answer »
There are two wildcards often used in conjunction with the LIKE operator:
Example
Select all customers that starts with the letter "a":
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Demo Database
Below is a selection from the Customers table used in the examples:
The _ Wildcard
The _ wildcard represents a single character.
It can be any character or number, but each _ represents one, and only one,
character.
Example
Return all customers from a city that starts with 'L' followed by one wildcard
character, then 'nd' and then two wildcard characters:
Example
Return all customers from a city that contains the letter 'L':
Starts With
To return records that starts with a specific letter or phrase, add the % at the
end of the letter or phrase.
Example
Return all customers that starts with 'La':
Tip: You can also combine any number of conditions using AND or OR operators.
Example
Return all customers that starts with 'a' or starts with 'b':
Ends With
To return records that ends with a specific letter or phrase, add the % at the
beginning of the letter or phrase.
Example
Return all customers that ends with 'a':
Tip: You can also combine "starts with" and "ends with":
Example
Return all customers that starts with "b" and ends with "s":
Contains
To return records that contains a specific letter or phrase, add the % both before
and after the letter or phrase.
Example
Return all customers that contains the phrase 'or'
Combine Wildcards
Any wildcard, like % and _ , can be used in combination with other wildcards.
Example
Return all customers that starts with "a" and are at least 3 characters in length:
Without Wildcard
If no wildcard is specified, the phrase has to have an exact match to return a
result.
Example
Return all customers from Spain:
Submit Answer »
SQL Wildcards
Wildcard characters are used with the LIKE operator. The LIKE operator is used
in a WHERE clause to search for a specified pattern in a column.
Example
Return all customers that starts with the letter 'a':
Wildcard Characters
Symbol Description
Demo Database
Below is a selection from the Customers table used in the examples:
Example
Return all customers that ends with the pattern 'es':
Example
Return all customers that contains the pattern 'mer':
It can be any character or number, but each _ represents one, and only one,
character.
Example
Return all customers with a City starting with any character, followed by
"ondon":
Example
Return all customers with a City starting with "L", followed by any 3 characters,
ending with "on":
SELECT * FROM Customers
WHERE City LIKE 'L___on';
Example
Return all customers starting with either "b", "s", or "p":
Example
Return all customers starting with "a", "b", "c", "d", "e" or "f":
Combine Wildcards
Any wildcard, like % and _ , can be used in combination with other wildcards.
Example
Return all customers that starts with "a" and are at least 3 characters in length:
Without Wildcard
If no wildcard is specified, the phrase has to have an exact match to return a
result.
Example
Return all customers from Spain:
* Represents zero or more bl* finds bl, black, blue, and blob
characters
[] Represents any single h[oa]t finds hot and hat, but not
character within the brackets hit
! Represents any character not h[!oa]t finds hit, but not hot and
in the brackets hat
# Represents any single numeric 2#5 finds 205, 215, 225, 235,
character 245, 255, 265, 275, 285, and
295
Submit Answer »
SQL IN Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
Example
Return all customers from 'Germany', 'France', or 'UK'
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Demo Database
Below is a selection from the Customers table used in the examples:
NOT IN
By using the NOT keyword in front of the IN operator, you return all records that
are NOT any of the values in the list.
Example
Return all customers that are NOT from 'Germany', 'France', or 'UK':
IN (SELECT)
You can also use IN with a subquery in the WHERE clause.
With a subquery you can return all records from the main query that are
present in the result of the subquery.
Example
Return all customers that have an order in the Orders table:
SELECT * FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders);
NOT IN (SELECT)
The result in the example above returned 74 records, that means that there are
17 customers that haven't placed any orders.
Example
Return all customers that have NOT placed any orders in the Orders table:
Submit Answer »
The BETWEEN operator is inclusive: begin and end values are included.
Example
Selects all products with a price between 10 and 20:
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
Below is a selection from the Products table used in the examples:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
3 Aniseed Syrup 1 2 12 - 550 ml 10
bottles
NOT BETWEEN
To display the products outside the range of the previous example, use NOT
BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN
The following SQL statement selects all products with a price between 10 and
20. In addition, the CategoryID must be either 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID IN (1,2,3);
BETWEEN Text Values
The following SQL statement selects all products with a ProductName
alphabetically between Carnarvon Tigers and Mozzarella di Giovanni:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName between
Carnarvon Tigers and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
BETWEEN Dates
The following SQL statement selects all orders with an OrderDate between '01-
July-1996' and '31-July-1996':
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
Sample Table
Below is a selection from the Orders table used in the examples:
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
Test Yourself With Exercises
Exercise:
Use the BETWEEN operator to select all the records where the value of the Price column
is between 10 and 20.
Submit Answer »
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Example
SELECT CustomerID AS ID
FROM Customers;
AS is Optional
Actually, in most database languages, you can skip the AS keyword and get the
same result:
Example
SELECT CustomerID ID
FROM Customers;
Syntax
When alias is used on column:
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
Below is a selection from the Customers and Orders tables used in the
examples:
Customers
Orders
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Using Aliases With a Space Character
If you want your alias to contain one or more spaces, like "My Great Products",
surround your alias with square brackets or double quotes.
Example
Using [square brackets] for aliases with space characters:
Example
Using "double quotes" for aliases with space characters:
Note: Some database systems allows both [] and "", and some only allows one
of them.
Concatenate Columns
The following SQL statement creates an alias named "Address" that combine
four columns (Address, PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
MySQL Example
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,',
',Country) AS Address
FROM Customers;
Note: To get the SQL statement above to work in Oracle use the following:
Oracle Example
SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ',
' || Country) AS Address
FROM Customers;
Example
Refer to the Customers table as Persons instead:
It might seem useless to use aliases on tables, but when you are using more
than one table in your queries, it can make the SQL statements shorter.
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 use
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 following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;
SELECT CustomerName,
Address,
PostalCode _____________
FROM Customers;
Submit Answer »
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
(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
Test Yourself With Exercises
Exercise:
Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,
using the CustomerID field in both tables as the relationship between the two tables.
SELECT *
FROM Orders
LEFT JOIN Customers
_____________=_____________;
Submit Answer »
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both
tables.
2 Chang 1 19
3 Aniseed Syrup 2 10
We will join the Products table with the Categories table, by using
the CategoryID field from both tables:
Example
Join Products and Categories with the INNER JOIN keyword:
Note: The INNER JOIN keyword returns only rows with a match in both tables.
Which means that if you have a product with no CategoryID, or with a
CategoryID that is not present in the Categories table, that record would not be
returned in the result.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
Specify the table names:
The example above works without specifying table names, because none of the
specified column names are present in both tables. If you try to
include CategoryID in the SELECT statement, you will get an error if you do not
specify the table name (because CategoryID is present in both tables).
INNER is the default join type for JOIN, so when you write JOIN the parser actually
writes INNER JOIN.
Example
JOIN is the same as INNER JOIN:
SELECT Products.ProductID, Products.ProductName, Categories.CategoryName
FROM Products
JOIN Categories ON Products.CategoryID = Categories.CategoryID;
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
SELECT *
FROM Orders
_____________
ON Orders.CustomerID=Customers.CustomerID;
Submit Answer »
SQL LEFT JOIN Keyword
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers),
even if there are no matches in the right table (Orders).
SQL RIGHT JOIN Keyword
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
Test Yourself With Exercises
Exercise:
Choose the correct JOIN clause to select all the records from the Customers table plus
all the matches in the Orders table.
SELECT *
FROM Orders
_____________
ON Orders.CustomerID=Customers.CustomerID;
Submit Answer »
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
CustomerName OrderID
Null 10309
Null 10310
Note: The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Customers"
that do not have matches in "Orders", or if there are rows in "Orders" that do
not have matches in "Customers", those rows will be listed as well.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
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;
Note: The column names in the result-set are usually equal to the column
names in the first SELECT statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
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!
SQL UNION ALL Example
The following SQL statement returns the cities (duplicate values also) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Another UNION Example
The following SQL statement lists all customers and suppliers:
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table
or a column a temporary name. An alias only exists for the duration of the
query. So, here we have created a temporary column named "Type", that list
whether the contact person is a "Customer" or a "Supplier".
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement lists the number of customers in each country,
sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
Submit Answer »
SQL HAVING Clause
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country,
sorted high to low (Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
The following SQL statement lists if the employees "Davolio" or "Fuller" have
registered more than 25 orders:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID
= Suppliers.supplierID AND Price < 20);
The following SQL statement returns TRUE and lists the suppliers with a product
price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID
= Suppliers.supplierID AND Price = 22);
ANY means that the condition will be true if the operation is true for any of the
values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).
The SQL ALL Operator
The ALL operator:
ALL means that the condition will be true only if the operation is true for all
values in the range.
Note: The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
8 Northwoods Cranberry 3 2 12 - 12 oz 40
Sauce jars
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
7 10250 51 35
8 10250 65 15
9 10251 22 6
10 10251 57 15
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 99 (this will return TRUE because
the Quantity column has some values larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 1000 (this will return FALSE
because the Quantity column has no values larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
Example
SELECT ALL ProductName
FROM Products
WHERE TRUE;
The following SQL statement lists the ProductName if ALL the records in the
OrderDetails table has Quantity equal to 10. This will of course return FALSE
because the Quantity column has many different values (not only the value of
10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in
the old table. You can create new column names using the AS clause.
SQL SELECT INTO Examples
The following SQL statement creates a backup copy of Customers:
The following SQL statement uses the IN clause to copy the table into a new
table in another database:
The following SQL statement copies only a few columns into a new table:
The following SQL statement copies only the German customers into a new
table:
The following SQL statement copies data from more than one table into a new
table:
Tip: SELECT INTO can also be used to create a new, empty table using the schema
of another. Just add a WHERE clause that causes the query to return no data:
The INSERT INTO SELECT statement requires that the data types in source and
target tables match.
Copy only some columns from one table into another table:
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
Copy "Suppliers" into "Customers" (fill all columns):
Example
Copy only the German suppliers into "Customers":
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
The following SQL will order the customers by City. However, if City is NULL,
then order by Country:
Example
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL
values.
In the example above, if any of the "UnitsOnOrder" values are NULL, the result
will be NULL.
Solutions
MySQL
SQL Server
The SQL Server ISNULL() function lets you return an alternative value when an
expression is NULL:
MS Access
The MS Access IsNull() function returns TRUE (-1) if the expression is a null
value, otherwise FALSE (0):
Oracle
So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Example
EXEC SelectAllCustomers;
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Example
EXEC SelectAllCustomers @City = 'London';
Stored Procedure With Multiple
Parameters
Setting up multiple parameters is very easy. Just list each parameter and the
data type separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers
from a particular City with a particular PostalCode from the "Customers" table:
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
Example
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';
SQL Comments
SQL Comments
Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
Any text between -- and the end of the line will be ignored (will not be
executed).
The following example uses a single-line comment as an explanation:
Example
-- Select all:
SELECT * FROM Customers;
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
Example
-- SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
Example
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;
SQL Operators
+ Add
- Subtract
* Multiply
/ Divide
% Modulo
| Bitwise OR
^ Bitwise exclusive OR
= Equal to
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= Bitwise AND equals
SQL DATABASE
SQL CREATE
DATABASE Statement
Syntax
CREATE DATABASE databasename;
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
_____________;
Submit Answer »
Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result in
loss of complete information stored in the database!
DROP DATABASE Example
The following SQL statement drops the existing database "testDB":
Example
DROP DATABASE testDB;
Tip: Make sure you have admin privilege before dropping any database. Once a
database is dropped, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
Exercise:
Write the correct SQL statement to delete a database named testDB.
Submit Answer »
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
The SQL BACKUP WITH DIFFERENTIAL
Statement
A differential back up only backs up the parts of the database that have
changed since the last full database backup.
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Tip: Always back up the database to a different drive than the actual database.
Then, if you get a disk crash, you will not lose your backup file along with the
database.
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are
backed up).
SQL CREATE TABLE Statement
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Tip: For an overview of the available data types, go to our complete Data Types
Reference.
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Tip: The empty "Persons" table can now be filled with data with the
SQL INSERT INTO statement.
The new table gets the same column definitions. All columns or specific columns
can be selected.
If you create a new table using an existing table, the new table will be filled
with the existing values from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of
the "Customers" table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
Test Yourself With Exercises
Exercise:
Write the correct SQL statement to create a new table called Persons.
_____________ (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Submit Answer »
Note: Be careful before dropping a table. Deleting a table will result in loss of
complete information stored in the table!
Example
DROP TABLE Shippers;
Syntax
TRUNCATE TABLE table_name;
_____________ Persons;
Submit Answer »
SQL ALTER TABLE Statement
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
SQL Server:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a
date. The data type specifies what type of data the column can hold. For a
complete reference of all the data types available in MS Access, MySQL, and
SQL Server, go to our complete Data Types reference.
Notice that the "DateOfBirth" column is now of type year and is going to hold a
year in a two- or four-digit format.
_____________ Persons
_____________;
Submit Answer »
SQL Constraints
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
MySQL:
MySQL:
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
MySQL:
Note: If you use ALTER TABLE to add a primary key, the primary key column(s)
must have been declared to not contain NULL values (when the table was first
created).
MySQL:
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the
parent table.
MySQL:
MySQL:
If you define a CHECK constraint on a column it will allow only certain values for
this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
MySQL:
The default value will be added to all new records, if no other value is specified.
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
MySQL:
SQL Server:
MS Access:
Oracle:
MySQL:
SQL Server:
Indexes are used to retrieve data from the database more quickly than
otherwise. The users cannot see the indexes, they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.
Syntax for MySQL
The following SQL statement defines the "Personid" column to be an auto-
increment primary key field in the "Persons" table:
To let the AUTO_INCREMENT sequence start with another value, use the following
SQL statement:
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" column (a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
In the example above, the starting value for IDENTITY is 1, and it will increment
by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and
increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" column (a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for
each new record.
Tip: To specify that the "Personid" column should start at value 10 and
increment by 5, change the autoincrement to AUTOINCREMENT(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
You will have to create an auto-increment field with the sequence object (this
object generates a number sequence).
The code above creates a sequence object called seq_person, that starts with 1
and will increment by 1. It will also cache up to 10 values for performance. The
cache option specifies how many sequence values will be stored in memory for
faster access.
To insert a new record into the "Persons" table, we will have to use the nextval
function (this function retrieves the next value from seq_person sequence):
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned the next number from the seq_person
sequence. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".
As long as your data contains only the date portion, your queries will work as
expected. However, if a time portion is involved, it gets more complicated.
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
Note: The date types are chosen for a column when you create a new table in
your database!
Orders Table
Now we want to select the records with an OrderDate of "2008-11-11" from the
table above.
1 Geitost 2008-11-11
Now, assume that the "Orders" table looks like this (notice the added time-
component in the "OrderDate" column):
we will get no result! This is because the query is looking only for dates with no
time portion.
Tip: To keep your queries simple and easy to maintain, do not use time-
components in your dates, unless you have to!
SQL Views
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if
the data were coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates the
view, every time a user queries it.
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Example
SELECT * FROM [Brazil Customers];
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Example
SELECT * FROM [Products Above Average Price];
SQL Updating a View
A view can be updated with the CREATE OR REPLACE VIEW statement.
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Example
DROP VIEW [Brazil Customers];
SQL Injection
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via web
page input.
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user input in
SQL statements.
If there is nothing to prevent a user from entering "wrong" input, the user can
enter some "smart" input like this:
105 OR 1=1
UserId:
The SQL above is valid and will return ALL rows from the "Users" table,
since OR 1=1 is always TRUE.
Does the example above look dangerous? What if the "Users" table contains
names and passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and passwords in a database,
by simply inserting 105 OR 1=1 into the input field.
Username:
John Doe
Password:
myPass
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
User Name:
Password:
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR
""="" is always TRUE.
The SQL statement below will return all rows from the "Users" table, then delete
the "Suppliers" table.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
105; DROP
User id:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
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);
Examples
The following examples shows how to build parameterized queries in some
common web languages.
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserId);
command.ExecuteReader();
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
INSERT INTO STATEMENT IN PHP:
SQL Hosting
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.
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.
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.
The data type of a column defines what value the column can hold: integer,
character, money, date and time, binary, and so on.
An SQL developer must decide what type of data that will be stored inside each
column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
Note: Data types might have different names in different database. And even if
the name is the same, the size and other details may be different! Always
check the documentation!
MySQL Data Types (Version 8.0)
In MySQL there are three main data types: string, numeric, and date and time.
CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1
TINYBLOB For BLOBs (Binary Large Objects). Max length: 255 bytes
ENUM(val1, val2, A string object that can have only one value, chosen from a list
val3, ...) of possible values. You can list up to 65535 values in an ENUM
list. If a value is inserted that is not in the list, a blank value will
be inserted. The values are sorted in the order you enter them
SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list
of possible values. You can list up to 64 values in a SET list
DOUBLE
PRECISION(size, d)
Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also adds
the UNSIGNED attribute to the column.
5-17
decimal(p,s) Fixed precision and scale numbers. bytes
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 8 bytes
3.33 milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 6-8
100 nanoseconds bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5
bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes
timestamp Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an
internal clock and does not correspond to real time. Each table
may have only one timestamp variable
Text Use for text or combinations of text and numbers. 255 characters
maximum
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 8 bytes
decimal places. Tip: You can choose which country's currency
to use
AutoNumber AutoNumber fields automatically give each record its own 4 bytes
number, usually starting at 1
Date/Time Use for dates and times 8 bytes
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large up to
Objects) 1GB
Lookup Let you type a list of options, which can then be chosen from a 4 bytes
Wizard drop-down list
SQL Keywords
Keyword Description
FULL OUTER JOIN Returns all rows when there is a match in either left
table or right table
INSERT INTO Copies data from one table into another table
SELECT
LEFT JOIN Returns all rows from the left table, and the matching
rows from the right table
OUTER JOIN Returns all rows when there is a match in either left
table or right table
RIGHT JOIN Returns all rows from the right table, and the
matching rows from the left table
SELECT INTO Copies data from one table into a new table
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
ADD
The ADD command is used to add a column in an existing table.
Example
Add an "Email" column to the "Customers" table:
ADD CONSTRAINT
The ADD CONSTRAINT command is used to create a constraint after a table is
already created.
The following SQL adds a constraint named "PK_Person" that is a PRIMARY KEY
constraint on multiple columns (ID and LastName):
Example
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
ALTER TABLE
The ALTER TABLE command adds, deletes, or modifies columns in a table.
The ALTER TABLE command also adds and deletes various constraints in a table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
ALTER COLUMN
The ALTER COLUMN command is used to change the data type of a column in a
table.
The following SQL changes the data type of the column named "BirthDate" in
the "Employees" table to type year:
Example
ALTER TABLE Employees
ALTER COLUMN BirthDate year;
ALTER COLUMN
The ALTER COLUMN command is used to change the data type of a column in a
table.
The following SQL changes the data type of the column named "BirthDate" in
the "Employees" table to type year:
Example
ALTER TABLE Employees
ALTER COLUMN BirthDate year;
ALTER TABLE
The ALTER TABLE command adds, deletes, or modifies columns in a table.
The ALTER TABLE command also adds and deletes various constraints in a table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
AND
The AND command is used with WHERE to only include rows where both
conditions is true.
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';
ANY
The ANY command returns true if any of the subquery values meet the
condition.
The following SQL statement returns TRUE and lists the productnames if it finds
ANY records in the OrderDetails table where quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
The following SQL statement returns TRUE and lists the productnames if it finds
ANY records in the OrderDetails table where quantity > 99:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
> 99);
SQL AS Keyword
AS
The AS command is used to rename a column or table with an alias.
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
The following SQL statement creates two aliases. Notice that it requires double
quotation marks or square brackets if the alias name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
The following SQL statement creates an alias named "Address" that combine
four columns (Address, PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;
ASC
The ASC command is used to sort the data returned in ascending order.
The following SQL statement selects all the columns from the "Customers"
table, sorted by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY CustomerName ASC;
SQL BACKUP DATABASE Keyword
BACKUP DATABASE
The BACKUP DATABASE command is used in SQL Server to create a full back up of
an existing SQL database.
The following SQL statement creates a full back up of the existing database
"testDB" to the D disk:
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Tip: Always back up the database to a different drive than the actual database.
If you get a disk crash, you will not lose your backup file along with the
database.
A differential back up only backs up the parts of the database that have
changed since the last full database backup.
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are
backed up).
The BETWEEN command is inclusive: begin and end values are included.
The following SQL statement selects all products with a price BETWEEN 10 and
20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use NOT
BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
The following SQL statement selects all products with a ProductName BETWEEN
'Carnarvon Tigers' and 'Mozzarella di Giovanni':
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
CASE
The CASE command is used is to create different output based on conditions.
The following SQL goes through several conditions and returns a value when the
specified condition is met:
Example
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END
FROM OrderDetails;
The following SQL will order the customers by City. However, if City is NULL,
then order by Country:
Example
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
CHECK
The CHECK constraint limits the value that can be placed in a column.
MySQL:
MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
ALTER COLUMN
The ALTER COLUMN command is used to change the data type of a column in a
table.
The following SQL changes the data type of the column named "BirthDate" in
the "Employees" table to type year:
Example
ALTER TABLE Employees
ALTER COLUMN BirthDate year;
DROP COLUMN
The DROP COLUMN command is used to delete a column in an existing table.
The following SQL deletes the "ContactName" column from the "Customers"
table:
Example
ALTER TABLE Customers
DROP COLUMN ContactName;
The following SQL adds a constraint named "PK_Person" that is a PRIMARY KEY
constraint on multiple columns (ID and LastName):
Example
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
DROP CONSTRAINT
The DROP CONSTRAINT command is used to delete a UNIQUE, PRIMARY KEY,
FOREIGN KEY, or CHECK constraint.
MySQL:
MySQL:
MySQL:
CREATE DATABASE
The CREATE DATABASE command is used is to create a new SQL database.
The following SQL creates a database called "testDB":
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
CREATE TABLE
The CREATE TABLE command creates a new table in the database.
The following SQL creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
CREATE INDEX
The CREATE INDEX command is used to create indexes in tables (allows duplicate
values).
Indexes are used to retrieve data from the database very fast. The users cannot
see the indexes, they are just used to speed up searches/queries.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
The following SQL creates an index named "uidx_pid" on the "PersonID" column
in the "Persons" table:
CREATE VIEW
The CREATE VIEW command creates a view.
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = "Brazil";
Example
SELECT * FROM [Brazil Customers];
CREATE PROCEDURE
The CREATE PROCEDURE command is used to create a stored procedure.
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
Example
EXEC SelectAllCustomers;
CREATE DATABASE
The CREATE DATABASE command is used is to create a new SQL database.
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
CREATE INDEX
The CREATE INDEX command is used to create indexes in tables (allows duplicate
values).
Indexes are used to retrieve data from the database very fast. The users cannot
see the indexes, they are just used to speed up searches/queries.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = "Brazil";
Query The View
We can query the view above as follows:
Example
SELECT * FROM [Brazil Customers];
CREATE TABLE
The CREATE TABLE command creates a new table in the database.
The following SQL creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
SQL CREATE PROCEDURE
Keyword
CREATE PROCEDURE
The CREATE PROCEDURE command is used to create a stored procedure.
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Example
EXEC SelectAllCustomers;
The following SQL creates an index named "uidx_pid" on the "PersonID" column
in the "Persons" table:
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
CREATE VIEW
The CREATE VIEW command creates a view.
The following SQL creates a view that selects all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
Example
SELECT * FROM [Brazil Customers];
SQL DATABASE Keyword
CREATE DATABASE
The CREATE DATABASE command is used is to create a new SQL database.
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
DROP DATABASE
The DROP DATABASE command is used is to delete an existing SQL database.
Example
DROP DATABASE testDB;
The default value will be added to all new records if no other value is specified.
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
MySQL:
SQL Server:
MS Access:
MySQL:
DELETE
The DELETE command is used to delete existing records in a table.
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
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!
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:
The following SQL statement deletes all rows in the "Customers" table, without
deleting the table. This means that the table structure, attributes, and indexes
will be intact:
Example
DELETE FROM Customers;
DESC
The DESC command is used to sort the data returned in descending order.
The following SQL statement selects all the columns from the "Customers"
table, sorted descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY CustomerName DESC;
SELECT DISTINCT
The SELECT DISTINCT command returns only distinct (different) values in the
result set.
The following SQL statement selects only the DISTINCT values from the
"Country" column in the "Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
The following SQL deletes the "ContactName" column from the "Customers"
table:
Example
ALTER TABLE Customers
DROP COLUMN ContactName;
MySQL:
MySQL:
MySQL:
MySQL:
DROP DEFAULT
The DROP DEFAULT command is used to delete a DEFAULT constraint.
MySQL:
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
DROP DATABASE
The DROP DATABASE command is used is to delete an existing SQL database.
Example
DROP DATABASE testDB;
DROP TABLE
The DROP TABLE command deletes a table in the database.
Note: Be careful before deleting a table. Deleting a table results in loss of all
information stored in the table!
DROP VIEW
The DROP VIEW command deletes a view.
Example
DROP VIEW [Brazil Customers];
DROP COLUMN
The DROP COLUMN command is used to delete a column in an existing table.
The following SQL deletes the "ContactName" column from the "Customers"
table:
Example
ALTER TABLE Customers
DROP COLUMN ContactName;
MySQL:
MySQL:
MySQL:
MySQL:
DROP DATABASE
The DROP DATABASE command is used to delete an existing SQL database.
Example
DROP DATABASE testDB;
DROP DEFAULT
The DROP DEFAULT command is used to delete a DEFAULT constraint.
MySQL:
DROP INDEX
The DROP INDEX command is used to delete an index in a table.
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
ALTER TABLE table_name
DROP INDEX index_name;
DROP TABLE
The DROP TABLE command deletes a table in the database.
Example
DROP TABLE Shippers;
Note: Be careful before deleting a table. Deleting a table results in loss of all
information stored in the table!
TRUNCATE TABLE
The TRUNCATE TABLE command deletes the data inside a table, but not the table
itself.
Example
TRUNCATE TABLE Categories;
Example
DROP VIEW [Brazil Customers];
EXEC
The EXEC command is used to execute a stored procedure.
Example
EXEC SelectAllCustomers;
EXISTS
The EXISTS command tests for the existence of any record in a subquery, and
returns true if the subquery returns one or more records.
The following SQL lists the suppliers with a product price less than 20:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId =
Suppliers.supplierId AND Price < 20);
The following SQL lists the suppliers with a product price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId =
Suppliers.supplierId AND Price = 22);
FOREIGN KEY
The FOREIGN KEY constraint is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL:
FROM
The FROM command is used to specify which table to select or delete data from.
The following SQL statement selects the "CustomerName" and "City" columns
from the "Customers" table:
Example
SELECT CustomerName, City FROM Customers;
The following SQL statement selects all the columns from the "Customers"
table:
Example
SELECT * FROM Customers;
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';
The following SQL statement selects all customers, and all orders:
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.
GROUP BY
The GROUP BY command is used to group the result set (used with aggregate
functions: COUNT, MAX, MIN, SUM, AVG).
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL lists the number of customers in each country, sorted high to
low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
HAVING
The HAVING command is used instead of WHERE with aggregate functions.
The following SQL lists the number of customers in each country. Only include
countries with more than 5 customers:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL lists the number of customers in each country, sorted high to
low (Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
SQL IN Keyword
IN
The IN command allows you to specify multiple values in a WHERE clause.
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL selects all customers that are NOT located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL selects all customers that are from the same countries as the
suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
CREATE INDEX
The CREATE INDEX command is used to create indexes in tables (allows duplicate
values).
Indexes are used to retrieve data from the database very fast. The users cannot
see the indexes, they are just used to speed up searches/queries.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.
DROP INDEX
The DROP INDEX command is used to delete an index in a table.
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
INNER JOIN
The INNER JOIN command returns rows that have matching values in both
tables.
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!
The following SQL statement selects all orders with customer and shipper
information:
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
INSERT INTO
The INSERT INTO command is used to insert new rows in a table.
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
The following SQL will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
SQL INSERT INTO SELECT
Keyword
The following SQL copies "Suppliers" into "Customers" (the columns that are not
filled with data, will contain NULL):
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
The following SQL copies "Suppliers" into "Customers" (fill all columns):
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
SELECT SupplierName, ContactName, Address, City,
PostalCode, Country FROM Suppliers;
The following SQL copies only the German suppliers into "Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
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!
IS NOT NULL
The IS NOT NULL command is used to test for non-empty values (NOT NULL
values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are records in the "Orders" table
that do not have matches in "Customers", these orders will not be shown!
The following SQL statement selects all orders with customer and shipper
information:
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
LEFT JOIN
The LEFT JOIN command returns all rows from the left table, and the matching
rows from the right table. The result is NULL from the right side, if there is no
match.
The following SQL will select 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;
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
The RIGHT JOIN command returns all rows from the right table, and the
matching records from the left table. The result is NULL from the left side, when
there is no match.
The following SQL will return all employees, and any orders they might have
placed:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
The following SQL statement selects all customers, and all orders:
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 following SQL will select 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;
Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
LIKE
The LIKE command is used in a WHERE clause to search for a specified pattern
in a column.
The following SQL selects all customers with a CustomerName starting with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL selects all customers with a CustomerName ending with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL selects all customers with a CustomerName that have "or" in
any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that
starts with "a" and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Note: SQL Server uses SELECT TOP. MySQL uses LIMIT, and Oracle
uses ROWNUM.
The following SQL statement selects the first three records from the
"Customers" table (SQL SERVER):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT
clause (MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM
(Oracle):
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
Note: SQL Server uses SELECT TOP. MySQL uses LIMIT, and Oracle
uses ROWNUM.
The following SQL statement selects the first three records from the
"Customers" table (SQL SERVER):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT
clause (MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM
(Oracle):
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
NOT NULL
The NOT NULL constraint enforces a column to not accept NULL values, which
means that you cannot insert or update a record without adding a value to this
field.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns
will NOT accept NULL values:
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
The following SQL creates a NOT NULL constraint on the "Age" column when the
"Persons" table is already created:
SQL OR Keyword
OR
The OR command is used with WHERE to include rows where either condition is
true.
The following SQL statement selects all fields from "Customers" where city is
"Berlin" OR city is "München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
ORDER BY
The ORDER BY command is used to sort the result set in ascending or descending
order.
The ORDER BY command sorts the result set in ascending order by default. To
sort the records in descending order, use the DESC keyword.
The following SQL statement selects all the columns from the "Customers"
table, sorted by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY CustomerName;
ASC
The ASC command is used to sort the data returned in ascending order.
The following SQL statement selects all the columns from the "Customers"
table, sorted by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY CustomerName ASC;
DESC
The DESC command is used to sort the data returned in descending order.
The following SQL statement selects all the columns from the "Customers"
table, sorted descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY CustomerName DESC;
The following SQL statement selects all customers, and all orders:
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.
SQL PRIMARY KEY Keyword
PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a table.
A table can have only one primary key, which may consist of one single or of
multiple fields.
MySQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: If you use the ALTER TABLE statement to add a primary key, the primary
key column(s) must already have been declared to not contain NULL values
(when the table was first created).
MySQL:
CREATE PROCEDURE
The CREATE PROCEDURE command is used to create a stored procedure.
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Example
EXEC SelectAllCustomers;
RIGHT JOIN
The RIGHT JOIN command returns all rows from the right table, and the
matching records from the left table. The result is NULL from the left side, when
there is no match.
The following SQL will return all employees, and any orders they might have
placed:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
Note: SQL Server uses SELECT TOP. MySQL uses LIMIT, and Oracle
uses ROWNUM.
The following SQL statement selects the first three records from the
"Customers" table (SQL SERVER):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT
clause (MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM
(Oracle):
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
SELECT
The SELECT command is used to select data from a database. The data returned
is stored in a result table, called the result set.
The following SQL statement selects the "CustomerName" and "City" columns
from the "Customers" table:
Example
SELECT CustomerName, City FROM Customers;
The following SQL statement selects all the columns from the "Customers"
table:
Example
SELECT * FROM Customers;
SELECT DISTINCT
The SELECT DISTINCT command returns only distinct (different) values in the
result set.
The following SQL statement selects only the DISTINCT values from the
"Country" column in the "Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
SELECT INTO
The SELECT INTO command copies data from one table and inserts it into a new
table.
The following SQL statement uses the IN clause to copy the table into a new
table in another database:
The following SQL statement copies only a few columns into a new table:
The following SQL statement copies only the German customers into a new
table:
The following SQL statement copies data from more than one table into a new
table:
Note: SQL Server uses SELECT TOP. MySQL uses LIMIT, and Oracle
uses ROWNUM.
The following SQL statement selects the first three records from the
"Customers" table (SQL SERVER):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT
clause (MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM
(Oracle):
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
The following SQL updates the first customer (CustomerID = 1) with a new
ContactName and a new City:
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The following SQL will update the "ContactName" field to "Juan" for all records
where Country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
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!
CREATE TABLE
The CREATE TABLE command creates a new table in the database.
The following SQL creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The following SQL creates a new table called "TestTables" (which is a copy of
the "Customers" table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
ALTER TABLE
The ALTER TABLE command adds, deletes, or modifies columns in a table.
The ALTER TABLE command also adds and deletes various constraints in a table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
DROP TABLE
The DROP TABLE command deletes a table in the database.
The following SQL deletes the table "Shippers":
Example
DROP TABLE Shippers;
Note: Be careful before deleting a table. Deleting a table results in loss of all
information stored in the table!
TRUNCATE TABLE
The TRUNCATE TABLE command deletes the data inside a table, but not the table
itself.
Example
TRUNCATE TABLE Categories;
Note: SQL Server uses SELECT TOP. MySQL uses LIMIT, and Oracle
uses ROWNUM.
The following SQL statement selects the first three records from the
"Customers" table (SQL SERVER):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT
clause (MySQL):
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM
(Oracle):
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
DROP TABLE
The DROP TABLE command deletes a table in the database.
Example
DROP TABLE Shippers;
Note: Be careful before deleting a table. Deleting a table results in loss of all
information stored in the table!
TRUNCATE TABLE
The TRUNCATE TABLE command deletes the data inside a table, but not the table
itself.
UNION
The UNION command combines the result set of two or more SELECT statements
(only distinct values)
The following SQL statement returns the cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
UNION ALL
The UNION ALL command combines the result set of two or more SELECT
statements (allows duplicate values).
The following SQL statement returns the cities (duplicate values also) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SQL UNIQUE Keyword
UNIQUE
The UNIQUE constraint ensures that all values in a column are unique.
MySQL:
MySQL:
The following SQL statement updates the first customer (CustomerID = 1) with
a new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The following SQL statement will update the contactname to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
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!
VALUES
The VALUES command specifies the values of an INSERT INTO statement.
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
The following SQL will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
CREATE VIEW
In SQL, a view is a virtual table based on the result set of an SQL statement.
The following SQL creates a view that selects all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
Example
SELECT * FROM [Brazil Customers];
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = "Brazil";
DROP VIEW
The DROP VIEW command deletes a view.
Example
DROP VIEW [Brazil Customers];
SELECT
The WHERE command filters a result set to include only records that fulfill a
specified condition.
The following SQL statement selects all the customers from "Mexico" in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
SQL requires single quotes around text values (most database systems will also
allow double quotes).
Note: The WHERE clause is not only used in SELECT statement, it is also used
in UPDATE, DELETE statement, etc.!
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may
be written as !=
MySQL Functions
This reference contains string, numeric, date, and some advanced functions
in MySQL.
LAST_DAY Extracts the last day of the month for a given date
YEARWEEK Returns the year and week number for a given date
CURRENT_USER Returns the user name and host name for the MySQL
account that the server used to authenticate the current
client
SYSTEM_USER Returns the current MySQL user name and host name
USER Returns the current MySQL user name and host name
UNICODE Returns the Unicode value for the first character of the
input expression
CURRENT_USER Returns the name of the current user in the SQL Server
database
SESSION_USER Returns the name of the current user in the SQL Server
database
MS Access Functions
This reference contains the string, numeric, and date functions in MS Access.
MS Access String Functions
Function Description
DateSerial Returns a date from the specified parts (year, month, and
day values)
or
or
SELECT column_name
FROM table_name AS table_alias
or
or
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO INSERT INTO table_name
VALUES (value1, value2, value3,....)
or
SELECT * SELECT *
FROM table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name