SQL With Mysql
SQL With Mysql
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
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
4
RDBMS
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.
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:
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;
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;
Number of Records: 91
Country
Germany
9
Mexico
Mexico
UK
Sweden
Germany
France
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
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
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';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
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';
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
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
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
17
SQL INSERT INTO Statement
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, ...);
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.
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
IS NULL Syntax
19
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Number of Records: 1
CustomerNam ContactName Address
e
Cardinal null 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.
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;
Number of Records: 1
CustomerI CustomerName ContactNam Address City PostalCode Country
D e
1 Alfreds Futterkiste Alfred Schmidt Obere Str. Frankfurt 12209 Germany
57
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';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be
updated!
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!
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
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
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
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
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
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
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
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
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
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
28
Test Yourself With Exercises
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"
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
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
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
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".
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
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
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
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
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
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.
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
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
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;
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 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.
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!
Exercise:
Choose the correct JOIN clause to select all records from the two tables where there is a
match in both tables. Hasilnya:
42
10250 34 4 1996-07- 2 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil
08 67 Janeiro
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even
if there are no matches in the right table (Orders).
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.
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.
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!
Number of Records: 13
City Country
Aachen Germany
Berlin Germany
46
Brandenbur Germany
g
Number of Records: 13
City Country
Aachen Germany
Berlin Germany
Brandenbur Germany
g
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==
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
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 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);
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
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 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
<=).
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
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
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.
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;
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.
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 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
Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
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;
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';
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;
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);
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
Look at the following SELECT statement:
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.
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
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;
58
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
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
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
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
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
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
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