Data Base System

Assignment 3

Kontak : \(\downarrow\)
Email
Instagram https://www.instagram.com/dhelaagatha/
RPubs https://rpubs.com/dhelaasafiani/
Nama Dhela Asafiani Agatha
NIM 20214920009
Prodi Statistika 2021

Introduction

# set up the connection and save it into the workspace
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
library(RMySQL)
library(DBI)
dhela <- dbConnect(RMySQL::MySQL(),
                   dbname='new_mariadb',
                   username='root',
                   password='',
                   host='localhost',
                   port=3306)
knitr::opts_chunk$set(connection = "dhela")  #set up the connection

SELECT

SELECT digunakan untuk mengambil data dari tabel database yang mengembalikan data ini dalam bentuk tabel hasil.

SELECT CustomerName, Address, City, Country
  FROM CUSTOMERS;
Displaying records 1 - 10
CustomerName Address City Country
Alfreds Futterkiste Obere Str. 57 Mexico Germany
Ana Trujillo Emparedados y helados Avda. de la Constitución 2222 México D.F. Mexico
Antonio Moreno Taquería Mataderos 2312 México D.F. Mexico
Around the Horn 120 Hanover Sq. London UK
Berglunds snabbköp Berguvsvägen 8 Luleå Sweden
Blauer See Delikatessen Forsterstr. 57 Mannheim Germany
Blondel père et fils 24, place Kléber Strasbourg France
Bólido Comidas preparadas C/ Araquil, 67 Madrid Spain
Bon app’ 12, rue des Bouchers Marseille France
Bottom-Dollar Marketse 23 Tsawassen Blvd. Tsawassen Canada

Jika Anda ingin mengambil semua bidang tabel PELANGGAN, maka Anda harus menggunakan kueri berikut.

SELECT *
  FROM CUSTOMERS;
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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 Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada

DISTINCT

DISTINCT berfungsi untuk menampilkan nilai yang berbeda. Biasanya dalam tabel terdapat kolom yang memiliki nilai duplikat, kita bisa menggunakan Distinct untuk menghilangkan nilai duplikat tersebut. Cara menggunakan Distinct yaitu bersamaan dengan Select seperti syntax di bawah ini :

SELECT DISTINCT Country
  FROM customers;
Displaying records 1 - 10
Country
Germany
Mexico
UK
Sweden
France
Spain
Canada
Argentina
Switzerland
Brazil

WHERE

WHERE berfungsi untuk menyaring atau memfilter record. Dengan kata lain, Where juga dipakai dalam menentukan kondisi ketika bergabung dengan beberapa tabel atau mengambil data dari satu tabel. Selain bersamaan dengan SELECT, Where juga bisa digunakan bersamaan dengan UPDATE, DELETE, dan perintah dasar SQL lainnya. Berikut ini syntax untuk memilih semua Customer dari negara Mexico :

SELECT *
  FROM Customers
    WHERE Country='Mexico';
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 5022 Mexico
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 5033 Mexico
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 5033 Mexico
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 5022 Mexico
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 5033 Mexico
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 5033 Mexico

Untuk menggunakan WHERE, kita harus memahami operator-operator yang digunakan dalam WHERE. Operator tersebut yaitu :
1. = (sama dengan)
2. > (lebih besar dari)
3. < (lebih kecil dari)
4. >= (lebih besar sama dengan)
5. <= (lebih kecil sama dengan)
6. <> atau != (tidak sama)
7. IS NULL atau IS NOT NUL (field tanpa nilai)
8. BETWEEN (antara range tertentu)
9. LIKE (mencari pola)
10. IN (menentukan beberapa kemungkinan nilai untuk kolom)

BETWEEN

BETWEEN berfungsi untuk memilih nilai dalam range tertentu. nilai tersebut bisa berupa angka, teks, ataupun tanggal. Between bisa digunakan bersamaan dengan SELECT, INSERT, UPDATE, atau DELETE.

Di bawah ini merupakan syntax Between menggunakan range angka :

SELECT *
  FROM Products
    WHERE Price
      BETWEEN 10 AND 20;
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18.00
2 Chang 1 1 24 - 12 oz bottles 19.00
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.00
15 Genen Shouyu 6 2 24 - 250 ml bottles 15.50
16 Pavlova 7 3 32 - 500 g boxes 17.45
21 Sir Rodney’s Scones 8 3 24 pkgs. x 4 pieces 10.00
25 NuNuCa Nuß-Nougat-Creme 11 3 20 - 450 g glasses 14.00
31 Gorgonzola Telino 14 4 12 - 100 g pkgs 12.50
34 Sasquatch Ale 16 1 24 - 12 oz bottles 14.00
35 Steeleye Stout 16 1 24 - 12 oz bottles 18.00

Di bawah ini merupakan syntax Between menggunakan range tanggal :

SELECT *
  FROM Orders
    WHERE OrderDate
      BETWEEN '1996-07-01' AND '1996-07-31';
Displaying records 1 - 10
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
10251 84 3 1996-07-08 1
10252 76 4 1996-07-09 2
10253 34 3 1996-07-10 2
10254 14 5 1996-07-11 2
10255 68 9 1996-07-12 3
10256 88 3 1996-07-15 2
10257 35 4 1996-07-16 3

IN

IN berfungsi untuk menentukan beberapa kemungkinan nilai untuk kolom. Kita bisa gunakan IN bersamaan dengan WHERE jika ingin menggunakan lebih dari 2 kondisi. Berikut ini syntax dengan memilih semua Customer yang berlokasi di “Germany”, “France”, atau “UK” :

SELECT *
  FROM Customers
    WHERE Country
      IN ('Germany', 'France', 'UK');
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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 Strasbourg 67000 France
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
11 B’s Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
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

Berikut ini syntax dengan memilih semua Customer yang berasal dari negara yang sama dengan Suppliernya :

SELECT *
  FROM Customers
    WHERE Country
      IN (SELECT Country FROM Suppliers);
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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 Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
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
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil

LIKE

LIKE berfungsi untuk mencari pola yang spesifik pada kolom. Like digunakan bersamaan dengan WHERE. Biasanya pada like, kita juga menggunakan % (mewakili multi character) atau _ (mewakili single character). Di bawah ini syntax dengan memilih semua Customer yang CustomerName-nya dimulai dengan huruf “a” :

SELECT *
  FROM Customers
    WHERE CustomerName
      LIKE 'a%';
8 records
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Penerapan % dan _ sebagai berikut :
1. WHERE CustomerName LIKE ‘a%’ (mencari nilai berawalan “a”)
2. WHERE CustomerName LIKE ‘%a’ (mencari nilai berakhiran “a”)
3. WHERE CustomerName LIKE ‘%or%’ (mencari nilai yang memiliki “or” di suatu posisi)
4. WHERE CustomerName LIKE ‘r%’ (mencari nilai yang memiliki “r” di posisi kedua)
5. WHERE CustomerName LIKE ’a
%’ (mencari nilai berawalan “a” dan setidaknya 2 karakter panjangnya)
6. WHERE CustomerName LIKE ’a__%’ (mencari nilai berawalan “a” dan setidaknya 3 karakter panjangnya)
7. WHERE ContactName LIKE ‘a%o’

AND, OR and NOT

Argumen ini bisa dikombinasikan dengan argumen WHERE.
- operasi AND dimana akan terlihat hasilnya jika kedua data tersebut sama atau bernilai TRUE dan akan eror jika ada salah satu yang tidak sama atau bernilai FALSE.
- operasi OR dimana akan terlihat hasilnya jika salah satu data tersebut bernilai TRUE atau sesuai dengan kondisi yang diingikan.
- operasi NOT adalah operasi yang menampilkan hasil yang bernilai FALSE.

Syntax di bawah ini memilih semua field dari “Customers” yang negaranya adalah “Germany” dan kotanya “Berlin atau”München” :

SELECT * 
  FROM Customers C
    WHERE C.Country='Germany' AND (C.City='Berlin' OR C.City='München');
2 records
CustomerID CustomerName ContactName Address City PostalCode Country
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

Jika kita ingin menggunakan NOT pada WHERE dapat diwakilkan dengan <>

SELECT * 
  FROM Customers C
    WHERE C.Country <> 'Germany' AND C.Country <> 'USA';
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
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 llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina

ORDER BY

ORDER BY berfungsi untuk mengurutkan data dari besar ke kecil (z-a) atau bisa juga kecil ke besar (a-z) berdasarkan satu atau lebih kolom.
- DESC atau descending yaitu mengurutkan data dari besar ke kecil.
- ASC atau ascending yaitu mengurutkan data dari kecil ke besar.
- Akan tetapi jika kita tidak menggunakan keyword DESC atau ASC maka data akan diurutkan otomatis dengan ASC.

Berikut ini syntaxnya :

SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München')
  ORDER BY Country, City;
2 records
CustomerID CustomerName ContactName Address City PostalCode Country
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

LIMIT

LIMIT berfungsi untuk menentukan jumlah record yang akan ditampilkan. Selain bersamaan dengan WHERE dan ORDER BY, LIMIT juga bisa dipadukan dengan OFFSET.

top 3 rows:

SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München')
  ORDER BY Country, City
    LIMIT 3;
2 records
CustomerID CustomerName ContactName Address City PostalCode Country
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

top 5 rows setelah top 3 rows :

SELECT CustomerName, Address, City, Country
  FROM customers
  ORDER BY City, Country DESC
    LIMIT 3, 5;
5 records
CustomerName Address City Country
Rattlesnake Canyon Grocery 2817 Milton Dr. Albuquerque USA
Old World Delicatessen 2743 Bering St. Anchorage USA
Old World Delicatessen 2743 Bering St. Anchorage USA
Vaffeljernet Smagsløget 45 Århus Denmark
Vaffeljernet Smagsløget 45 Århus Denmark

MIN and MAX

MIN dan MAX berfungsi untuk menentukan nilai terkecil dan terbesar dalam bidang berdasakan pengelompokan yang ditentukan.

syntax min untuk menentukan harga produk termurah:

SELECT MIN(Price) AS SmallestPrice
  FROM Products;
1 records
SmallestPrice
2.5

syntax max untuk menentukan harga produk terbesar:

SELECT MAX(Price) AS LargestPrice
  FROM Products;
1 records
LargestPrice
263.5

COUNT, SUM and AVG

COUNT berfungsi untuk menentukan jumlah baris yang cocok dengan kriteria tertentu. SUM berfungsi untuk menjumlah total kolom numerik. AVG berfungsi untuk menghitung nilai rata-rata kolom numerik.

syntax count :

SELECT COUNT(P.Price)
  FROM Products P;
1 records
COUNT(P.Price)
154

syntax sum :

SELECT SUM(P.Price)
  FROM Products P;
1 records
SUM(P.Price)
4445.42

syntax avg :

SELECT AVG(P.Price)
  FROM Products P;
1 records
AVG(P.Price)
28.86636

HAVING

HAVING digunakan sebagai pengganti WHERE dengan fungsi agregat (COUNT, MAX, MIN, SUM, AVG).

syntax having dengan menggunakan fungsi COUNT:

SELECT COUNT(C.CustomerID), C.Country
  FROM Customers C
    GROUP BY C.Country
      HAVING COUNT(C.CustomerID) > 5
        ORDER BY COUNT(C.CustomerID) DESC;
Displaying records 1 - 10
COUNT(C.CustomerID) Country
26 USA
22 Germany
22 France
18 Brazil
14 UK
10 Spain
10 Mexico
8 Venezuela
6 Italy
6 Canada

CASE

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;
Displaying records 1 - 10
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
10250 15 The quantity is under 30
10251 6 The quantity is under 30
10251 15 The quantity is under 30
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);
Displaying records 1 - 10
CustomerName City Country
Drachenblut Delikatessend Aachen Germany
Drachenblut Delikatessend Aachen Germany
Rattlesnake Canyon Grocery Albuquerque USA
Rattlesnake Canyon Grocery Albuquerque USA
Old World Delicatessen Anchorage USA
Old World Delicatessen Anchorage USA
Vaffeljernet Ã…rhus Denmark
Vaffeljernet Ã…rhus Denmark
Galería del gastrónomo Barcelona Spain
Galería del gastrónomo Barcelona Spain

Exercise

# set up the connection and save it into the workspace
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
library(RMySQL)
library(DBI)
dhela<- dbConnect(RMySQL::MySQL(),
                   dbname='new_mariadb',
                   username='root',
                   password='',
                   host='localhost',
                   port=3306)
knitr::opts_chunk$set(connection = "dhela")  #set up the connecti

1. Select Some attributes of suppliers in alphabetical order!

SELECT SupplierName, ContactName, Address, Country, City
FROM suppliers
ORDER BY SupplierName
Displaying records 1 - 10
SupplierName ContactName Address Country City
Aux joyeux ecclésiastiques Guylène Nodier 203, Rue des Francs-Bourgeois France Paris
Aux joyeux ecclésiastiques Guylène Nodier 203, Rue des Francs-Bourgeois France Paris
Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 USA Bend
Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 USA Bend
Cooperativa de Quesos ‘Las Cabras’ Antonio del Valle Saavedra Calle del Rosal 4 Spain Oviedo
Cooperativa de Quesos ‘Las Cabras’ Antonio del Valle Saavedra Calle del Rosal 4 Spain Oviedo
Escargots Nouveaux Marie Delamare 22, rue H. Voiron France Montceau
Escargots Nouveaux Marie Delamare 22, rue H. Voiron France Montceau
Exotic Liquid Charlotte Cooper 49 Gilbert St. UK Londona
Exotic Liquid Charlotte Cooper 49 Gilbert St. UK Londona

2. Some attributes of suppliers in reverse alphabetical order!

SELECT SupplierName, ContactName, Address, Country, City
FROM suppliers
ORDER BY SupplierName DESC
Displaying records 1 - 10
SupplierName ContactName Address Country City
Zaanse Snoepfabriek Dirk Luchte Verkoop Rijnweg 22 Netherlands Zaandam
Zaanse Snoepfabriek Dirk Luchte Verkoop Rijnweg 22 Netherlands Zaandam
Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Japan Tokyo
Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Japan Tokyo
Svensk Sjöföda AB Michael Björn Brovallavägen 231 Sweden Stockholm
Svensk Sjöföda AB Michael Björn Brovallavägen 231 Sweden Stockholm
Specialty Biscuits, Ltd. Peter Wilson 29 King’s Way UK Manchester
Specialty Biscuits, Ltd. Peter Wilson 29 King’s Way UK Manchester
Refrescos Americanas LTDA Carlos Diaz Av. das Americanas 12.890 Brazil São Paulo
Refrescos Americanas LTDA Carlos Diaz Av. das Americanas 12.890 Brazil São Paulo

3. Some attributes of suppliers ordered by country, then by city!

SELECT SupplierName, ContactName, Address, Country, City
FROM suppliers
ORDER BY Country, City
Displaying records 1 - 10
SupplierName ContactName Address Country City
Pavlova, Ltd. Ian Devling 74 Rose St. Moonie Ponds Australia Melbourne
Pavlova, Ltd. Ian Devling 74 Rose St. Moonie Ponds Australia Melbourne
G’day, Mate Wendy Mackenzie 170 Prince Edward Parade Hunter’s Hill Australia Sydney
G’day, Mate Wendy Mackenzie 170 Prince Edward Parade Hunter’s Hill Australia Sydney
Refrescos Americanas LTDA Carlos Diaz Av. das Americanas 12.890 Brazil São Paulo
Refrescos Americanas LTDA Carlos Diaz Av. das Americanas 12.890 Brazil São Paulo
Ma Maison Jean-Guy Lauzon 2960 Rue St. Laurent Canada Montréal
Ma Maison Jean-Guy Lauzon 2960 Rue St. Laurent Canada Montréal
Forêts d’érables Chantal Goulet 148 rue Chasseur Canada Ste-Hyacinthe
Forêts d’érables Chantal Goulet 148 rue Chasseur Canada Ste-Hyacinthe

4. All atributes of suppliers and reverse alphabetical ordered by country, then by city!

SELECT *
FROM suppliers
ORDER BY Country DESC, City DESC
Displaying records 1 - 10
SupplierID SupplierName ContactName Address City PostalCode Country Phone
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822
19 New England Seafood Cannery Robb Merchant Order Processing Dept. 2100 Paul Revere Blvd. Boston 2134 USA (617) 555-3267
19 New England Seafood Cannery Robb Merchant Order Processing Dept. 2100 Paul Revere Blvd. Boston 2134 USA (617) 555-3267
16 Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 Bend 97101 USA (503) 555-9931
16 Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 Bend 97101 USA (503) 555-9931
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA (313) 555-5735
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA (313) 555-5735
8 Specialty Biscuits, Ltd. Peter Wilson 29 King’s Way Manchester M14 GSD UK (161) 555-4448
8 Specialty Biscuits, Ltd. Peter Wilson 29 King’s Way Manchester M14 GSD UK (161) 555-4448

5. All orders, sorted by total amount, the largest first!

SELECT o.*, od.Quantity
  FROM orders o
    JOIN orderdetails od
      ON o.OrderID = od.OrderID
        ORDER BY od.Quantity DESC;
Displaying records 1 - 10
OrderID CustomerID EmployeeID OrderDate ShipperID Quantity
10398 71 2 1996-12-30 3 120
10398 71 2 1996-12-30 3 120
10286 63 8 1996-08-21 3 100
10286 63 8 1996-08-21 3 100
10440 71 4 1997-02-10 2 90
10440 71 4 1997-02-10 2 90
10345 63 2 1996-11-04 2 80
10373 37 4 1996-12-05 3 80
10345 63 2 1996-11-04 2 80
10373 37 4 1996-12-05 3 80

6. Get all but the 10 most expensive products sorted by price!

SELECT *
FROM products
ORDER BY Price DESC
LIMIT 10
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
38 Côte de Blaye 18 1 12 - 75 cl bottles 263.50
38 Côte de Blaye 18 1 12 - 75 cl bottles 263.50
29 Thüringer Rostbratwurst 12 6 50 bags x 30 sausgs. 123.79
29 Thüringer Rostbratwurst 12 6 50 bags x 30 sausgs. 123.79
9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97.00
9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97.00
20 Sir Rodney’s Marmalade 8 3 30 gift boxes 81.00
20 Sir Rodney’s Marmalade 8 3 30 gift boxes 81.00
18 Carnarvon Tigers 7 8 16 kg pkg. 62.50
18 Carnarvon Tigers 7 8 16 kg pkg. 62.50

7. Get the 10th to 15th most expensive products sorted by price!

SELECT *
FROM products
ORDER BY Price DESC
LIMIT 10,15;
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
59 Raclette Courdavault 28 4 5 kg pkg. 55.0
59 Raclette Courdavault 28 4 5 kg pkg. 55.0
51 Manjimup Dried Apples 24 7 50 - 300 g pkgs. 53.0
51 Manjimup Dried Apples 24 7 50 - 300 g pkgs. 53.0
62 Tarte au sucre 29 3 48 pies 49.3
62 Tarte au sucre 29 3 48 pies 49.3
43 Ipoh Coffee 20 1 16 - 500 g tins 46.0
43 Ipoh Coffee 20 1 16 - 500 g tins 46.0
28 Rössle Sauerkraut 12 7 25 - 825 g cans 45.6
28 Rössle Sauerkraut 12 7 25 - 825 g cans 45.6

8. List all supplier countries in alphabetical order!

SELECT DISTINCT Country
FROM suppliers
ORDER BY Country
Displaying records 1 - 10
Country
Australia
Brazil
Canada
Denmark
Finland
France
Germany
Italy
Japan
Netherlands

9. Find the cheapest product and Expensive Orders!

9.1 Cheapest Product

SELECT ProductName, Unit, Price
FROM products
ORDER BY Price
LIMIT 1
1 records
ProductName Unit Price
Geitost 500 g 2.5

9.2 Expensive Product

SELECT ProductName, Unit, Price
FROM products
ORDER BY Price DESC
LIMIT 1
1 records
ProductName Unit Price
Côte de Blaye 12 - 75 cl bottles 263.5

ini yg 9.2 gbs kluar hasil dh wkwk, tolong yyyyy

10. Find the number of Supplier USA!

SELECT *
FROM suppliers
WHERE Country='USA'
8 records
SupplierID SupplierName ContactName Address City PostalCode Country Phone
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA (313) 555-5735
16 Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 Bend 97101 USA (503) 555-9931
19 New England Seafood Cannery Robb Merchant Order Processing Dept. 2100 Paul Revere Blvd. Boston 2134 USA (617) 555-3267
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA (313) 555-5735
16 Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 Bend 97101 USA (503) 555-9931
19 New England Seafood Cannery Robb Merchant Order Processing Dept. 2100 Paul Revere Blvd. Boston 2134 USA (617) 555-3267

11. Compute the total Quantity of orderitem!

SELECT SUM(Quantity)
FROM orderdetails
1 records
SUM(Quantity)
25486

12. Compute the average UnitPrice of all product!

SELECT AVG(Price)
FROM products
1 records
AVG(Price)
28.86636

13. Get all information about customer named Thomas Hardy!

SELECT *
FROM customers
WHERE ContactName='Thomas Hardy'
2 records
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

14. List all customers from Spain or France!

SELECT *
FROM customers
WHERE Country='Spain' OR Country='France'
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 8022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
40 La corne d’abondance Daniel Tonini 67, avenue de l’Europe Versailles 78000 France

15. List all customers that are not from the USA!

SELECT *
FROM customers
WHERE Country!='USA'
Displaying records 1 - 10
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Agatha Obere Str. 57 Mexico 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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 Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app’ Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada

16. List all orders that not between $50 and $15000!

SELECT o.OrderDate, p.ProductID, p.ProductName, p.Price
FROM orders o
JOIN orderdetails od
ON o.OrderID = od.OrderID
JOIN products p
ON od.ProductID = p.ProductID
WHERE Price NOT BETWEEN 50 AND 15000
Displaying records 1 - 10
OrderDate ProductID ProductName Price
1996-07-04 11 Queso Cabrales 21.00
1996-07-04 11 Queso Cabrales 21.00
1996-07-04 42 Singaporean Hokkien Fried Mee 14.00
1996-07-04 42 Singaporean Hokkien Fried Mee 14.00
1996-07-04 72 Mozzarella di Giovanni 34.80
1996-07-04 72 Mozzarella di Giovanni 34.80
1996-07-05 14 Tofu 23.25
1996-07-05 14 Tofu 23.25
1996-07-08 41 Jack’s New England Clam Chowder 9.65
1996-07-08 41 Jack’s New England Clam Chowder 9.65

17. List all products between $10 and $20

SELECT *
FROM products
WHERE Price BETWEEN 10 AND 20
ORDER BY Price
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
21 Sir Rodney’s Scones 8 3 24 pkgs. x 4 pieces 10.0
21 Sir Rodney’s Scones 8 3 24 pkgs. x 4 pieces 10.0
74 Longlife Tofu 4 7 5 kg pkg. 10.0
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.0
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.0
74 Longlife Tofu 4 7 5 kg pkg. 10.0
46 Spegesild 21 8 4 - 450 g glasses 12.0
46 Spegesild 21 8 4 - 450 g glasses 12.0
68 Scottish Longbreads 8 3 10 boxes x 8 pieces 12.5
31 Gorgonzola Telino 14 4 12 - 100 g pkgs 12.5

18. List all products not between $10 and $100 sorted by price!

SELECT *
FROM products
WHERE Price NOT BETWEEN 10 AND 20
ORDER BY Price
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
33 Geitost 15 4 500 g 2.50
33 Geitost 15 4 500 g 2.50
24 Guaraná Fantástica 10 1 12 - 355 ml cans 4.50
24 Guaraná Fantástica 10 1 12 - 355 ml cans 4.50
13 Konbu 6 8 2 kg box 6.00
13 Konbu 6 8 2 kg box 6.00
52 Filo Mix 24 5 16 - 2 kg boxes 7.00
52 Filo Mix 24 5 16 - 2 kg boxes 7.00
54 Tourtière 25 6 16 pies 7.45
54 Tourtière 25 6 16 pies 7.45

19. Get the list of orders and amount sold between 1996 Jan 01 and 1996 Des 31!

SELECT *
FROM orders
WHERE OrderDate BETWEEN '1996-01-01' AND '1996-12-31';
Displaying records 1 - 10
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
10251 84 3 1996-07-08 1
10252 76 4 1996-07-09 2
10253 34 3 1996-07-10 2
10254 14 5 1996-07-11 2
10255 68 9 1996-07-12 3
10256 88 3 1996-07-15 2
10257 35 4 1996-07-16 3

20. List all suppliers from the USA, UK, OR Japan!

SELECT *
FROM suppliers
WHERE Country='USA' OR Country='UK' OR Country='Japan'
Displaying records 1 - 10
SupplierID SupplierName ContactName Address City PostalCode Country Phone
1 Exotic Liquid Charlotte Cooper 49 Gilbert St. Londona EC1 4SD UK (171) 555-2222
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA (313) 555-5735
4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Tokyo 100 Japan (03) 3555-5011
6 Mayumi’s Mayumi Ohno 92 Setsuko Chuo-ku Osaka 545 Japan (06) 431-7877
8 Specialty Biscuits, Ltd. Peter Wilson 29 King’s Way Manchester M14 GSD UK (161) 555-4448
16 Bigfoot Breweries Cheryl Saylor 3400 - 8th Avenue Suite 210 Bend 97101 USA (503) 555-9931
19 New England Seafood Cannery Robb Merchant Order Processing Dept. 2100 Paul Revere Blvd. Boston 2134 USA (617) 555-3267
1 Exotic Liquid Charlotte Cooper 49 Gilbert St. Londona EC1 4SD UK (171) 555-2222
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA (100) 555-4822

21. List all products that are not exactly $10, $20, $30, $40, or $50!

SELECT *
FROM products
WHERE Price NOT IN(10,20,30,40,50)
Displaying records 1 - 10
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18.00
2 Chang 1 1 24 - 12 oz bottles 19.00
4 Chef Anton’s Cajun Seasoning 2 2 48 - 6 oz jars 22.00
5 Chef Anton’s Gumbo Mix 2 2 36 boxes 21.35
6 Grandma’s Boysenberry Spread 3 2 12 - 8 oz jars 25.00
9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97.00
10 Ikura 4 8 12 - 200 ml jars 31.00
11 Queso Cabrales 5 4 1 kg pkg. 21.00
12 Queso Manchego La Pastora 5 4 10 - 500 g pkgs. 38.00
13 Konbu 6 8 2 kg box 6.00

22. List all customers that are from the same countries as the suppliers!

SELECT c.CustomerName, s.SupplierName, c.Country, s.Country
FROM customers c
JOIN orders o
ON c.CustomerID = o.CustomerID
JOIN orderdetails od
ON o.OrderID = od.OrderID
JOIN products p
ON od.ProductID = p.ProductID
JOIN suppliers s
ON p.SupplierID = s.SupplierID
WHERE c.Country = s.Country
Displaying records 1 - 10
CustomerName SupplierName Country Country
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Old World Delicatessen New England Seafood Cannery USA USA
Rattlesnake Canyon Grocery New Orleans Cajun Delights USA USA
Rattlesnake Canyon Grocery New Orleans Cajun Delights USA USA

23. List all products that start with ‘Cha’ or ‘Chan’ and have one more character!

SELECT *
FROM products
WHERE ProductName LIKE 'Cha_' OR ProductName LIKE 'Chan_'
2 records
ProductID ProductName SupplierID CategoryID Unit Price
2 Chang 1 1 24 - 12 oz bottles 19
2 Chang 1 1 24 - 12 oz bottles 19

24. List all suppliers that do have a fax number!

Tidak ada kolom nomor Fax, maka dianggap para pembeli tidak mempunyai nomor Fax.

25. List all customer with average orders between $1000 and $1200 !

SELECT CustomerName, AVG(TotalAmount) AverageOrders
FROM 
(
SELECT CustomerName, SUM(od.Quantity * p.Price) TotalAmount
FROM customers c
JOIN orders o
ON c.CustomerID = o.CustomerID
JOIN orderdetails od
ON o.OrderID = od.OrderID
JOIN products p
ON od.ProductID = p.ProductID
GROUP BY od.OrderID
) A
GROUP BY CustomerName
HAVING AverageOrders
BETWEEN 1000 AND 1200
ORDER BY AverageOrders
1 records
CustomerName AverageOrders
Centro comercial Moctezuma 1008

26. List total customers in each country.

SELECT Country, COUNT(CustomerName) TotalCustomer
FROM customers
GROUP BY Country
Displaying records 1 - 10
Country TotalCustomer
Argentina 6
Austria 4
Belgium 4
Brazil 18
Canada 6
Denmark 4
Finland 4
France 22
Germany 22
Indonesia 1