W3 schools
SQL
Some of The Most Important SQL
Commands
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT column1, column2, ...
FROM table_name;
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT DISTINCT Country FROM Customers;
SELECT COUNT(DISTINCT Country) FROM Customers;
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 column1, column2, ...
FROM table_name
WHERE condition;
SELECT * FROM Customers
WHERE Country='Mexico';
Operators in The WHERE Clause
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
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
BETWEEN
Select ProductName from products where price between 18 and 30;
SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;
LIKE
SELECT * FROM Customers
WHERE City LIKE 'ber%';
SELECT * FROM Customers
WHERE City LIKE '%el%';
SELECT * FROM Customers
WHERE City LIKE '%in';
IN
SELECT * FROM Customers
WHERE City IN ('Paris','London');
select * from customers where country = 'UK';
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one
condition:
The AND operator displays a record if all the conditions separated
by AND are TRUE.
The OR operator displays a record if any of the conditions separated
by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
CustomerID CustomerName ContactName Address City Po
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12
2 Ana Trujillo Emparedados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05
y helados
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-9
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68
7 Blondel père et fils Frédérique 24, place Kléber Strasbourg 67
Citeaux
8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28
preparadas
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC
12 Cactus Comidas para Patricio Simpson Cerrito 333 Buenos Aires 10
llevar
13 Centro comercial Francisco Chang Sierras de Granada 9993 México D.F. 05
Moctezuma
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 30
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX
17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52
Delikatessend
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44
19 Eastern Connection Ann Devon 35 King George London WX
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 80
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05
22 FISSA Fabrica Inter. Diego Roel C/ Moralzarzal, 86 Madrid 28
Salchichas S.A.
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-8
25 Frankenversand Peter Franken Berliner Platz 43 München 80
26 France restauration Carine Schmitt 54, rue Royale Nantes 44
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10
28 Furia Bacalhau e Frutos Lino Rodriguez Jardim das rosas n. 32 Lisboa 16
do Mar
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 10
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05
35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos San Cristóbal 50
Soublette #8-35
36 Hungry Coyote Import Yoshi Latimer City Center Plaza 516 Main St. Elgin 97
Store
37 Hungry Owl All-Night Patricia McKenna 8 Johnstown Road Cork
Grocers
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31
42 Laughing Bacchus Wine Yoshi Tannamuri 1900 Oak St. Vancouver V3
Cellars
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt 60
a.M.
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94
46 LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar Barquisimeto 35
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de 49
Margarita
48 Lonesome Pine Fran Wilson 89 Chiaroscuro Rd. Portland 97
Restaurant
49 Magazzini Alimentari Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24
Riuniti
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04
53 North/South Simon Crowther South House 300 Queensbridge London SW
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Buenos Aires 10
Piso 20-A
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99
56 Ottilies Käseladen Henriette Mehrheimerstr. 369 Köln 50
Pfalzheim
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75
58 Pericles Comidas clásicas Guillermo Calle Dr. Jorge Cash 321 México D.F. 05
Fernández
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 50
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 17
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 10
65 Rattlesnake Canyon Paula Wilson 2817 Milton Dr. Albuquerque 87
Grocery
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 12
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 41
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX
73 Simons bistro Jytte Petersen Vinbæltet 34 København 17
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75
75 Split Rail Beer & Ale Art P.O. Box 555 Lander 82
Braunschweiger
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44
80 Tortuga Restaurante Miguel Angel Avda. Azteca 123 México D.F. 05
Paolino
81 Tradição Hipermercados Anabela Av. Inês de Castro, 414 São Paulo 05
Domingues
82 Trail's Head Gourmet Helvetius Nagy 722 DaVinci Blvd. Kirkland 98
Provisioners
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 82
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01
ADVERTISEMENT
AND Example
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
Try it Yourself »
OR Example
The following SQL statement selects all fields from "Customers" where city is
"Berlin" OR "München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
Try it Yourself »
The following SQL statement selects all fields from "Customers" where country is
"Germany" OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
Try it Yourself »
NOT Example
The following SQL statement selects all fields from "Customers" where country is
NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
Try it Yourself »
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form
complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Try it Yourself »
The following SQL statement selects all fields from "Customers" where country is
NOT "Germany" and NOT "USA":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT * FROM Customers
ORDER BY Country;
SELECT * FROM Customers
ORDER BY Country DESC;
SELECT * FROM Customers
ORDER BY Country, CustomerName;
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
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, ...);
Ex
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');
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, ...);
What is a NULL Value?
A field with a NULL value is a field with no value.
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.
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
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 Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE FROM table_name WHERE condition;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
SELECT TOP 3 * FROM Customers;
SELECT TOP 50 PERCENT * FROM Customers;
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The SQL MIN() and MAX() Functions
SELECT MIN(column_name)
FROM table_name
WHERE condition;
The SQL COUNT(), AVG() and SUM()
Functions
The COUNT() function returns the number of rows that matches a specified
criterion.
Note: NULL values are not counted.
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
SELECT COUNT(ProductID)
FROM Products;
The AVG() function returns the average value of a numeric column.
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
The SUM() function returns the total sum of a numeric column.
SELECT SUM(Quantity)
FROM OrderDetails;
Note: NULL values are ignored.
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
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2
length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3
length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
The following SQL statement selects all customers with a CustomerName that
have "r" in the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that
does NOT start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Using the [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b",
"s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
Try it Yourself »
The following SQL statement selects all customers with a City starting with "a",
"b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Using the [!charlist] Wildcard
The two following SQL statements select all customers with a City NOT starting
with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
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.
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
BETWEEN Text Values Example
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;
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
BETWEEN Dates Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
SQL Aliases
The following SQL statement creates two aliases, one for the CustomerName
column and one for the ContactName column. Note: 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;
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;
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
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or
more SELECT statements.
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword cannot be
used with aggregate functions.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a
subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.Suppl
ierID = Suppliers.supplierID AND Price < 20);
The SQL ANY and ALL Operators
The ANY and ALL operators allow you to perform a comparison between a single
column value and a range of other values.
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
The SELECT INTO statement copies data from one table into a new table.
SQL Logical Operators
Operator Description
ALL TRUE if all of the subquery values meet the condition
AND TRUE if all the conditions separated by AND is TRUE
ANY TRUE if any of the subquery values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the subquery returns one or more records
IN TRUE if the operand is equal to one of a list of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is TRUE
SOME TRUE if any of the subquery values meet the condition
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very
quickly