0% found this document useful (0 votes)
30 views

SQL (W3School)

Uploaded by

Sheeba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

SQL (W3School)

Uploaded by

Sheeba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

SQL Tutorial

SQL is a standard language for storing, manipulating and retrieving data in


databases.
https://www.w3schools.com/sql/sql_intro.asp

Introduction to SQL
What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO standard, there are different versions of the
SQL language.

However, to be compliant with the ANSI standard, they all support at least
the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a
similar manner.

Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:

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


 To use a server-side scripting language, like PHP or ASP
 To use SQL to get the data you want
 To use HTML / CSS to style the page

RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a


collection of related data entries and it consists of columns and rows.

Every table is broken up into smaller entities called fields. The fields in the
Customers table consist of CustomerID, CustomerName, ContactName,
Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.

A record, also called a row, is each individual entry that exists in a table. For
example, there are 91 records in the above Customers table. A record is a
horizontal entity in a table.

A column is a vertical entity in a table that contains all information associated


with a specific field in a table.

SQL Syntax
SQL Statements
SQL statements consists of keywords.

The following SQL statement returns all records from a table named
"Customers":

SELECT * FROM Customers;


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.

Keep in Mind That...


 SQL keywords are NOT case sensitive: select is the same as SELECT

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL
statement.

Semicolon is the standard way to separate each SQL statement in database


systems that allow more than one SQL statement to be executed in the same
call to the server.

Some of The Most Important SQL


Commands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SQL SELECT Statement


The SQL SELECT Statement
The SELECT statement is used to select data from a database.

SELECT CustomerName, City FROM Customers;

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.

Select ALL columns


If you want to return all columns, without specifying every column name,
you can use the SELECT * syntax:

SELECT * FROM Customers;

SQL SELECT
DISTINCT Statement
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different)
values.

SELECT DISTINCT Country FROM Customers;

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;

Count Distinct
By using the DISTINCT keyword in a function called COUNT, we can return the
number of different countries.

SELECT COUNT(DISTINCT Country) FROM Customers;

SQL WHERE Clause


The SQL WHERE Clause
The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

SELECT * FROM Customers


WHERE Country='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.!

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will
also allow double quotes).

However, numeric fields should not be enclosed in quotes:


SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause


You can use other operators than the = operator to filter the search.

SELECT * FROM Customers


WHERE CustomerID > 80;

The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be
written as !=

BETWEEN Between a certain range


LIKE Search for a pattern

IN To specify multiple possible values for a column

SQL ORDER BY Keyword


The SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.

SELECT * FROM Products


ORDER BY Price;

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

DESC
The ORDER BY keyword sorts the records in ascending order by default. To
sort the records in descending order, use the DESC keyword.

Example
Sort the products from highest to lowest price:

SELECT * FROM Products


ORDER BY Price DESC;
Order Alphabetically
For string values the ORDER BY keyword will order alphabetically:

Example
Sort the products alphabetically by ProductName:

SELECT * FROM Products


ORDER BY ProductName;

Alphabetically DESC
To sort the table reverse alphabetically, use the DESC keyword:

Example
Sort the products by ProductName in reverse order:

SELECT * FROM Products


ORDER BY ProductName DESC;

ORDER BY Several Columns


The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" and the "CustomerName" column. This means
that it orders by Country, but if some rows have the same Country, it orders
them by CustomerName:

Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Using Both ASC and DESC
The following SQL statement selects all customers from the "Customers"
table, sorted ascending by the "Country" and descending by the
"CustomerName" column:

Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

SQL AND Operator


The SQL AND Operator
The WHERE clause can contain one or many AND operators.

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.
The OR operator displays a record if any of the conditions are TRUE.

All Conditions Must Be True


The following SQL statement selects all fields
from Customers where Country is "Germany" AND City is "Berlin"
AND PostalCode is higher than 12000:

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".

Make sure you use parenthesis to get the correct result.

Example
Select all Spanish customers that starts with either "G" or "R":

SELECT * FROM Customers


WHERE Country = 'Spain' AND (CustomerName LIKE 'G
%' OR CustomerName LIKE '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":

SELECT * FROM Customers


WHERE Country = 'Spain' AND CustomerName LIKE 'G
%' OR CustomerName LIKE 'R%';

SQL OR Operator
The SQL OR Operator
The WHERE clause can contain one or more OR operators.

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.

At Least One Condition Must Be True


The following SQL statement selects all fields from Customers where
either City is "Berlin", CustomerName starts with the letter "G" or Country is
"Norway":

Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country = 'Norway';

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".

Make sure you use parenthesis to get the correct result.

Example
Select all Spanish customers that starts with either "G" or "R":

SELECT * FROM Customers


WHERE Country = 'Spain' AND (CustomerName LIKE 'G
%' OR CustomerName LIKE '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":
SELECT * FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G
%' OR CustomerName LIKE 'R%';

SQL NOT Operator


The NOT Operator
The NOT operator is used in combination with other operators to give the
opposite result, also called the negative result.

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

In the example above, the NOT operator is used in combination with


the = operator, but it can be used in combination with other comparison
and/or logical operators. See examples below.

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

NOT LIKE
Example
Select customers that does not start with the letter 'A':
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'A%';

NOT BETWEEN
Example
Select customers with a customerID not between 10 and 60:

SELECT * FROM Customers


WHERE CustomerID NOT BETWEEN 10 AND 60;

NOT IN
Example
Select customers that are not from Paris or London:

SELECT * FROM Customers


WHERE City NOT IN ('Paris', 'London');

NOT Greater Than


Example
Select customers with a CustomerId not greater than 50:

SELECT * FROM Customers


WHERE NOT CustomerID > 50;

Note: There is a not-greater-than operator: !> that would give you the same
result.
NOT Less Than
Example
Select customers with a CustomerID not less than 50:

SELECT * FROM Customers


WHERE NOT CustomerId < 50;

Note: There is a not-less-than operator: !< that would give you the same
result.

SQL INSERT INTO Statement


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

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need
to specify the column names in the SQL query. However, make sure the
order of the values is in the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');

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.

Insert Data Only in Specified Columns


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

The following SQL statement will insert a new record, but only insert data in
the "CustomerName", "City", and "Country" columns (CustomerID will be
updated automatically):

Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

Insert Multiple Rows


It is also possible to insert multiple rows in one statement.

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

Make sure you separate each set of values with a comma ,.

SQL NULL Values


What is a NULL Value?
A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update


a record without adding a value to this field. Then, the field will be saved
with a NULL value.

Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during
record creation!

How to Test for NULL Values?


It is not possible to test for NULL values with comparison operators, such as
=, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).

The following SQL lists all customers with a NULL value in the "Address"
field:

Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

Tip: Always use IS NULL to look for NULL values.

The IS NOT NULL Operator


The IS NOT NULL operator is used to test for non-empty values (NOT NULL
values).

The following SQL lists all customers with a value in the "Address" field:

Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

SQL UPDATE Statement


The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should
be updated. If you omit the WHERE clause, all records in the table will be
updated!

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1)
with a new contact person and a new city.

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

UPDATE Multiple Records


It is the WHERE clause that determines how many records will be updated.

The following SQL statement will update the ContactName to "Juan" for all
records where country is "Mexico":

Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records
will be updated!
Example
UPDATE Customers
SET ContactName='Juan';

SQL DELETE Statement


The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!

SQL DELETE Example


The following SQL statement deletes the customer "Alfreds Futterkiste" from
the "Customers" table:

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records


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

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:
Example
DELETE FROM Customers;

Delete a Table
To delete the table completely, use the DROP TABLE statement:

Example
Remove the Customers table:

DROP TABLE Customers;

SQL TOP, LIMIT, FETCH FIRST or


ROWNUM Clause
The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records.
Returning a large number of records can impact performance.

Example
Select only the first 3 records of the Customers table:

SELECT TOP 3 * FROM Customers;

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.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;

LIMIT
The following SQL statement shows the equivalent example for MySQL:

Example
Select the first 3 records of the Customers table:

SELECT * FROM Customers


LIMIT 3;

FETCH FIRST
The following SQL statement shows the equivalent example for Oracle:

Example
Select the first 3 records of the Customers table:

SELECT * FROM Customers


FETCH FIRST 3 ROWS ONLY;

SQL TOP PERCENT Example


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

Example
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
ADD a WHERE CLAUSE
The following SQL statement selects the first three records from the
"Customers" table, where the country is "Germany"

Example
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;

ADD the ORDER BY Keyword


Add the ORDER BY keyword when you want to sort the result, and return the
first 3 records of the sorted result.

The following SQL statement shows the equivalent example for Oracle:

Example
SELECT * FROM Customers
ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;

SQL Aggregate Functions


SQL Aggregate Functions
An aggregate function is a function that performs a calculation on a set of
values, and returns a single value.

Aggregate functions are often used with the GROUP BY clause of


the SELECT statement. The GROUP BY clause splits the result-set into groups
of values and the aggregate function can be used to return a single value for
each group.

The most commonly used SQL aggregate functions are:

 MIN() - returns the smallest value within the selected column


 MAX() - returns the largest value within the selected column
 COUNT() - returns the number of rows in a set
 SUM() - returns the total sum of a numerical column
 AVG() - returns the average value of a numerical column

Aggregate functions ignore null values (except for COUNT()).

SQL MIN() and MAX() Functions


The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN 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;
Set Column Name (Alias)
When you use MIN() or MAX(), the returned column will not have a
descriptive name. To give the column a descriptive name, use
the AS keyword:

Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;

Use MIN() with GROUP BY


Here we use the MIN() function and the GROUP BY clause, to return the
smallest price for each category in the Products table:

Example
SELECT MIN(Price) AS SmallestPrice, CategoryID
FROM Products
GROUP BY CategoryID;

SQL COUNT() Function


The SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified
criterion.

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;

Specify Column
You can specify a column name instead of the asterix symbol (*).

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;

Add a WHERE Clause


You can add a WHERE clause to specify conditions:

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":

SELECT COUNT(*) AS [Number of records]


FROM Products;

Use COUNT() with GROUP BY


Here we use the COUNT() function and the GROUP BY clause, to return the
number of records for each category in the Products table:

Example
SELECT COUNT(*) AS [Number of records], CategoryID
FROM Products
GROUP BY CategoryID;

SQL SUM() Function


The SQL SUM() Function
The SUM() function returns the total sum of a numeric column.
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;

Add a WHERE Clause


You can add a WHERE clause to specify conditions:

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":

SELECT SUM(Quantity) AS total


FROM OrderDetails;
Use SUM() with GROUP BY
Here we use the SUM() function and the GROUP BY clause, to return
the Quantity for each OrderID in the OrderDetails table:

Example
SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;

SUM() With an Expression


The parameter inside the SUM() function can also be an expression.

If we assume that each product in the OrderDetails column costs 10 dollars,


we can find the total earnings in dollars by multiply each quantity with 10:

Example
Use an expression inside the SUM() function:

SELECT SUM(Quantity * 10)


FROM OrderDetails;

We can also join the OrderDetails table to the Products table to find the actual
amount, instead of assuming it is 10 dollars:

Example
Join OrderDetails with Products, and use SUM() to find the total amount:

SELECT SUM(Price * Quantity)


FROM OrderDetails
LEFT JOIN Products ON OrderDetails.ProductID = Products.ProductID;

SQL AVG() Function


The SQL AVG() Function
The AVG() function returns the average value of a numeric column.

Example
Find the average price of all products:

SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.

Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

Add a WHERE Clause


You can add a WHERE clause to specify conditions:

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":

SELECT AVG(Price) AS [average price]


FROM Products;

Higher Than Average


To list all records with a higher price than average, we can use
the AVG() function in a sub query:

Example
Return all products with a higher price than the average price:

SELECT * FROM Products


WHERE price > (SELECT AVG(price) FROM Products);

Use AVG() with GROUP BY


Here we use the AVG() function and the GROUP BY clause, to return the
average price for each category in the Products table:

Example
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;

SQL LIKE Operator


The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.

There are two wildcards often used in conjunction with the LIKE operator:
 The percent sign % represents zero, one, or multiple characters
 The underscore sign _ represents one, single character

Example
Select all customers that starts with the letter "a":

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

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:

SELECT * FROM Customers


WHERE city LIKE 'L_nd__';

The % Wildcard
The % wildcard represents any number of characters, even zero characters.
Example
Return all customers from a city that contains the letter 'L':

SELECT * FROM Customers


WHERE city LIKE '%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':

SELECT * FROM Customers


WHERE CustomerName LIKE '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':

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%' OR CustomerName LIKE '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':

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';
Tip: You can also combine "starts with" and "ends with":

Example
Return all customers that starts with "b" and ends with "s":

SELECT * FROM Customers


WHERE CustomerName LIKE 'b%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'

SELECT * FROM Customers


WHERE CustomerName LIKE '%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:

SELECT * FROM Customers


WHERE CustomerName LIKE 'a__%';

Example
Return all customers that have "r" in the second position:

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';
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:

SELECT * FROM Customers


WHERE Country LIKE 'Spain';

SQL Wildcards
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.

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':

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

Wildcard Characters

Symbol Description

% Represents zero or more characters


_ Represents a single character

[] Represents any single character within the brackets

^ Represents any character not in the brackets

- Represents any single character within the specified range

{} Represents any escaped character

Using the % Wildcard


The % wildcard represents any number of characters, even zero characters.

Example
Return all customers that ends with the pattern 'es':

SELECT * FROM Customers


WHERE CustomerName LIKE '%es';

Example
Return all customers that contains the pattern 'mer':

SELECT * FROM Customers


WHERE CustomerName LIKE '%mer%';
Using 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 with a City starting with any character, followed by
"ondon":

SELECT * FROM Customers


WHERE City LIKE '_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';

Using the [] Wildcard


The [] wildcard returns a result if any of the characters inside gets a match.

Example
Return all customers starting with either "b", "s", or "p":

SELECT * FROM Customers


WHERE CustomerName LIKE '[bsp]%';

Using the - Wildcard


The - wildcard allows you to specify a range of characters inside
the [] wildcard.
Example
Return all customers starting with "a", "b", "c", "d", "e" or "f":

SELECT * FROM Customers


WHERE CustomerName LIKE '[a-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:

SELECT * FROM Customers


WHERE CustomerName LIKE 'a__%';

Example
Return all customers that have "r" in the second position:

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';

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:

SELECT * FROM Customers


WHERE Country LIKE 'Spain';
SQL IN Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

Example
Return all customers from 'Germany', 'France', or 'UK'

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');

Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

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':

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', '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.

Let us check if that is correct, by using the NOT IN operator.

Example
Return all customers that have NOT placed any orders in the Orders table:

SELECT * FROM Customers


WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders);

SQL BETWEEN Operator


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

The BETWEEN operator is inclusive: begin and end values are included.

Example
Selects all products with a price between 10 and 20:

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

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;

NOT BETWEEN Text Values


The following SQL statement selects all products with a ProductName not
between Carnarvon Tigers and Mozzarella di Giovanni:

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';
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary
name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

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 AS alias_name


FROM table_name;

When alias is used on table:

SELECT column_name(s)
FROM table_name AS alias_name;
Alias for Columns
The following SQL statement creates two aliases, one for the CustomerID
column and one for the CustomerName column:

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:

SELECT ProductName AS [My Great Products]


FROM Products;

Example
Using "double quotes" for aliases with space characters:

SELECT ProductName AS "My Great Products"


FROM Products;

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

Alias for Tables


The same rules applies when you want to use an alias for a table.

Example
Refer to the Customers table as Persons instead:

SELECT * FROM Customers AS Persons;

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;

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

You might also like