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

SQL With Mysql

RDBMS stands for Relational Database Management System and is the basis for SQL and modern database systems. In an RDBMS, data is stored in database objects called tables which consist of columns and rows. Each table contains fields (columns) that maintain specific information about records (rows). A record is an individual entry in a table. A column contains all information associated with a specific field across all records.

Uploaded by

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

SQL With Mysql

RDBMS stands for Relational Database Management System and is the basis for SQL and modern database systems. In an RDBMS, data is stored in database objects called tables which consist of columns and rows. Each table contains fields (columns) that maintain specific information about records (rows). A record is an individual entry in a table. A column contains all information associated with a specific field across all records.

Uploaded by

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

Database Latihan01

Database untuk Latihan M11-M14


Berikut ini daftar Tabel dan kolom/variabel untuk setiap tabel yang ada dalam database Latihan01. Database
Latihan01 ini akan digunakan sebagai data untuk latihan pada pertemuan 11-14.

Tabel dalam database latihan01: SupplierName varchar(100),


1. Orders
ContactName varchar(100),
2. Products
3. Customers Address varchar(150),
4. Suppliers City varchar(100),
5. OrderDetails PostalCode varchar(10),
Country varchar(50),
Kolom/Field/Variabel dalam Tabel Orders:
Phone varchar(50),
Kolom Tipe data
OrderID int Kolom/Field/Variabel dalam Tabel
CustomerID int, OrderDetails:
EmployeeID int,
OrderDate date,
ShipperID int,

Kolom/Field/Variabel dalam Tabel Products:


Kolom Tipe data
ProductID int
ProductName varchar(100),
SupplierID int,
CategoryID int,
Unit varchar(100),
Price dec(7,2),

Kolom/Field/Variabel dalam Tabel Customers:


Kolom Tipe data
CustomerID int
CustomerName varchar(100),
ContactName varchar(100),
Address varchar(150),
City varchar(100),
PostalCode varchar(10),
Country varchar(50),

Kolom/Field/Variabel dalam Tabel Suppliers:

Kolom Tipe data


SupplierID int
1
Kolom Tipe data
OrderDetailID int
OrderID int,
ProductID int,
Quantity int,

2
Print daftar tabel
dan daftar kolom setiap tabel

3
Introduction to SQL

SQL is a standard language for storing, manipulating and retrieving data in databases.
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

SQL is a standard language for accessing and manipulating databases.

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

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

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

Table: Customers. Number of Records: 91

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
Emparedados y helados
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique 24, place Kléber Strasbourg 67000 France
Citeaux
8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
preparadas
9 Bon app' Laurence 12, rue des Bouchers Marseille 13008 France
Lebihans
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
llevar
13 Centro comercial Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
Moctezuma
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany
Delikatessend
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
Salchichas S.A.
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
5
CustomerID CustomerName ContactName Address City PostalCode Country
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
do Mar
29 Galería del gastrónomo Eduardo Rambla de Cataluña, 23 Barcelona 08022 Spain
Saavedra
30 Godos Cocina Típica José Pedro C/ Romero, 33 Sevilla 41101 Spain
Freyre
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de 05454-876 Brazil
Janeiro
35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos San Cristóbal 5022 Venezuela
Soublette #8-35
36 Hungry Coyote Import Yoshi Latimer City Center Plaza 516 Main Elgin 97827 USA
Store St.
37 Hungry Owl All-Night Patricia McKenna 8 Johnstown Road Cork Ireland
Grocers
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
Cellars
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt 60528 Germany
a.M.
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San 94117 USA
Francisco
46 LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar Barquisimeto 3508 Venezuela
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de 4980 Venezuela
Margarita
48 Lonesome Pine Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
Restaurant
49 Magazzini Alimentari Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
Riuniti
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
53 North/South Simon Crowther South House 300 London SW7 1RZ UK
Queensbridge
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Buenos Aires 1010 Argentina
Piso 20-A
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Mehrheimerstr. 369 Köln 50739 Germany
Pfalzheim
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas Guillermo Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
clásicas Fernández
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de 02389-673 Brazil
6
CustomerID CustomerName ContactName Address City PostalCode Country
Janeiro
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
Grocery
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio 42100 Italy
Emilia
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de 02389-890 Brazil
Janeiro
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art P.O. Box 555 Lander 82520 USA
Braunschweiger
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Avda. Azteca 123 México D.F. 05033 Mexico
Paolino
81 Tradição Hipermercados Anabela Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
Domingues
82 Trail's Head Gourmet Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
Provisioners
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

DATABASE TABLES
A database most often contains one or more tables. Each table is identified by a name
(e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
SQL STATEMENTS
Most of the actions you need to perform on a database are done with SQL statements.
KEEP IN MIND THAT...
SQL keywords are NOT case sensitive: select is the same as SELECT
In this tutorial we will write all SQL keywords in upper-case.

SEMICOLON AFTER SQL STATEMENTS?


Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems
that allow more than one SQL statement to be executed in the same call to the server.
7
In this tutorial, we will use semicolon at the end of each SQL statement.

SOME OF THE MOST IMPORTANT SQL COMMANDS


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

The SQL SELECT Statement

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


The data returned is stored in a result table, called the result-set.

SELECT SYNTAX
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

SELECT COLUMN EXAMPLE


The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
EXAMPLE
SELECT CustomerName, City FROM Customers;

Number of Records: 91 [yang ditampilkan hanya sebagian]

CustomerName City
Alfreds Futterkiste Berlin
Ana Trujillo Emparedados y México D.F.
helados
Antonio Moreno Taquería México D.F.
Around the Horn London
Berglunds snabbköp Luleå

SELECT * EXAMPLE
The following SQL statement selects all the columns from the "Customers" table:
EXAMPLE
8
SELECT * FROM Customers;

Number of Records: 91 [yang ditampilkan hanya sebagian]

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;

SQL SELECT DISTINCT Statement

 SELECT DISTINCT returns only distinct (different) values.


 SELECT DISTINCT eliminates duplicate records from the results.
 DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.
 DISTINCT operates on a single column. DISTINCT for multiple columns is not supported.

SELECT Example Without DISTINCT


The following SQL statement selects ALL (including the duplicates) values from the
"Country" column in the "Customers" table:
Example
Now, let us use the DISTINCT keyword with the above SELECT statement and see the
result.
SELECT Country FROM Customers;

Number of Records: 91
Country
Germany
9
Mexico
Mexico
UK
Sweden
Germany
France

SELECT DISTINCT Examples


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 statement lists the number of different (distinct) customer countries:
Number of Records: 21
Country
Germany
Mexico
UK
Sweden
France

Example
SELECT DISTINCT Country,city FROM Customers;

Number of Records: 69
Country City
Germany Berlin
Mexico México D.F.
UK London
Sweden Luleå
Germany Mannheim
France Strasbourg

Example
SELECT COUNT(DISTINCT Country) FROM Customers;

Note: The example above will not work in Firefox and Microsoft Edge! Because
COUNT(DISTINCT column_name) is not supported in Microsoft Access databases.
Firefox and Microsoft Edge are using Microsoft Access in our examples.
Here is the workaround for MS Access:

Number of Records: 1
COUNT(DISTINCT Country)
21
10
Example
SELECT Count(*) AS DistinctCountries FROM (SELECT DISTINCT Country FROM
Customers);

Number of Records: 1
DistinctCountries
21

SQL WHERE Clause

The WHERE clause is used to filter records.


The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statement, it is also used in
UPDATE, DELETE statement, etc.!

WHERE Clause Example


The following SQL statement selects all the customers from the country "Mexico", in
the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';

Number of Records: 5
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.
13 Centro comercial Francisco Sierras de México 05022 Mexico
Moctezuma Chang Granada D.F.
9993
58 Pericles Comidas Guillermo Calle Dr. México 05033 Mexico
clásicas Fernández Jorge Cash D.F.
321
80 Tortuga Miguel Angel Avda. Azteca México 05033 Mexico
Restaurante Paolino 123 D.F.
11
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow
double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID=1;

Number of Records: 1

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Futterkiste Maria Anders Obere Str. Berli 12209 Germany
57 n

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 as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column

SQL AND, OR and NOT Operators

THE SQL AND, OR AND NOT OPERATORS


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one
condition:
 The AND operator displays a record if all the conditions separated by AND are
TRUE.
12
 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;

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

Number of Records: 1
CustomerI CustomerName ContactName Address City PostalCode Country
D
1 Alfreds Futterkiste Maria Anders Obere Str. Berlin 12209 Germany
57

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

Number of Records: 2
CustomerI CustomerName ContactNam Address City PostalCode Country

13
D e
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

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

Number of Records: 16 [sebagian tidak ditampilkan]


CustomerI CustomerName ContactName Address City PostalCode Country
D
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
8 Bólido Comidas Martín C/ Araquil, 67 Madrid 28023 Spain
preparadas Sommer
17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany
Delikatessend
22 FISSA Fabrica Inter. Diego Roel C/ Madrid 28034 Spain
Salchichas S.A. Moralzarzal,
86
25 Frankenversand Peter Franken Berliner Platz München 80805 Germany
43

NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';

Number of Records: 80 [sebagian tidak ditampilkan]


CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Moreno Mataderos 2312 México 05023 Mexico
Taquería D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
7 Blondel père et fils Frédérique 24, place Kléber Strasbourg 67000 France
Citeaux

COMBINING AND, OR AND NOT


You can also combine the AND, OR and NOT operators.

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

Number of Records: 2
CustomerI CustomerName ContactName Address City PostalCod Country
D e
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
25 Frankenversand Peter Franken Berliner Platz München 80805 Germany
43

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

Number of Records: 67 [sebagian tidak ditampilkan]


CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Moreno Mataderos 2312 México 05023 Mexico
Taquería D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
7 Blondel père et fils Frédérique 24, place Kléber Strasbourg 67000 France
Citeaux

t Yourself With Exercises


Exercise:
Select all records where the City column has the value 'Berlin' and the PostalCode
column has the value 12209.

SQL ORDER BY Keyword

THE SQL ORDER BY KEYWORD


The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
15
ORDER BY S YNTAX
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

ORDER BY EXAMPLE
The following SQL statement selects all customers from the "Customers" table, sorted
by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;

Number of Records: 91 [sebagian tidak ditampilkan]


CustomerID CustomerName ContactName Address City PostalCode Country
12 Cactus Comidas Patricio Cerrito 333 Buenos 1010 Argentina
para llevar Simpson Aires
54 Océano Atlántico Yvonne Ing. Gustavo Buenos 1010 Argentina
Ltda. Moncada Moncada Aires
8585 Piso
20-A
64 Rancho grande Sergio Av. del Buenos 1010 Argentina
Gutiérrez Libertador Aires
900
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

ORDER BY DESC E XAMPLE


The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;

Number of Records: 91 [sebagian tidak ditampilkan]


CustomerI CustomerName ContactName Address City PostalCode Country
D
33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela
Restaurante Palos Grandes
35 HILARIÓN- Carlos Carrera 22 con San Cristóbal 5022 Venezuela
Abastos Hernández Ave. Carlos
Soublette #8-35
46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela
Supermercado González Ave. Bolívar
#65-98 Llano
Largo
47 LINO-Delicateses Felipe Ave. 5 de Mayo I. de 4980 Venezuela
Izquierdo Porlamar Margarita

LIHAT BANYAKNYA RECORD. JIKA RECORD TERLALU BANYAK, MAKA DALAM


CATATAN INI TIDAK SEMUANYA DITAMPILKAN UNTUK MENGHEMAT TEMPAT. JADI
SAYA TIDAK AKAN LAGI MENAMPILKAN PERNYATAAN
16
[sebagian tidak ditampilkan]

ORDER BY S EVERAL COLUMNS EXAMPLE


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

Number of Records: 91
CustomerID CustomerName ContactName Address City PostalCode Country
12 Cactus Comidas Patricio Cerrito 333 Buenos 1010 Argentina
para llevar Simpson Aires
54 Océano Atlántico Yvonne Ing. Gustavo Buenos 1010 Argentina
Ltda. Moncada Moncada 8585 Aires
Piso 20-A
64 Rancho grande Sergio Av. del Libertador Buenos 1010 Argentina
Gutiérrez 900 Aires
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
50 Maison Dewey Catherine Rue Joseph-Bens Bruxelles B-1180 Belgium
Dewey 532
76 Suprêmes délices Pascale Boulevard Tirou, Charleroi B-6000 Belgium
Cartrain 255

ORDER BY S EVERAL COLUMNS EXAMPLE 2


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

Number of Records: 91
CustomerID CustomerName ContactName Address
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20-A
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333
59 Piccolo und mehr Georg Pipps Geislweg 14
20 Ernst Handel Roland Mendel Kirchgasse 6

Test Yourself With Exercises


Exercise:
Select all records from the Customers table, sort the result alphabetically by the column
City.

17
SQL INSERT INTO Statement

THE SQL INSERT INTO S TATEMENT


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.
The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

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. The INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);

INSERT INTO E XAMPLE


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

SELECT * FROM Customers;

Number of Records: 92 [cataan: sebelumnya hanya ada 91 record/baris]


CustomerI CustomerName ContactName Address City PostalCode Country
D
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
Importadora
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite Seattle 98128 USA
3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 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):
18
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

Number of Records: 93
CustomerI CustomerName ContactName Address City PostalCode Country
D
89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Skagen 21 Stavanger 4006 Norway
Erichsen
93 Cardinal null null Stavanger null Norway

Exercise:
Insert a new record in the Customers table.

Field/kolom Nilai
CustomerNam
e Hekkan Burger
Address Gateveien 15
City Sandnes
PostalCode 4306
Country Norway

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

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

Number of Records: 1
CustomerNam ContactName Address
e
Cardinal null 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;

Number of Records: 92
CustomerName ContactName Address
Alfreds Futterkiste Maria Anders Obere Str. 57
Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222
Antonio Moreno Taquería Antonio Moreno Mataderos 2312

Exercise:
Select all records from the Customers where the PostalCode column is empty.

SQL UPDATE Statement

20
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.
Example
SELECT * FROM Customers
WHERE CustomerID = 1;

Number of Records: 1
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

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

HASIL SETELAH UPDATE :


You have made changes to the database. Rows affected: 1

SELECT * FROM Customers


WHERE CustomerID = 1;

Number of Records: 1
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
1 Alfreds Futterkiste Alfred Schmidt Obere Str. Frankfurt 12209 Germany
57

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

SELECT* FROM Customers


WHERE Country='Mexico';

21
Number of Records: 5
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Moreno Mataderos 2312 México 05023 Mexico
Taquería D.F.
13 Centro comercial Francisco Chang Sierras de México 05022 Mexico
Moctezuma Granada 9993 D.F.
58 Pericles Comidas Guillermo Calle Dr. Jorge México 05033 Mexico
clásicas Fernández Cash 321 D.F.
80 Tortuga Restaurante Miguel Angel Avda. Azteca 123 México 05033 Mexico
Paolino D.F.

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

You have made changes to the database. Rows affected: 5

HASIL SETELAH UPDATE:


Number of Records: 5
CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Juan Avda. de la México 05021 Mexico
Emparedados y helados Constitución 2222 D.F.
3 Antonio Moreno Juan Mataderos 2312 México 05023 Mexico
Taquería D.F.
13 Centro comercial Juan Sierras de México 05022 Mexico
Moctezuma Granada 9993 D.F.
58 Pericles Comidas Juan Calle Dr. Jorge México 05033 Mexico
clásicas Cash 321 D.F.
80 Tortuga Restaurante Juan Avda. Azteca 123 México 05033 Mexico
D.F.

Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be
updated!

Test Yourself With Exercises


Exercise:
Update the City column of all records in the Customers table. City=’London’ =>
City=’London, UK’

SQL DELETE Statement

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

You have made changes to the database. Rows affected: 1

SELECT * FROM Customers;

Number of Records: 92
CustomerI CustomerName ContactName Address City PostalCod Country
D e
2 Ana Trujillo Emparedados Ana Trujillo Avda. de la México 05021 Mexico
y helados Constitución 2222 D.F.
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

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;

Exercise:
Delete all the records from the Customers table where the Country value is 'Norway'.

23
SQL LIMIT Clause

THE SQL SELECT TOP C LAUSE


The SELECT LIMIT clause is used to specify the number of records to return.
The SELECT LIMIT clause is useful on large tables with thousands of records. Returning
a large number of records can impact performance.
MYSQL SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Example
SELECT * FROM Customers
LIMIT 3;

Number of Records: 3
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
2 Ana Trujillo Juan Avda. de la México 05021 Mexico
Emparedados y Constitución 2222 D.F.
helados
3 Antonio Moreno Juan Mataderos 2312 México 05023 Mexico
Taquería D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

ADD A WHERE CLAUSE

The following SQL statement shows the equivalent example using the LIMIT clause (for
MySQL):
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

Number of Records: 3
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany
Delikatessend
25 Frankenversand Peter Franken Berliner Platz München 80805 Germany
43

24
STATICTICAL FUNCTION

Kita akan menggnakan data berikut ini untuk kasus fungsi-fungsi statistik.
Data Table: Products
Number of Records: 77

ProductI ProductName SupplierI CategoryID Unit Price


D D
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25
7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs. 30
8 Northwoods Cranberry Sauce 3 2 12 - 12 oz jars 40
9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97
10 Ikura 4 8 12 - 200 ml jars 31
11 Queso Cabrales 5 4 1 kg pkg. 21
12 Queso Manchego La Pastora 5 4 10 - 500 g pkgs. 38
13 Konbu 6 8 2 kg box 6
14 Tofu 6 7 40 - 100 g pkgs. 23.25
15 Genen Shouyu 6 2 24 - 250 ml bottles 15.5
16 Pavlova 7 3 32 - 500 g boxes 17.45
17 Alice Mutton 7 6 20 - 1 kg tins 39
18 Carnarvon Tigers 7 8 16 kg pkg. 62.5
19 Teatime Chocolate Biscuits 8 3 10 boxes x 12 pieces 9.2
20 Sir Rodney's Marmalade 8 3 30 gift boxes 81
21 Sir Rodney's Scones 8 3 24 pkgs. x 4 pieces 10
22 Gustaf's Knäckebröd 9 5 24 - 500 g pkgs. 21
23 Tunnbröd 9 5 12 - 250 g pkgs. 9
24 Guaraná Fantástica 10 1 12 - 355 ml cans 4.5
25 NuNuCa Nuß-Nougat-Creme 11 3 20 - 450 g glasses 14
26 Gumbär Gummibärchen 11 3 100 - 250 g bags 31.23
27 Schoggi Schokolade 11 3 100 - 100 g pieces 43.9
28 Rössle Sauerkraut 12 7 25 - 825 g cans 45.6
29 Thüringer Rostbratwurst 12 6 50 bags x 30 123.79
sausgs.
30 Nord-Ost Matjeshering 13 8 10 - 200 g glasses 25.89
31 Gorgonzola Telino 14 4 12 - 100 g pkgs 12.5
32 Mascarpone Fabioli 14 4 24 - 200 g pkgs. 32
33 Geitost 15 4 500 g 2.5
34 Sasquatch Ale 16 1 24 - 12 oz bottles 14
35 Steeleye Stout 16 1 24 - 12 oz bottles 18
36 Inlagd Sill 17 8 24 - 250 g jars 19
37 Gravad lax 17 8 12 - 500 g pkgs. 26
38 Côte de Blaye 18 1 12 - 75 cl bottles 263.5
39 Chartreuse verte 18 1 750 cc per bottle 18
40 Boston Crab Meat 19 8 24 - 4 oz tins 18.4

25
ProductI ProductName SupplierI CategoryID Unit Price
D D
41 Jack's New England Clam 19 8 12 - 12 oz cans 9.65
Chowder
42 Singaporean Hokkien Fried Mee 20 5 32 - 1 kg pkgs. 14
43 Ipoh Coffee 20 1 16 - 500 g tins 46
44 Gula Malacca 20 2 20 - 2 kg bags 19.45
45 Røgede sild 21 8 1k pkg. 9.5
46 Spegesild 21 8 4 - 450 g glasses 12
47 Zaanse koeken 22 3 10 - 4 oz boxes 9.5
48 Chocolade 22 3 10 pkgs. 12.75
49 Maxilaku 23 3 24 - 50 g pkgs. 20
50 Valkoinen suklaa 23 3 12 - 100 g bars 16.25
51 Manjimup Dried Apples 24 7 50 - 300 g pkgs. 53
52 Filo Mix 24 5 16 - 2 kg boxes 7
53 Perth Pasties 24 6 48 pieces 32.8
54 Tourtière 25 6 16 pies 7.45
55 Pâté chinois 25 6 24 boxes x 2 pies 24
56 Gnocchi di nonna Alice 26 5 24 - 250 g pkgs. 38
57 Ravioli Angelo 26 5 24 - 250 g pkgs. 19.5
58 Escargots de Bourgogne 27 8 24 pieces 13.25
59 Raclette Courdavault 28 4 5 kg pkg. 55
60 Camembert Pierrot 28 4 15 - 300 g rounds 34
61 Sirop d'érable 29 2 24 - 500 ml bottles 28.5
62 Tarte au sucre 29 3 48 pies 49.3
63 Vegie-spread 7 2 15 - 625 g jars 43.9
64 Wimmers gute Semmelknödel 12 5 20 bags x 4 pieces 33.25
65 Louisiana Fiery Hot Pepper Sauce 2 2 32 - 8 oz bottles 21.05
66 Louisiana Hot Spiced Okra 2 2 24 - 8 oz jars 17
67 Laughing Lumberjack Lager 16 1 24 - 12 oz bottles 14
68 Scottish Longbreads 8 3 10 boxes x 8 pieces 12.5
69 Gudbrandsdalsost 15 4 10 kg pkg. 36
70 Outback Lager 7 1 24 - 355 ml bottles 15
71 Fløtemysost 15 4 10 - 500 g pkgs. 21.5
72 Mozzarella di Giovanni 14 4 24 - 200 g pkgs. 34.8
73 Röd Kaviar 17 8 24 - 150 g jars 15
74 Longlife Tofu 4 7 5 kg pkg. 10
75 Rhönbräu Klosterbier 12 1 24 - 0.5 l bottles 7.75
76 Lakkalikööri 23 1 500 ml 18
77 Original Frankfurter grüne Soße 12 2 12 boxes 13

SQL MIN() and MAX() Functions

THE SQL MIN() AND MAX() FUNCTIONS


26
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() SYNTAX
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() SYNTAX
SELECT MAX(column_name)
FROM table_name
WHERE condition;

MIN() EXAMPLE
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price)
FROM Products;

Number of Records: 1
MIN(Price)
2.5

SELECT MIN(Price) AS SmallestPrice


FROM Products;

Number of Records: 1
SmallestPrice
2.5

MAX() EXAMPLE
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;

Number of Records: 1
LargestPrice
263.5

THE SQL COUNT(), AVG() AND SUM() F UNCTIONS


The COUNT() function returns the number of rows that matches a specified criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.

COUNT() SYNTAX
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

27
AVG() SYNTAX
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() SYNTAX
SELECT SUM(column_name)
FROM table_name
WHERE condition;

COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;

Number of Records: 1
COUNT(ProductID)
77

Note: NULL values are not counted.

AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;

Number of Records: 1
AVG(Price)
28.866363636363637

Note: NULL values are ignored.

SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails"
table:
Example
SELECT SUM(Price)
FROM Products;

Number of Records: 1
SUM(Price)
2222.71

Note: NULL values are ignored.

28
Test Yourself With Exercises

SQL LIKE Operator

Pengganti tanda =, >,<,>=,<=, <>

THE SQL LIKE O PERATOR


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 represents a single character

The percent sign and the underscore can also be used in combinations!

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

Tip: You can also combine any number of conditions using AND or OR operators.

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"
“a”, “Ai”,”AIN”, “A BU”
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
“a”,”kelapa”,’dia’, ‘kepadanya’
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
“or”,”ora”,”bogor”,”bocor”
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
‘trio’,’bro’,’Tree”
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length
“aku”
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"

Kita akan menggunakan data: Customers.

SQL LIKE Examples


The following SQL statement selects all customers with a CustomerName starting with
"a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

Number of Records: 3
29
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados Juan Avda. de la México 05021 Mexico
y helados Constitución 2222 D.F.
3 Antonio Moreno Taquería Juan Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

The following SQL statement selects all customers with a CustomerName ending with
"a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

Number of Records: 7
CustomerI CustomerName ContactName Address City PostalCode Country
D
3 Antonio Moreno Taquería Juan Mataderos 2312 México D.F. 05023 Mexico
13 Centro comercial Juan Sierras de Granada 9993 México D.F. 05022 Mexico
Moctezuma
30 Godos Cocina Típica José Pedro C/ Romero, 33 Sevilla 41101 Spain
Freyre
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de 02389-673 Brazil
Janeiro
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

The following SQL statement selects all customers with a CustomerName that have "or"
in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

Number of Records: 11
CustomerID CustomerName ContactName Address City PostalCode Country
3 Antonio Moreno Taquería Juan Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
36 Hungry Coyote Import Yoshi Latimer City Center Plaza 516 Main St. Elgin 97827 USA
Store
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA

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

Number of Records: 11

30
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aache 52066 Germany
n
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

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

Number of Records: 3
CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Emparedados y Juan Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
3 Antonio Moreno Taquería Juan Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

The following SQL statement selects all customers with a ContactName that starts with
"a" and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

Number of Records: 1
CustomerI CustomerName ContactName Address City PostalCode Country
D
69 Romero y tomillo Alejandra Gran Vía, Madrid 28001 Spain
Camino 1

The following SQL statement selects all customers with a CustomerName that does
NOT start with "a":

Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

Number of Records: 89
CustomerI CustomerName ContactName Address City PostalCode Country
D
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique 24, place Strasbour 67000 France
Citeaux Kléber g

31
Exercise:
Select all records where the value of the City column starts with the letter "a".

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 SQL LIKE operator. The LIKE operator is used in
a WHERE clause to search for a specified pattern in a column.

WILDCARD CHARACTERS IN SQL SERVER


Symbo Description Example
l
% Represents zero or more characters bl% finds bl, black, blue, and blob
_ Represents a single character h_t finds hot, hat, and hit
[] Represents any single character within the h[oa]t finds hot and hat, but not hit
brackets
^ Represents any character not in the brackets h[^oa]t finds hit, but not hot and hat
- Represents a range of characters c[a-e]t finds cat,cbt,cct,cdt,cet

All the wildcards can also be used in combinations!


Here are some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends 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 starts with "a" and are at least 3
%' characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

USING THE % WILDCARD


The following SQL statement selects all customers with a City starting with "ber":
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';

Number of Records: 2
CustomerI CustomerName ContactName Address City PostalCode Country
D
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
49 Magazzini Alimentari Giovanni Via Ludovico il Moro Bergamo 24100 Italy
Riuniti Rovelli 22

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

Number of Records: 9
CustomerI CustomerName ContactName Address City PostalCode Country
D
12 Cactus Comidas para Patricio Cerrito 333 Buenos Aires 1010 Argentina
llevar Simpson
18 Du monde entier Janine Labrune 67, rue des Cinquante Nantes 44000 France
Otages
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France

USING THE _ WILDCARD


The following SQL statement selects all customers with a City starting with any
character, followed by "ondon":
Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';

Number of Records: 6
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. Londo WA1 1DP UK
n
11 B's Beverages Victoria Fauntleroy Circus Londo EC2 5NT UK
Ashworth n
16 Consolidated Elizabeth Brown Berkeley Gardens 12 Londo WX1 6LT UK
Holdings Brewery n

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

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

Number of Records: 6
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. Londo WA1 1DP UK
n
11 B's Beverages Victoria Fauntleroy Circus Londo EC2 5NT UK
Ashworth n
16 Consolidated Elizabeth Brown Berkeley Gardens 12 Londo WX1 6LT UK
Holdings Brewery n

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

IN Operator Examples
The following SQL statement selects all customers that are located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
sama dengan
SELECT * FROM Customers
WHERE Country='Germany' or Country='France' or Country= 'UK';

Number of Records: 28
CustomerI CustomerName ContactName Address City PostalCode Country
D
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
Delikatessen
7 Blondel père et fils Frédérique 24, place Kléber Strasbourg 67000 France
Citeaux
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France

The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":

Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

Number of Records: 64
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados Juan Avda. de la México 05021 Mexico
y helados Constitución 2222 D.F.
3 Antonio Moreno Taquería Juan Mataderos 2312 México 05023 Mexico
34
D.F.
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

The following SQL statement selects all customers that are from the same countries as
the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

Number of Records: 70
CustomerI CustomerName ContactName Address City PostalCode Country
D
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbour 67000 France
g

Exercise:
Use the IN operator to select all the records where Country is either "Norway" or
"France".

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.

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

BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
35
Number of Records: 29
ProductI ProductNam SupplierID CategoryID Unit Price
D e
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
15 Genen Shouyu 6 2 24 - 250 ml bottles 15.5
16 Pavlova 7 3 32 - 500 g boxes 17.45

NOT BETWEEN Example


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;

Number of Records: 48
ProductI ProductName SupplierI CategoryID Unit Price
D D
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25
7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs. 30

BETWEEN with IN Example


The following SQL statement selects all products with a price BETWEEN 10 and 20. In
addition; do not show products with a CategoryID of 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

Number of Records: 9
ProductID ProductName SupplierID CategoryI Unit Price
D
31 Gorgonzola Telino 14 4 12 - 100 g pkgs 12.5
36 Inlagd Sill 17 8 24 - 250 g jars 19
40 Boston Crab Meat 19 8 24 - 4 oz tins 18.4
42 Singaporean Hokkien Fried Mee 20 5 32 - 1 kg pkgs. 14
46 Spegesild 21 8 4 - 450 g 12
glasses

BETWEEN Text Values Example

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

Number of Records: 37
ProductI ProductName SupplierID CategoryI Unit Price
D D
18 Carnarvon Tigers 7 8 16 kg pkg. 62.5
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
39 Chartreuse verte 18 1 750 cc per bottle 18
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

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;

Number of Records: 5
ProductI ProductName SupplierID CategoryI Unit Price
D D
18 Carnarvon Tigers 7 8 16 kg pkg. 62.5
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
39 Chartreuse verte 18 1 750 cc per bottle 18
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

NOT BETWEEN Text Values Example


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;

Data Products
Number of Records: 40
ProductI ProductName SupplierI CategoryID Unit Price
D D
17 Alice Mutton 7 6 20 - 1 kg tins 39
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
40 Boston Crab Meat 19 8 24 - 4 oz tins 18.4
60 Camembert Pierrot 28 4 15 - 300 g rounds 34

37
Data Orders
Number of Records: 196
OrderI CustomerID EmployeeI OrderDate ShipperID
D D
10248 90 5 1996-07- 3
04
10249 81 6 1996-07- 1
05
10250 34 4 1996-07- 2
08
10251 84 3 1996-07- 1
08

BETWEEN Dates Example


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 #01/07/1996# AND #31/07/1996#;

OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

Number of Records: 22
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07- 3
04
10249 81 6 1996-07- 1
05
10250 34 4 1996-07- 2
08
10251 84 3 1996-07- 1
08

Exercise:
Use the BETWEEN operator to select all the records where the value of the Price column is
between 10 and 20 from Products data.

SQL Aliases

38
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 the query.

ALIAS COLUMN SYNTAX


SELECT column_name AS alias_name
FROM table_name;

ALIAS TABLE SYNTAX


SELECT column_name(s)
FROM table_name AS alias_name;

Alias for Columns Examples


The following SQL statement creates two aliases, one for the CustomerID column and
one for the CustomerName column:
Example No Alias
SELECT CustomerID, CustomerName
FROM Customers;

Number of Records: 92
CustomerID CustomerName
2 Ana Trujillo Emparedados y helados
3 Antonio Moreno Taquería
4 Around the Horn
5 Berglunds snabbköp

Example with Alias


SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

Number of Records: 92
ID Customer
2 Ana Trujillo Emparedados y helados
3 Antonio Moreno Taquería
4 Around the Horn
5 Berglunds snabbköp

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

39
SELECT CustomerName AS Customer, ContactName AS ‘Contact Person’
FROM Customers;

Number of Records: 92
Customer Contact Person
Ana Trujillo Emparedados y helados Juan
Antonio Moreno Taquería Juan
Around the Horn Thomas Hardy

Alias for Tables Example


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;
identik dengan
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the Horn"
AND Customers.CustomerID= Orders.CustomerID;

Number of Records: 2
OrderID OrderDate CustomerName
10355 1996-11- Around the Horn
15
10383 1996-12- Around the Horn
16

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

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

Tabel yang digunakan "Orders" & "Customers":

Tabel Order.
Number of Records: 196
OrderI CustomerI EmployeeID OrderDate ShipperID
D D
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
3 10 7

Tabel "Customers":
Number of Records: 92
CustomerI CustomerName ContactName Address City PostalCode Country
D
2 Ana Trujillo Emparedados y helados Juan Avda. de la Constitución 2222 México 05021 Mexico
D.F.
3 Antonio Moreno Taquería Juan Mataderos 2312 México 05023 Mexico
D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

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.

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

Test Yourself With Exercises


SQL INNER JOIN K EYWORD
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN SYNTAX
SELECT column_name(s)
FROM table1
41
INNER JOIN table2
ON table1.column_name = table2.column_name;

SQL INNER JOIN E XAMPLE


The following SQL statement selects all orders with customer information:
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Number of Records: 196


OrderI CustomerName
D
10248 Wilman Kala
10249 Tradição Hipermercados
10250 Hanari Carnes

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!

JOIN THREE TABLES


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

Number of Records: 196


OrderID CustomerName ShipperName
10248 Wilman Kala Federal Shipping
10249 Tradição Hipermercados Speedy Express
10250 Hanari Carnes United Package

Exercise:
Choose the correct JOIN clause to select all records from the two tables where there is a
match in both tables. Hasilnya:

Number of Records: 196


OrderI CustomerID EmployeeI OrderDate ShipperID CustomerName ContactName Address City PostalCode Country
D D
10248 90 5 1996-07- 3 Wilman Kala Matti Karttunen Keskuskatu Helsinki 21240 Finland
04 45
10249 81 6 1996-07- 1 Tradição Anabela Av. Inês de São 05634-030 Brazil
05 Hipermercados Domingues Castro, 414 Paulo

42
10250 34 4 1996-07- 2 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil
08 67 Janeiro

SQL LEFT JOIN K EYWORD


The LEFT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right side, if
there is no match.
LEFT JOIN SYNTAX
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Example


The following SQL statement 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;

Number of Records: 214


CustomerName OrderID
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10355

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 K EYWORD


The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match.
RIGHT JOIN SYNTAX
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

43
SQL RIGHT JOIN Example
The following SQL statement 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).

Exercise:
Choose the correct JOIN clause to select all the records from the Customers table plus all the
matches in the Orders table.

SQL FULL OUTER JOIN K EYWORD [MY SQL TIDAK BISA LANGSUNG]
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN S YNTAX


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

44
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

CustomerName OrderID
Alfreds Futterkiste Null
Ana Trujillo Emparedados y 10308
helados
Antonio Moreno Taquería 10365

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.

THE SQL UNION O PERATOR


The UNION operator is used to combine the result-set of two or more SELECT
statements.
 Each SELECT statement within UNION must have the same number of
columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order
UNION SYNTAX
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL S YNTAX


The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column names in
the first SELECT statement in the UNION.

SQL UNION EXAMPLE


The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

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

Number of Records: 95
City
Aachen
Albuquerque
Anchorage
Ann Arbor

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;

Number of Records: 121


City
Aachen
Albuquerque
Anchorage

SQL UNION WITH WHERE


The following SQL statement returns the German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Number of Records: 13
City Country
Aachen Germany
Berlin Germany
46
Brandenbur Germany
g

SQL UNION ALL WITH WHERE


The following SQL statement returns the German cities (duplicate values also) from
both the "Customers" and the "Suppliers" table:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Number of Records: 13
City Country
Aachen Germany
Berlin Germany
Brandenbur Germany
g

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;

Number of Records: 117


Type ContactName City Country
Custome null Stavanger Norway
r
Custome Alejandra Camino Madrid Spain
r
Custome Alexander Feuer Leipzig Germany
r

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

==BATAS==

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.
47
GROUP BY S YNTAX
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

SQL GROUP BY E XAMPLES


The following SQL statement lists the number of customers in each country:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

Number of Records: 21
COUNT(CustomerID) Country
3 Argentina
2 Austria
2 Belgium

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;

Number of Records: 21
COUNT(CustomerID) Country
13 USA
11 France
10 Germany

GROUP BY WITH JOIN EXAMPLE


The following SQL statement lists the number of orders sent by each shipper:
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

Number of Records: 3

48
ShipperName NumberOfOrders
Federal 68
Shipping
Speedy Express 54
United Package 74

Exercise:
List the number of customers in each country.

The SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.

The main difference between WHERE and HAVING clause comes when used together
with GROUP BY clause, In that case WHERE is used to filter rows before grouping and
HAVING is used to exclude records after grouping. This is the most important
difference and if you remember this, it will help you write better SQL queries. This is
also one of the important SQL concepts to understand, not just from an interview
perspective but also from a day-to-day use perspective. I am sure you have used
WHERE clause because its one of the most common clause in SQL along with SELECT
and used to specify filtering criterion or condition. You can even use WHERE clause
without HAVING or GROUP BY, as you have seen it many times.

On the other hand, HAVING can only be used if grouping has been performed using
GROUP BY clause in the SQL query. Another worth noting thing about WHERE and
HAVING clause is that WHERE clause cannot contain aggregate function like COUNT(),
SUM(), MAX(), MIN(), etc but HAVING clause may contain aggregate functions.

Another worth noting the difference between WHERE and HAVING clause is that WHERE
is used to impose filtering criterion on a SELECT, UPDATE, DELETE statement as well as
single row function and used before group by clause but HAVING is always used after
group by clause.

HAVING SYNTAX
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

SQL HAVING E XAMPLES


The following SQL statement lists the number of customers in each country. Only
include countries with more than 5 customers:
Example
49
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

Number of Records: 5
COUNT(CustomerID) Country
9 Brazil
11 France
10 Germany
7 UK
13 USA

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:
OrderI CustomerID EmployeeID OrderDat ShipperID
D e
10248 90 5 1996-07- 3
04
10249 81 6 1996-07- 1
05
10250 34 4 1996-07- 2
08

And a selection from the "Employees" table:


EmployeeI LastName FirstName BirthDate Photo Notes
D
1 Davolio Nancy 1968-12- EmpID1.pi Education includes a BA....
08 c
2 Fuller Andrew 1952-02- EmpID2.pi Andrew received his BTS....
19 c
3 Leverling Janet 1963-08- EmpID3.pi Janet has a BS degree....
30 c

MORE HAVING EXAMPLES


50
The following SQL statement lists the employees that have registered more than 10
orders:
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;

Number of Records: 8
LastName NumberOfOrders
Buchanan 11
Callahan 27
Davolio 29
Fuller 20
King 14
Leverling 31
Peacock 40
Suyama 18

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;

Number of Records: 1
LastName NumberOfOrders
Davolio 29

The SQL ANY and ALL Operators

The ANY and ALL operators are used with a WHERE or HAVING clause.
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.

ANY SYNTAX
51
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

ALL SYNTAX
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or
<=).

SQL ANY EXAMPLES


The ANY operator returns TRUE if any of the subquery values meet the condition.
The following SQL statement returns TRUE and lists the product names if it finds ANY
records in the OrderDetails table that quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

Number of Records: 31
ProductName
Chais 
Chang 
Chef Anton's Cajun Seasoning 
Uncle Bob's Organic Dried Pears 

The following SQL statement returns TRUE and lists the product names if it finds ANY
records in the OrderDetails table that quantity > 99:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 99);

Number of Records: 2
ProductName
Steeleye Stout 
Pâté chinois 

SQL ALL EXAMPLE


The ALL operator returns TRUE if all of the subquery values meet the condition.

52
The following SQL statement returns TRUE and lists the product names if ALL the
records in the OrderDetails table has quantity = 10 (so, this example will return FALSE,
because not ALL records in the OrderDetails table has quantity = 10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

Number of Records: 0
ProductName

The SQL Statement to Save the Query Result

Saving the query result may be needed due to other purpose. MySQL Server doesn't support
the SELECT ... INTO TABLE Sybase SQL extension. Instead, MySQL Server supports
the INSERT INTO ... SELECT standard SQL syntax, which is basically the same thing.

We may save the query result in two conditions:


1. The result will be saved in a new table. The SQL is
CREATE TABLE New_table SELECT /* write your here */

2. The result will be saved in an existing table with the same columns table name.
INSERT INTO New_table SELECT /* write your here */

53
The SQL SELECT INTO Statement

The SELECT INTO statement copies data from one table into a new table.
SELECT INTO S YNTAX
Copy all columns into a new table:
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

Copy only some columns into a new table:


SELECT column1, column2, column3, ...
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 E XAMPLES


The following SQL statement creates a backup copy of Customers:
SELECT * INTO CustomersBackup2017
FROM Customers;

The following SQL statement uses the IN clause to copy the table into a new table in
another database:
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;

The following SQL statement copies only a few columns into a new table:
SELECT CustomerName, ContactName INTO CustomersBackup2017
FROM Customers;

The following SQL statement copies only the German customers into a new table:
SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = 'Germany';

The following SQL statement copies data from more than one table into a new table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

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:

54
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;

The SQL INSERT INTO SELECT Statement

The INSERT INTO SELECT statement copies data from one table and inserts it into
another table.
 INSERT INTO SELECT requires that data types in source and target tables match
 The existing records in the target table are unaffected

INSERT INTO SELECT S YNTAX


Copy all columns from one table to another table:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;

Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

SQL INSERT INTO SELECT E XAMPLES


The following SQL statement 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;

You have made changes to the database. Rows affected: 29

The following SQL statement 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;

You have made changes to the database. Rows affected: 29

The following SQL statement copies only the German suppliers into "Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

You have made changes to the database. Rows affected: 3

55
The SQL CASE Statement

The CASE statement goes through conditions and returns a value when the first
condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will
stop reading and return the result. If no conditions are true, it returns the value in the
ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
CASE SYNTAX
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

SQL CASE EXAMPLES


The following SQL goes through conditions and returns a value when the first 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 AS QuantityText
FROM OrderDetails;

Number of Records: 518


OrderID Quantity QuantityText
10248 12 The quantity is under 30
10248 10 The quantity is under 30
10248 5 The quantity is under 30
10249 9 The quantity is under 30
10249 40 The quantity is greater than 30
10250 10 The quantity is under 30
10250 35 The quantity is greater than 30

The following SQL will order the customers by City. However, if City is NULL, then order
by Country:

56
Example
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

Number of Records: 156


CustomerName City Country
Drachenblut Delikatessend Aachen Germany
Rattlesnake Canyon Grocery Albuquerque USA
Old World Delicatessen Anchorage USA
Grandma Kelly's Homestead Ann Arbor USA

SQL NULL Functions

SQL IFNULL(), ISNULL(), COALESCE(), AND NVL() FUNCTIONS


Look at the following "Products" table:
P_I ProductName UnitPrice UnitsInStock UnitsOnOrder
d
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.
Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)


FROM Products;

In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be
NULL.

SOLUTIONS
MySQL
The MySQL IFNULL() function lets you return an alternative value if an expression is
NULL:
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
or we can use the COALESCE() function, like this:
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;

57
SQL COMMENTS
Comments are used to explain sections of SQL statements, or to prevent execution
of SQL statements.
Note: The examples in this chapter will not work in Firefox and Microsoft
Edge!
Comments are not supported in Microsoft Access databases. Firefox and Microsoft Edge
are using Microsoft Access database in our examples.

SINGLE LINE COMMENTS


Single line comments start with --.
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';

The following example uses a single-line comment to ignore a statement:


Example
--SELECT * FROM Customers;
SELECT * FROM Products;

MULTI-LINE COMMENTS
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
The following example uses a multi-line comment as an explanation:
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

The following example uses a multi-line comment to ignore many statements:


Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

To ignore just a part of a statement, also use the /* */ comment.


The following example uses a comment to ignore part of a line:

58
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;

The following example uses a comment to ignore part of a statement:


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 Keywords Reference

This SQL keywords reference contains the reserved words in SQL.

SQL KEYWORDS
Keyword Description
ADD Adds a column in an existing table
ADD CONSTRAINT Adds a constraint after a table is already created
ALTER Adds, deletes, or modifies columns in a table, or changes the data type of a
column in a table
ALTER COLUMN Changes the data type of a column in a table
ALTER TABLE Adds, deletes, or modifies columns in a table
ALL Returns true if all of the subquery values meet the condition
AND Only includes rows where both conditions is true
ANY Returns true if any of the subquery values meet the condition
AS Renames a column or table with an alias
ASC Sorts the result set in ascending order
BACKUP DATABASE Creates a back up of an existing database
BETWEEN Selects values within a given range
CASE Creates different outputs based on conditions
CHECK A constraint that limits the value that can be placed in a column
COLUMN Changes the data type of a column or deletes a column in a table
CONSTRAINT Adds or deletes a constraint
CREATE Creates a database, index, view, table, or procedure
CREATE DATABASE Creates a new SQL database
CREATE INDEX Creates an index on a table (allows duplicate values)
CREATE OR REPLACE Updates a view
VIEW
CREATE TABLE Creates a new table in the database
CREATE PROCEDURE Creates a stored procedure
CREATE UNIQUE Creates a unique index on a table (no duplicate values)
INDEX

59
Keyword Description
CREATE VIEW Creates a view based on the result set of a SELECT statement
DATABASE Creates or deletes an SQL database
DEFAULT A constraint that provides a default value for a column
DELETE Deletes rows from a table
DESC Sorts the result set in descending order
DISTINCT Selects only distinct (different) values
DROP Deletes a column, constraint, database, index, table, or view
DROP COLUMN Deletes a column in a table
DROP CONSTRAINT Deletes a UNIQUE, PRIMARY KEY, FOREIGN KEY, or CHECK constraint
DROP DATABASE Deletes an existing SQL database
DROP DEFAULT Deletes a DEFAULT constraint
DROP INDEX Deletes an index in a table
DROP TABLE Deletes an existing table in the database
DROP VIEW Deletes a view
EXEC Executes a stored procedure
EXISTS Tests for the existence of any record in a subquery
FOREIGN KEY A constraint that is a key used to link two tables together
FROM Specifies which table to select or delete data from
FULL OUTER JOIN Returns all rows when there is a match in either left table or right table
GROUP BY Groups the result set (used with aggregate functions: COUNT, MAX, MIN,
SUM, AVG)
HAVING Used instead of WHERE with aggregate functions
IN Allows you to specify multiple values in a WHERE clause
INDEX Creates or deletes an index in a table
INNER JOIN Returns rows that have matching values in both tables
INSERT INTO Inserts new rows in a table
INSERT INTO SELECT Copies data from one table into another table
IS NULL Tests for empty values
IS NOT NULL Tests for non-empty values
JOIN Joins tables
LEFT JOIN Returns all rows from the left table, and the matching rows from the right
table
LIKE Searches for a specified pattern in a column
LIMIT Specifies the number of records to return in the result set
NOT Only includes rows where a condition is not true
NOT NULL A constraint that enforces a column to not accept NULL values
OR Includes rows where either condition is true
ORDER BY Sorts the result set in ascending or descending order
OUTER JOIN Returns all rows when there is a match in either left table or right table
PRIMARY KEY A constraint that uniquely identifies each record in a database table
PROCEDURE A stored procedure
RIGHT JOIN Returns all rows from the right table, and the matching rows from the left
table
ROWNUM Specifies the number of records to return in the result set
SELECT Selects data from a database
SELECT DISTINCT Selects only distinct (different) values
SELECT INTO Copies data from one table into a new table
SELECT TOP Specifies the number of records to return in the result set
SET Specifies which columns and values that should be updated in a table

60
Keyword Description
TABLE Creates a table, or adds, deletes, or modifies columns in a table, or deletes
a table or data inside a table
TOP Specifies the number of records to return in the result set
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
UNION Combines the result set of two or more SELECT statements (only distinct
values)
UNION ALL Combines the result set of two or more SELECT statements (allows duplicate
values)
UNIQUE A constraint that ensures that all values in a column are unique
UPDATE Updates existing rows in a table
VALUES Specifies the values of an INSERT INTO statement
VIEW Creates, updates, or deletes a view
WHERE Filters a result set to include only records that fulfill a specified condition

MYSQL FUNCTIONS

MySQL has many built-in functions.


This reference contains string, numeric, date, and some advanced functions in
MySQL.

MYSQL STRING FUNCTIONS


Function Description
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LENGTH Returns the length of a string (in characters)
CONCAT Adds two or more expressions together
CONCAT_WS Adds two or more expressions together with a separator
FIELD Returns the index position of a value in a list of values
FIND_IN_SET Returns the position of a string within a list of strings
FORMAT Formats a number to a format like "#,###,###.##", rounded to a specified
number of decimal places
INSERT Inserts a string within a string at the specified position and for a certain
number of characters
INSTR Returns the position of the first occurrence of a string in another string
LCASE Converts a string to lower-case
LEFT Extracts a number of characters from a string (starting from left)
LENGTH Returns the length of a string (in bytes)
LOCATE Returns the position of the first occurrence of a substring in a string
LOWER Converts a string to lower-case
LPAD Left-pads a string with another string, to a certain length
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any position)
POSITION Returns the position of the first occurrence of a substring in a string
REPEAT Repeats a string as many times as specified

61
Function Description
REPLACE Replaces all occurrences of a substring within a string, with a new substring
REVERSE Reverses a string and returns the result
RIGHT Extracts a number of characters from a string (starting from right)
RPAD Right-pads a string with another string, to a certain length
RTRIM Removes trailing spaces from a string
SPACE Returns a string of the specified number of space characters
STRCMP Compares two strings
SUBSTR Extracts a substring from a string (starting at any position)
SUBSTRING Extracts a substring from a string (starting at any position)
SUBSTRING_INDEX Returns a substring of a string before a specified number of delimiter occurs
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case

MYSQL NUMERIC FUNCTIONS


FunctionDescription
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of one or two numbers
ATAN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a number
CEILING Returns the smallest integer value that is >= to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select query
DEGREES Converts a value in radians to degrees
DIV Used for integer division
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a number
GREATESTReturns the greatest value of the list of arguments
LEAST Returns the smallest value of the list of arguments
LN Returns the natural logarithm of a number
LOG Returns the natural logarithm of a number, or the logarithm of a number to a specified
base
LOG10 Returns the natural logarithm of a number to base 10
LOG2 Returns the natural logarithm of a number to base 2
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
MOD Returns the remainder of a number divided by another number
PI Returns the value of PI
POW Returns the value of a number raised to the power of another number
POWER Returns the value of a number raised to the power of another number
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places

62
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number
TRUNCATE Truncates a number to the specified number of decimal places

MYSQL DATE FUNCTIONS

Function Description
ADDDATE Adds a time/date interval to a date and then returns the date
ADDTIME Adds a time interval to a time/datetime and then returns the time/datetime
CURDATE Returns the current date
CURRENT_DATE Returns the current date
CURRENT_TIME Returns the current time
CURRENT_TIMESTAMP Returns the current date and time
CURTIME Returns the current time
DATE Extracts the date part from a datetime expression
DATEDIFF Returns the number of days between two date values
DATE_ADD Adds a time/date interval to a date and then returns the date
DATE_FORMAT Formats a date
DATE_SUB Subtracts a time/date interval from a date and then returns the date
DAY Returns the day of the month for a given date
DAYNAME Returns the weekday name for a given date
DAYOFMONTH Returns the day of the month for a given date
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
EXTRACT Extracts a part from a given date
FROM_DAYS Returns a date from a numeric datevalue
HOUR Returns the hour part for a given date
LAST_DAY Extracts the last day of the month for a given date
LOCALTIME Returns the current date and time
LOCALTIMESTAMP Returns the current date and time
MAKEDATE Creates and returns a date based on a year and a number of days value
MAKETIME Creates and returns a time based on an hour, minute, and second value
MICROSECOND Returns the microsecond part of a time/datetime
MINUTE Returns the minute part of a time/datetime
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
PERIOD_ADD Adds a specified number of months to a period
PERIOD_DIFF Returns the difference between two periods
QUARTER Returns the quarter of the year for a given date value
SECOND Returns the seconds part of a time/datetime
SEC_TO_TIME Returns a time value based on the specified seconds
STR_TO_DATE Returns a date based on a string and a format
SUBDATE Subtracts a time/date interval from a date and then returns the date
SUBTIME Subtracts a time interval from a datetime and then returns the time/datetime
SYSDATE Returns the current date and time
TIME Extracts the time part from a given time/datetime

63
TIME_FORMAT Formats a time by a specified format
TIME_TO_SEC Converts a time value into seconds
TIMEDIFF Returns the difference between two time/datetime expressions
TIMESTAMP Returns a datetime value based on a date or datetime value
TO_DAYS Returns the number of days between a date and date "0000-00-00"
WEEK Returns the week number for a given date
WEEKDAY Returns the weekday number for a given date
WEEKOFYEAR Returns the week number for a given date
YEAR Returns the year part for a given date
YEARWEEK Returns the year and week number for a given date

SQL SERVER STRING FUNCTIONS


SQL Server has many built-in functions.
This reference contains string, numeric, date, conversion, and some advanced
functions in SQL Server.

Function Description
ASCII Returns the ASCII value for the specific character
CHAR Returns the character based on the ASCII code
CHARINDEX Returns the position of a substring in a string
CONCAT Adds two or more strings together
Concat with + Adds two or more strings together
CONCAT_WS Adds two or more strings together with a separator
DATALENGTH Returns the number of bytes used to represent an expression
DIFFERENCE Compares two SOUNDEX values, and returns an integer value
FORMAT Formats a value with the specified format
LEFT Extracts a number of characters from a string (starting from left)
LEN Returns the length of a string
LOWER Converts a string to lower-case
LTRIM Removes leading spaces from a string
NCHAR Returns the Unicode character based on the number code
PATINDEX Returns the position of a pattern in a string
QUOTENAME Returns a Unicode string with delimiters added to make the string a valid SQL
Server delimited identifier
REPLACE Replaces all occurrences of a substring within a string, with a new substring
REPLICATE Repeats a string a specified number of times
REVERSE Reverses a string and returns the result
RIGHT Extracts a number of characters from a string (starting from right)
RTRIM Removes trailing spaces from a string
SOUNDEX Returns a four-character code to evaluate the similarity of two strings
SPACE Returns a string of the specified number of space characters
STR Returns a number as string
STUFF Deletes a part of a string and then inserts another part into the string, starting at a
specified position
SUBSTRING Extracts some characters from a string
TRANSLATE Returns the string from the first argument after the characters specified in the
second argument are translated into the characters specified in the third argument.
TRIM Removes leading and trailing spaces (or other specified characters) from a string
UNICODE Returns the Unicode value for the first character of the input expression
UPPER Converts a string to upper-case

64
SQL SERVER MATH/NUMERIC FUNCTIONS
Functio Description
n
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of a number
ATN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEILING Returns the smallest integer value that is >= a number
COUNT Returns the number of records returned by a select query
COS Returns the cosine of a number
COT Returns the cotangent of a number
DEGREES Converts a value in radians to degrees
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a number
LOG Returns the natural logarithm of a number, or the logarithm of a number to a specified
base
LOG10 Returns the natural logarithm of a number to base 10
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
PI Returns the value of PI
POWER Returns the value of a number raised to the power of another number
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square root of a number
SQUARE Returns the square of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number

SQL SERVER DATE FUNCTIONS


Function Description
CURRENT_TIMESTAM Returns the current date and time
P
DATEADD Adds a time/date interval to a date and then returns the date
DATEDIFF Returns the difference between two dates
DATEFROMPARTS Returns a date from the specified parts (year, month, and day values)
DATENAME Returns a specified part of a date (as string)
DATEPART Returns a specified part of a date (as integer)
DAY Returns the day of the month for a specified date
GETDATE Returns the current database system date and time
GETUTCDATE Returns the current database system UTC date and time
ISDATE Checks an expression and returns 1 if it is a valid date, otherwise 0
MONTH Returns the month part for a specified date (a number from 1 to 12)
SYSDATETIME Returns the date and time of the SQL Server
65
YEAR Returns the year part for a specified date

SQL ARITHMETIC OPERATORS


Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulo

SQL BITWISE OPERATORS


Operato Description
r
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

SQL COMPARISON OPERATORS


Operato Description
r
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

SQL LOGICAL OPERATORS


Operato Description
r
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

SQL QUICK REFERENCE FROM W3SCHOOLS


SQL Statement Syntax
AND / OR SELECT column_name(s)
FROM table_name
WHERE condition
66
SQL Statement Syntax
AND|OR condition
ALTER TABLE ALTER TABLE table_name
ADD column_name datatype
or
ALTER TABLE table_name
DROP COLUMN column_name
AS (alias) SELECT column_name AS column_alias
FROM table_name
or
SELECT column_name
FROM table_name AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
or
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE DELETE FROM table_name
WHERE some_column=some_value
or
DELETE FROM table_name
(Note: Deletes the entire table!!)
DELETE * FROM table_name
(Note: Deletes the entire table!!)
DROP DATABASE DROP DATABASE database_name
DROP INDEX DROP INDEX table_name.index_name (SQL Server)
DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)
DROP TABLE DROP TABLE table_name
EXISTS IF EXISTS (SELECT * FROM table_name WHERE id = ?)
BEGIN
--do what needs to be done if exists
END
ELSE
BEGIN
--do what needs to be done if not
END
GROUP BY SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING SELECT column_name, aggregate_function(column_name)
67
SQL Statement Syntax
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
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
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
INNER JOIN SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LEFT JOIN SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
RIGHT JOIN SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FULL JOIN SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LIKE SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT SELECT column_name(s)
FROM table_name
SELECT * SELECT *
FROM table_name
SELECT DISTINCT SELECT DISTINCT column_name(s)
FROM table_name
SELECT INTO SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP SELECT TOP number|percent column_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

68
SQL Statement Syntax
UPDATE UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE column_name operator value

Source : https://www.w3schools.com/sql

69

You might also like