๐Ÿ“– Database Technology โ€“ Kisi-Kisi Lengkap 20 Case/Topik

MySQL Quiz Master Guide

Materi lengkap 20 case per topik termasuk yang kompleks: GROUP BY, HAVING, CASE WHEN, subquery, aggregate, dan pola soal khas Binus. Semangat! ๐Ÿ’ช

๐Ÿ” Select Data 20
๐Ÿ”— UNION 20
โ†•๏ธ ORDER BY 10
๐Ÿ”ง ALTER TABLE 10
๐Ÿ‘๏ธ CREATE VIEW 20
โœ๏ธ UPDATE 10
๐Ÿ—‘๏ธ DELETE 10
๐Ÿ“‹
Skema Tabel Referensi (Binus Style)
Semua contoh menggunakan tabel-tabel ini
TabelKolom UtamaKeterangan
TransactionHeaderTransactionID (PK), CustomerID (FK), TransactionDateHeader transaksi
TransactionDetailTransactionID (FK), ProductID (FK), quantity, subtotalDetail item transaksi
MsProductProductID (PK), ProductName, Price, CategoryIDMaster produk
MsCustomerCustomerID (PK), CustomerName, City, EmailMaster customer
MsCategoryCategoryID (PK), CategoryNameKategori produk
๐Ÿ”
1. Select Data
Basic โ†’ JOIN โ†’ Agregasi โ†’ Subquery โ†’ CASE WHEN
20 poin
SELECT mengambil data. Kombinasikan dengan JOIN, WHERE, GROUP BY, HAVING, fungsi string/agregat, subquery, dan CASE WHEN untuk soal kompleks.
CASE 1 SELECT dasar dengan fungsi string Easy
select-01-basic-string.sql
SELECT
  ProductID,
  UPPER(ProductName)               AS ProductName,
  LOWER(ProductName)               AS ProductNameLower,
  LENGTH(ProductName)              AS NameLength,
  REPLACE(ProductName,'Wild','W') AS ShortName,
  Price
FROM MsProduct;
CASE 2 SELECT + LIKE filter berbagai pola Easy
select-02-like.sql
-- Produk nama diawali 'Wild'
SELECT * FROM MsProduct WHERE ProductName LIKE 'Wild%';

-- Customer nama mengandung spasi (minimal 2 kata)
SELECT * FROM MsCustomer WHERE CustomerName LIKE '% %';

-- Email diakhiri '@gmail.com'
SELECT * FROM MsCustomer WHERE Email LIKE '%@gmail.com';

-- NOT LIKE: produk yang BUKAN kategori 'Wild'
SELECT * FROM MsProduct WHERE ProductName NOT LIKE '%Wild%';
CASE 3 SELECT + 4-table JOIN (pola khas Binus) Medium
select-03-4join.sql
SELECT
  REPLACE(td.TransactionID, 'TR', 'Wild-')  AS TransactionCode,
  p.ProductName,
  UPPER(c.CustomerName)                   AS CustomerName,
  td.quantity
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
WHERE
  p.ProductName   LIKE '%Wild%'
  AND c.CustomerName LIKE '% %'
  AND td.quantity   > 12;
CASE 4 SELECT + 5-table JOIN (dengan kategori) Medium
select-04-5join-category.sql
SELECT
  REPLACE(th.TransactionID, 'TR', 'INV-') AS InvoiceNo,
  UPPER(c.CustomerName)                  AS CustomerName,
  cat.CategoryName,
  p.ProductName,
  td.quantity,
  p.Price,
  (td.quantity * p.Price)               AS Total
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID  = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID      = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID    = c.CustomerID
JOIN  MsCategory          cat ON p.CategoryID     = cat.CategoryID
WHERE
  cat.CategoryName LIKE '%Organic%'
  AND c.City        LIKE '%Jakarta%';
CASE 5 SELECT + GROUP BY + COUNT/SUM/AVG Medium
select-05-group-aggregate.sql
-- Total transaksi per customer
SELECT
  UPPER(c.CustomerName)  AS CustomerName,
  c.City,
  COUNT(th.TransactionID) AS TotalTransaksi,
  SUM(td.quantity)        AS TotalQty,
  AVG(p.Price)            AS RataHarga
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName, c.City
ORDER BY TotalTransaksi DESC;
CASE 6 SELECT + GROUP BY + HAVING Medium
select-06-having.sql
-- Customer yang total transaksinya lebih dari 3x
SELECT
  UPPER(c.CustomerName)  AS CustomerName,
  COUNT(th.TransactionID) AS TotalTransaksi,
  SUM(td.quantity * p.Price) AS TotalBelanja
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName
HAVING COUNT(th.TransactionID) > 3
ORDER BY TotalBelanja DESC;
๐Ÿ’ก
WHERE vs HAVING: WHERE memfilter baris sebelum GROUP BY. HAVING memfilter grup setelah GROUP BY. Jadi HAVING dipakai untuk kondisi yang melibatkan fungsi agregat (COUNT, SUM, AVG, dll).
CASE 7 SELECT + CASE WHEN (kolom kondisional) Hard
select-07-case-when.sql
SELECT
  p.ProductName,
  p.Price,
  td.quantity,
  CASE
    WHEN td.quantity >= 20 THEN 'Large Order'
    WHEN td.quantity >= 10 THEN 'Medium Order'
    ELSE                        'Small Order'
  END                                         AS OrderCategory,
  CASE
    WHEN p.Price >= 100000 THEN 'Premium'
    WHEN p.Price >= 50000  THEN 'Standard'
    ELSE                         'Budget'
  END                                         AS PriceCategory
FROM  TransactionDetail  td
JOIN  MsProduct          p ON td.ProductID = p.ProductID
ORDER BY p.Price DESC;
CASE 8 SELECT + Subquery di WHERE Hard
select-08-subquery-where.sql
-- Produk yang pernah dibeli customer dari Jakarta
SELECT
  p.ProductID,
  UPPER(p.ProductName) AS ProductName,
  p.Price
FROM MsProduct p
WHERE p.ProductID IN (
  SELECT td.ProductID
  FROM  TransactionDetail  td
  JOIN  TransactionHeader   th ON td.TransactionID = th.TransactionID
  JOIN  MsCustomer          c  ON th.CustomerID   = c.CustomerID
  WHERE c.City LIKE '%Jakarta%'
);
CASE 9 SELECT + Subquery di SELECT (scalar) Hard
select-09-scalar-subquery.sql
SELECT
  p.ProductName,
  p.Price,
  (SELECT AVG(Price) FROM MsProduct) AS AvgPrice,
  p.Price - (SELECT AVG(Price) FROM MsProduct) AS SelisihDariAvg
FROM MsProduct p
ORDER BY p.Price DESC;
CASE 10 SELECT + CONCAT + kondisi tanggal Medium
select-10-concat-date.sql
SELECT
  CONCAT(c.CustomerName, ' - ', c.City)  AS CustomerInfo,
  CONCAT('Rp. ', FORMAT(p.Price,0))      AS HargaFormatted,
  th.TransactionDate,
  YEAR(th.TransactionDate)               AS Tahun,
  MONTH(th.TransactionDate)              AS Bulan
FROM  TransactionHeader  th
JOIN  TransactionDetail   td ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p  ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c  ON th.CustomerID   = c.CustomerID
WHERE YEAR(th.TransactionDate) = 2023;
CASE 11 SELECT + LEFT JOIN (tampilkan customer tanpa transaksi) Hard
select-11-left-join.sql
-- Customer yang BELUM pernah bertransaksi (LEFT JOIN + IS NULL)
SELECT
  c.CustomerID,
  UPPER(c.CustomerName) AS CustomerName,
  c.City,
  th.TransactionID       AS TransactionID  -- akan NULL
FROM      MsCustomer       c
LEFT JOIN TransactionHeader th ON c.CustomerID = th.CustomerID
WHERE th.TransactionID IS NULL;
CASE 12 SELECT + DISTINCT Easy
select-12-distinct.sql
-- Kota unik yang ada di customer
SELECT DISTINCT City FROM MsCustomer ORDER BY City ASC;

-- Produk unik yang pernah dibeli (tidak duplikat)
SELECT DISTINCT
  p.ProductID,
  UPPER(p.ProductName) AS ProductName
FROM  TransactionDetail  td
JOIN  MsProduct          p ON td.ProductID = p.ProductID
ORDER BY p.ProductName;
CASE 13 SELECT + MIN / MAX per grup Medium
select-13-min-max.sql
-- Harga tertinggi dan terendah per kategori
SELECT
  cat.CategoryName,
  MAX(p.Price)   AS HargaMax,
  MIN(p.Price)   AS HargaMin,
  AVG(p.Price)   AS HargaRata,
  COUNT(p.ProductID) AS JumlahProduk
FROM  MsProduct   p
JOIN  MsCategory  cat ON p.CategoryID = cat.CategoryID
GROUP BY cat.CategoryID, cat.CategoryName
ORDER BY HargaMax DESC;
CASE 14 SELECT + SUBSTRING / LEFT / RIGHT Medium
select-14-substring.sql
SELECT
  ProductID,
  ProductName,
  LEFT(ProductName, 5)         AS Prefix5,
  RIGHT(ProductName, 4)        AS Suffix4,
  SUBSTRING(ProductName,1,3)  AS Sub3,
  TRIM(ProductName)           AS Trimmed
FROM MsProduct;
CASE 15 SELECT kompleks: JOIN + GROUP BY + HAVING + CASE WHEN Hard
select-15-full-complex.sql
SELECT
  UPPER(c.CustomerName)         AS CustomerName,
  c.City,
  COUNT(DISTINCT th.TransactionID) AS TotalTransaksi,
  SUM(td.quantity * p.Price)     AS TotalBelanja,
  CASE
    WHEN SUM(td.quantity * p.Price) >= 5000000 THEN 'Gold'
    WHEN SUM(td.quantity * p.Price) >= 2000000 THEN 'Silver'
    ELSE                                              'Bronze'
  END                               AS CustomerTier
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName, c.City
HAVING   COUNT(DISTINCT th.TransactionID) > 2
ORDER BY TotalBelanja DESC;
๐Ÿ”—
2. Select Data with UNION
Gabungkan 2+ query โ€“ jumlah kolom harus identik
20 poin
UNION gabungkan hasil dua SELECT. Syarat: jumlah kolom dan tipe data harus sama. UNION hapus duplikat, UNION ALL pertahankan semua baris.
CASE 1 UNION dasar dari tabel sama, kondisi berbeda Easy
union-01-basic.sql
-- Customer dari Jakarta UNION customer dari Bandung
SELECT CustomerID, CustomerName, City
FROM   MsCustomer
WHERE  City = 'Jakarta'

UNION

SELECT CustomerID, CustomerName, City
FROM   MsCustomer
WHERE  City = 'Bandung'

ORDER BY City, CustomerName;
CASE 2 UNION persis seperti soal Binus (Wild + Organic) Medium
union-02-binus-style.sql
-- โ•โ• Produk 'Wild' qty > 12 โ•โ•
SELECT
  REPLACE(td.TransactionID, 'TR', 'Wild-')    AS TransactionCode,
  p.ProductName,
  UPPER(c.CustomerName)                       AS CustomerName,
  td.quantity
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
WHERE  p.ProductName   LIKE '%Wild%'
  AND  c.CustomerName LIKE '% %'
  AND  td.quantity   > 12

UNION

-- โ•โ• Produk 'Organic' qty < 12 โ•โ•
SELECT
  REPLACE(td.TransactionID, 'TR', 'Organic-') AS TransactionCode,
  p.ProductName,
  UPPER(c.CustomerName)                       AS CustomerName,
  td.quantity
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
WHERE  p.ProductName   LIKE '%Organic%'
  AND  c.CustomerName LIKE '% %'
  AND  td.quantity   < 12;
CASE 3 UNION 3 query sekaligus Hard
union-03-triple.sql
-- Gold: qty > 20
SELECT
  REPLACE(td.TransactionID,'TR','GOLD-')    AS TrxCode,
  p.ProductName, UPPER(c.CustomerName) AS Customer,
  td.quantity,   'Gold'                  AS Tier
FROM  TransactionHeader th
JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
JOIN  MsCustomer         c  ON th.CustomerID   = c.CustomerID
WHERE td.quantity > 20

UNION

-- Silver: qty 10-20
SELECT
  REPLACE(td.TransactionID,'TR','SILV-')  AS TrxCode,
  p.ProductName, UPPER(c.CustomerName) AS Customer,
  td.quantity,   'Silver'                AS Tier
FROM  TransactionHeader th
JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
JOIN  MsCustomer         c  ON th.CustomerID   = c.CustomerID
WHERE td.quantity BETWEEN 10 AND 20

UNION

-- Bronze: qty < 10
SELECT
  REPLACE(td.TransactionID,'TR','BRNZ-') AS TrxCode,
  p.ProductName, UPPER(c.CustomerName) AS Customer,
  td.quantity,   'Bronze'               AS Tier
FROM  TransactionHeader th
JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
JOIN  MsCustomer         c  ON th.CustomerID   = c.CustomerID
WHERE td.quantity < 10

ORDER BY Tier, quantity DESC;
CASE 4 UNION + ORDER BY di akhir + literal kolom Medium
union-04-literal-orderby.sql
-- Gabung produk mahal + produk murah, tambah label
SELECT
  ProductName,
  Price,
  'Mahal'    AS Kategori   -- literal string sebagai kolom
FROM  MsProduct
WHERE Price > 100000

UNION

SELECT
  ProductName,
  Price,
  'Murah'    AS Kategori
FROM  MsProduct
WHERE Price <= 50000

ORDER BY Kategori, Price DESC;
CASE 5 UNION ALL vs UNION (perbedaan duplikat) Easy
union-05-union-all.sql
-- UNION: hapus duplikat otomatis
SELECT City FROM MsCustomer
UNION
SELECT City FROM MsCustomer;

-- UNION ALL: simpan semua termasuk duplikat
SELECT City FROM MsCustomer
UNION ALL
SELECT City FROM MsCustomer;
โš ๏ธ
Aturan UNION: (1) Jumlah kolom harus SAMA. (2) Tipe data harus KOMPATIBEL. (3) Nama kolom hasil diambil dari query PERTAMA. (4) ORDER BY hanya di bagian PALING AKHIR.
โ†•๏ธ
3. Select Data with ORDER BY
ASC/DESC, multi-kolom, CASE WHEN dalam ORDER, LIMIT
10 poin
ORDER BY mengurutkan hasil. Default = ASC. Bisa kombinasi beberapa kolom, pakai alias, atau ekspresi CASE WHEN.
CASE 1 ORDER BY single column ASC/DESC Easy
orderby-01.sql
SELECT ProductName, Price FROM MsProduct ORDER BY Price ASC;
SELECT ProductName, Price FROM MsProduct ORDER BY Price DESC;
SELECT CustomerName, City FROM MsCustomer ORDER BY CustomerName;
CASE 2 ORDER BY multi-kolom Easy
orderby-02-multi.sql
-- Urut kota A-Z, lalu per kota nama customer Z-A
SELECT CustomerName, City
FROM   MsCustomer
ORDER BY City ASC, CustomerName DESC;
CASE 3 ORDER BY + JOIN + alias kolom Medium
orderby-03-join-alias.sql
SELECT
  UPPER(c.CustomerName) AS CustomerName,
  p.ProductName,
  td.quantity,
  (td.quantity * p.Price) AS Subtotal
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
ORDER BY Subtotal DESC, p.ProductName ASC;
CASE 4 ORDER BY + LIMIT (Top N) Easy
orderby-04-limit.sql
-- Top 5 produk termahal
SELECT ProductName, Price
FROM   MsProduct
ORDER BY Price DESC
LIMIT 5;

-- Halaman ke-2 (skip 5, ambil 5 berikutnya)
SELECT ProductName, Price
FROM   MsProduct
ORDER BY Price DESC
LIMIT 5 OFFSET 5;
CASE 5 ORDER BY + GROUP BY + agregat Medium
orderby-05-group-order.sql
-- Produk diurutkan dari yang paling sering dibeli
SELECT
  UPPER(p.ProductName) AS ProductName,
  SUM(td.quantity)     AS TotalTerjual,
  COUNT(td.TransactionID) AS JumlahOrder
FROM  TransactionDetail  td
JOIN  MsProduct          p ON td.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductName
ORDER BY TotalTerjual DESC;
CASE 6 ORDER BY dengan CASE WHEN (custom sort) Hard
orderby-06-case-sort.sql
-- Urutkan: Jakarta dulu, Bandung, lalu kota lain
SELECT CustomerName, City
FROM   MsCustomer
ORDER BY
  CASE
    WHEN City = 'Jakarta' THEN 1
    WHEN City = 'Bandung' THEN 2
    ELSE                       3
  END,
  CustomerName ASC;
๐Ÿ”ง
4. Alter Table
ADD ยท MODIFY ยท CHANGE ยท DROP ยท RENAME ยท CONSTRAINT
10 poin
ALTER TABLE memodifikasi STRUKTUR tabel yang sudah ada, bukan datanya.
CASE 1 ADD kolom baru (berbagai posisi) Easy
alter-01-add.sql
-- Tambah di akhir tabel
ALTER TABLE MsProduct
ADD Stock INT DEFAULT 0;

-- Tambah di posisi pertama
ALTER TABLE MsProduct
ADD CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP FIRST;

-- Tambah setelah kolom tertentu
ALTER TABLE MsProduct
ADD Discount DECIMAL(5,2) DEFAULT 0 AFTER Price;
CASE 2 ADD banyak kolom sekaligus Medium
alter-02-add-multi.sql
ALTER TABLE MsCustomer
ADD PhoneNumber VARCHAR(15),
ADD Email       VARCHAR(100),
ADD JoinDate    DATE DEFAULT (CURDATE());
CASE 3 MODIFY COLUMN (ubah tipe / constraint) Easy
alter-03-modify.sql
-- Ubah tipe VARCHAR lebih panjang
ALTER TABLE MsProduct
MODIFY COLUMN ProductName VARCHAR(255) NOT NULL;

-- Ubah INT ke BIGINT
ALTER TABLE MsProduct
MODIFY COLUMN Stock BIGINT DEFAULT 0;

-- Ubah ke NOT NULL
ALTER TABLE MsCustomer
MODIFY COLUMN City VARCHAR(100) NOT NULL;
CASE 4 CHANGE (rename + ubah tipe) Medium
alter-04-change.sql
-- CHANGE: ganti nama DAN tipe sekaligus
ALTER TABLE MsProduct
CHANGE Stock StockBarang INT NOT NULL DEFAULT 0;

-- RENAME COLUMN (MySQL 8.0+, hanya ganti nama)
ALTER TABLE MsProduct
RENAME COLUMN Discount TO DiscountPct;
CASE 5 DROP COLUMN Easy
alter-05-drop-col.sql
ALTER TABLE MsProduct
DROP COLUMN Discount;

-- Hapus beberapa kolom sekaligus
ALTER TABLE MsProduct
DROP COLUMN Stock,
DROP COLUMN CreatedAt;
CASE 6 ADD / DROP PRIMARY KEY & FOREIGN KEY Hard
alter-06-constraints.sql
-- Tambah PRIMARY KEY
ALTER TABLE MsProduct
ADD PRIMARY KEY (ProductID);

-- Tambah FOREIGN KEY
ALTER TABLE TransactionDetail
ADD CONSTRAINT fk_td_product
  FOREIGN KEY (ProductID) REFERENCES MsProduct(ProductID)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

-- Hapus FOREIGN KEY
ALTER TABLE TransactionDetail
DROP FOREIGN KEY fk_td_product;

-- Hapus PRIMARY KEY
ALTER TABLE MsProduct
DROP PRIMARY KEY;
CASE 7 ADD INDEX + UNIQUE Medium
alter-07-index.sql
-- Tambah INDEX biasa (percepat pencarian)
ALTER TABLE MsProduct
ADD INDEX idx_productname (ProductName);

-- Tambah UNIQUE constraint
ALTER TABLE MsCustomer
ADD UNIQUE (Email);

-- Hapus INDEX
ALTER TABLE MsProduct
DROP INDEX idx_productname;
CASE 8 RENAME TABLE Easy
alter-08-rename-table.sql
-- Cara 1: ALTER TABLE ... RENAME TO
ALTER TABLE MsCustomer RENAME TO MasterCustomer;

-- Cara 2: RENAME TABLE (bisa ganti banyak sekaligus)
RENAME TABLE
  MsProduct  TO MasterProduct,
  MsCustomer TO MasterCustomer;
๐Ÿ‘๏ธ
5. Create View
Virtual table dari SELECT โ€“ bisa berisi JOIN, UNION, GROUP BY, CASE WHEN
20 poin
VIEW adalah query yang disimpan dengan nama. Tidak menyimpan data fisik โ€“ selalu ambil data terkini. Bisa dipakai seperti tabel biasa.
CASE 1 VIEW dasar Easy
view-01-basic.sql
CREATE VIEW v_ProductList AS
SELECT
  ProductID,
  UPPER(ProductName) AS ProductName,
  Price
FROM  MsProduct
WHERE Price > 50000;

-- Pakai view seperti tabel
SELECT * FROM v_ProductList;
CASE 2 VIEW dengan JOIN (pola Binus) Medium
view-02-join.sql
CREATE VIEW v_WildTransaction AS
SELECT
  REPLACE(td.TransactionID, 'TR', 'Wild-')  AS TransactionCode,
  p.ProductName,
  UPPER(c.CustomerName)                     AS CustomerName,
  td.quantity
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
WHERE p.ProductName LIKE '%Wild%'
  AND td.quantity   > 12;
CASE 3 VIEW dengan UNION (paling sering keluar!) Hard
view-03-union.sql
CREATE VIEW v_AllGroupedTransaction AS
  SELECT
    REPLACE(td.TransactionID,'TR','Wild-')     AS TransactionCode,
    p.ProductName,
    UPPER(c.CustomerName)                      AS CustomerName,
    td.quantity
  FROM  TransactionHeader th
  JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
  JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
  JOIN  MsCustomer         c  ON th.CustomerID   = c.CustomerID
  WHERE p.ProductName LIKE '%Wild%' AND td.quantity > 12

UNION

  SELECT
    REPLACE(td.TransactionID,'TR','Organic-')  AS TransactionCode,
    p.ProductName,
    UPPER(c.CustomerName)                      AS CustomerName,
    td.quantity
  FROM  TransactionHeader th
  JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
  JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
  JOIN  MsCustomer         c  ON th.CustomerID   = c.CustomerID
  WHERE p.ProductName LIKE '%Organic%' AND td.quantity < 12;
CASE 4 VIEW dengan GROUP BY + agregat Hard
view-04-group.sql
CREATE VIEW v_CustomerSummary AS
SELECT
  UPPER(c.CustomerName)             AS CustomerName,
  c.City,
  COUNT(DISTINCT th.TransactionID)   AS TotalTransaksi,
  SUM(td.quantity)                   AS TotalQty,
  SUM(td.quantity * p.Price)        AS TotalBelanja
FROM  TransactionHeader  th
JOIN  TransactionDetail   td ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p  ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c  ON th.CustomerID   = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName, c.City;

-- Pakai view dan filter dari luar
SELECT * FROM v_CustomerSummary
WHERE  TotalBelanja > 1000000
ORDER BY TotalBelanja DESC;
CASE 5 VIEW dengan CASE WHEN Hard
view-05-case.sql
CREATE VIEW v_TransactionWithTier AS
SELECT
  th.TransactionID,
  UPPER(c.CustomerName)  AS CustomerName,
  p.ProductName,
  td.quantity,
  p.Price,
  (td.quantity * p.Price)  AS Subtotal,
  CASE
    WHEN (td.quantity * p.Price) >= 1000000 THEN 'Premium'
    WHEN (td.quantity * p.Price) >= 500000  THEN 'Standard'
    ELSE                                       'Budget'
  END                       AS TransactionTier
FROM  TransactionHeader  th
JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID;
CASE 6 CREATE OR REPLACE VIEW + DROP VIEW Easy
view-06-replace-drop.sql
-- Update view yang sudah ada (tidak error jika belum ada)
CREATE OR REPLACE VIEW v_ProductList AS
SELECT ProductID, UPPER(ProductName) AS ProductName, Price
FROM   MsProduct
WHERE  Price > 0;

-- Hapus view
DROP VIEW IF EXISTS v_WildTransaction;
DROP VIEW IF EXISTS v_ProductList, v_CustomerSummary;
โœ๏ธ
6. Update Data
SET + WHERE โ€“ satu kolom, banyak kolom, ekspresi, subquery
10 poin
UPDATE mengubah nilai data. WAJIB pakai WHERE! Tanpa WHERE = semua baris berubah.
CASE 1 UPDATE satu kolom berdasarkan ID Easy
update-01-single.sql
UPDATE MsProduct
SET    Price = 85000
WHERE  ProductID = 'P001';
CASE 2 UPDATE banyak kolom sekaligus Easy
update-02-multi-col.sql
UPDATE MsCustomer
SET    CustomerName = 'Budi Santoso',
       City         = 'Surabaya',
       Email        = 'budi@email.com'
WHERE  CustomerID   = 'C001';
CASE 3 UPDATE dengan ekspresi matematika Easy
update-03-expression.sql
-- Naikkan harga semua produk 'Wild' sebesar 10%
UPDATE MsProduct
SET    Price = Price * 1.10
WHERE  ProductName LIKE '%Wild%';

-- Kurangi qty sebesar 5 jika qty > 10
UPDATE TransactionDetail
SET    quantity = quantity - 5
WHERE  quantity > 10;
CASE 4 UPDATE dengan CASE WHEN Hard
update-04-case.sql
-- Set discount berbeda berdasarkan harga produk
UPDATE MsProduct
SET    Discount =
  CASE
    WHEN Price >= 200000 THEN 20
    WHEN Price >= 100000 THEN 15
    WHEN Price >= 50000  THEN 10
    ELSE                       5
  END;
CASE 5 UPDATE dengan subquery IN Hard
update-05-subquery.sql
-- Naikkan harga produk yang pernah dibeli customer Jakarta
UPDATE MsProduct
SET    Price = Price * 1.05
WHERE  ProductID IN (
  SELECT DISTINCT td.ProductID
  FROM  TransactionDetail  td
  JOIN  TransactionHeader   th ON td.TransactionID = th.TransactionID
  JOIN  MsCustomer          c  ON th.CustomerID   = c.CustomerID
  WHERE c.City = 'Jakarta'
);
CASE 6 UPDATE dengan kondisi BETWEEN Easy
update-06-between.sql
-- Set qty = 10 untuk semua detail dengan qty antara 1-5
UPDATE TransactionDetail
SET    quantity = 10
WHERE  quantity BETWEEN 1 AND 5;
โš ๏ธ
BAHAYA! UPDATE MsProduct SET Price = 0; tanpa WHERE โ†’ SEMUA harga jadi 0. Selalu verify WHERE-mu sebelum eksekusi!
๐Ÿ—‘๏ธ
7. Delete Data
Hapus baris โ€“ WHERE wajib โ€“ TRUNCATE vs DROP
10 poin
DELETE FROM menghapus satu atau lebih baris. Tanpa WHERE = hapus semua baris (berbahaya!)
CASE 1 DELETE berdasarkan ID Easy
delete-01-id.sql
DELETE FROM MsProduct
WHERE ProductID = 'P001';
CASE 2 DELETE dengan LIKE Easy
delete-02-like.sql
-- Hapus semua produk yang namanya mengandung 'Expired'
DELETE FROM MsProduct
WHERE ProductName LIKE '%Expired%';
CASE 3 DELETE dengan kondisi angka dan BETWEEN Easy
delete-03-numeric.sql
-- Hapus detail transaksi dengan qty = 0
DELETE FROM TransactionDetail
WHERE quantity = 0;

-- Hapus produk dengan harga sangat murah
DELETE FROM MsProduct
WHERE Price BETWEEN 0 AND 999;
CASE 4 DELETE dengan subquery IN Hard
delete-04-subquery.sql
-- Hapus detail transaksi untuk produk kategori 'Wild'
DELETE FROM TransactionDetail
WHERE ProductID IN (
  SELECT ProductID FROM MsProduct
  WHERE  ProductName LIKE '%Wild%'
);

-- Hapus customer yang tidak punya transaksi
DELETE FROM MsCustomer
WHERE CustomerID NOT IN (
  SELECT DISTINCT CustomerID FROM TransactionHeader
);
CASE 5 DELETE dengan kondisi AND / OR Medium
delete-05-and-or.sql
-- Hapus produk: kategori Wild DAN harga kurang dari 50000
DELETE FROM MsProduct
WHERE  ProductName LIKE '%Wild%'
  AND  Price < 50000;

-- Hapus customer dari Jakarta ATAU Bandung
DELETE FROM MsCustomer
WHERE  City = 'Jakarta'
  OR   City = 'Bandung';
CASE 6 DELETE semua + TRUNCATE + DROP perbedaan Medium
delete-06-truncate-drop.sql
-- DELETE tanpa WHERE (hapus semua baris, bisa rollback)
DELETE FROM MsProduct;

-- TRUNCATE (lebih cepat, reset auto-increment, TIDAK bisa rollback)
TRUNCATE TABLE MsProduct;

-- DROP TABLE (hapus tabel + strukturnya)
DROP TABLE IF EXISTS MsProduct;
PerintahHapus BarisHapus StrukturBisa RollbackReset Auto-Inc
DELETEโœ… (dengan WHERE)โŒโœ…โŒ
TRUNCATEโœ… (semua)โŒโŒโœ…
DROP TABLEโœ… (semua)โœ…โŒโœ…
๐Ÿš€
8. Pola Soal Advanced (Kemungkinan Keluar)
Kombinasi teknik yang sering muncul di quiz Binus level sulit
Bonus Tips
ADV 1 CREATE VIEW dari UNION + panggil dengan ORDER BY Hard
adv-01-view-union-call.sql
-- Buat view berisi UNION
CREATE VIEW v_ProductTier AS
  SELECT ProductID, ProductName, Price, 'Premium' AS Tier
  FROM  MsProduct WHERE Price >= 200000
UNION
  SELECT ProductID, ProductName, Price, 'Standard' AS Tier
  FROM  MsProduct WHERE Price BETWEEN 50000 AND 199999
UNION
  SELECT ProductID, ProductName, Price, 'Budget' AS Tier
  FROM  MsProduct WHERE Price < 50000;

-- Query dari view
SELECT * FROM v_ProductTier
WHERE  Tier = 'Premium'
ORDER BY Price DESC;
ADV 2 UPDATE dengan JOIN (MySQL-specific) Hard
adv-02-update-join.sql
-- Update subtotal di TransactionDetail berdasarkan harga produk
UPDATE TransactionDetail  td
JOIN   MsProduct          p ON td.ProductID = p.ProductID
SET    td.subtotal = td.quantity * p.Price
WHERE  p.ProductName LIKE '%Wild%';
ADV 3 SELECT dengan HAVING + LIKE di agregat Hard
adv-03-having-complex.sql
-- Produk yang total qty-nya lebih dari rata-rata semua produk
SELECT
  UPPER(p.ProductName) AS ProductName,
  SUM(td.quantity)     AS TotalQty
FROM  TransactionDetail  td
JOIN  MsProduct          p ON td.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductName
HAVING   SUM(td.quantity) > (
  SELECT AVG(TotalPerProduct)
  FROM (
    SELECT SUM(quantity) AS TotalPerProduct
    FROM   TransactionDetail
    GROUP BY ProductID
  ) sub
)
ORDER BY TotalQty DESC;
ADV 4 Pola REPLACE + UPPER + JOIN + UNION + ORDER (combo lengkap) Hard
adv-04-full-combo.sql
-- โ•โ•โ•โ• SOAL TIPE PALING SULIT โ•โ•โ•โ•
-- Gabungkan 2 kondisi produk berbeda
-- Dengan label, fungsi string, dan ORDER BY akhir

CREATE VIEW v_ComplexReport AS

  SELECT
    REPLACE(th.TransactionID,'TR','W')           AS TrxCode,
    UPPER(LEFT(c.CustomerName,10))               AS Customer,
    p.ProductName,
    td.quantity,
    CASE
      WHEN td.quantity > 15 THEN 'HIGH'
      ELSE 'NORMAL'
    END                                             AS QtyLabel
  FROM  TransactionHeader  th
  JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
  JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
  JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
  WHERE  p.ProductName   LIKE '%Wild%'
    AND  c.CustomerName LIKE '% %'
    AND  td.quantity   > 12

UNION

  SELECT
    REPLACE(th.TransactionID,'TR','O')           AS TrxCode,
    UPPER(LEFT(c.CustomerName,10))               AS Customer,
    p.ProductName,
    td.quantity,
    CASE
      WHEN td.quantity > 15 THEN 'HIGH'
      ELSE 'NORMAL'
    END                                             AS QtyLabel
  FROM  TransactionHeader  th
  JOIN  TransactionDetail   td  ON th.TransactionID = td.TransactionID
  JOIN  MsProduct           p   ON td.ProductID     = p.ProductID
  JOIN  MsCustomer          c   ON th.CustomerID   = c.CustomerID
  WHERE  p.ProductName   LIKE '%Organic%'
    AND  c.CustomerName LIKE '% %'
    AND  td.quantity   < 12;

-- Pakai view + filter + sort
SELECT * FROM v_ComplexReport
ORDER BY quantity DESC;

๐Ÿ“Œ Cheat Sheet โ€“ Urutan Penulisan Query SQL
urutan-klausa.sql
-- URUTAN WAJIB (jangan sampai kebalik!)
SELECT   kolom / fungsi / ekspresi       -- 1. Kolom yang ditampilkan
FROM     tabel_utama                     -- 2. Tabel sumber
JOIN     tabel_lain ON kondisi          -- 3. Join tabel lain
WHERE    kondisi_filter_baris            -- 4. Filter sebelum group
GROUP BY kolom_pengelompokan            -- 5. Kelompokkan
HAVING   kondisi_agregat               -- 6. Filter setelah group
ORDER BY kolom_urutan ASC/DESC         -- 7. Urutkan hasil
LIMIT    n;                             -- 8. Batasi jumlah baris
๐Ÿ“„
Materi Tambahan dari DB Quiz 2 (PDF Notes)
SUBSTRING ยท YEAR ยท MONTH ยท DATE ยท POSITION ยท REVERSE ยท ALTER VIEW ยท INDEX ยท TEMP TABLE ยท INTERSECT ยท EXCEPT
Dari PDF
๐Ÿ“Œ A. Fungsi String Lengkap (dari catatan PDF)
STR 1 UPPER ยท LOWER ยท REVERSE Easy
string-upper-lower-reverse.sql
-- UPPER: semua huruf jadi kapital
SELECT UPPER(CustomerName) AS NamaKapital
FROM MsCustomer;

-- LOWER: semua huruf jadi kecil
SELECT LOWER(ProductName) AS NamaKecil
FROM MsProduct;

-- REVERSE: balik urutan huruf
SELECT
  ProductName,
  REVERSE(ProductName) AS ReversedName
FROM MsProduct;
-- Contoh: 'Wild Berry' โ†’ 'yrreB dliW'
STR 2 LEFT ยท RIGHT ยท SUBSTRING Easy
string-left-right-substring.sql
-- LEFT(col, n) โ†’ n karakter dari KIRI
SELECT
  ProductName,
  LEFT(ProductName, 4)  AS Prefix   -- 'Wild Berry' โ†’ 'Wild'
FROM MsProduct;

-- RIGHT(col, n) โ†’ n karakter dari KANAN
SELECT
  ProductName,
  RIGHT(ProductName, 5) AS Suffix   -- 'Wild Berry' โ†’ 'Berry'
FROM MsProduct;

-- SUBSTRING(col, start, length) โ†’ potong dari posisi tertentu
SELECT
  TransactionID,
  SUBSTRING(TransactionID, 3, 3) AS IDNumber
  -- 'TR001' โ†’ mulai posisi 3, ambil 3 char โ†’ '001'
FROM TransactionHeader;

-- SUBSTRING tanpa length โ†’ sampai akhir string
SELECT SUBSTRING(ProductName, 6) AS AfterPos5
FROM MsProduct;
-- 'Wild Berry' mulai pos 6 โ†’ 'Berry'
STR 3 REPLACE ยท CONCAT ยท POSITION Medium
string-replace-concat-position.sql
-- REPLACE(col, 'old', 'new') โ†’ ganti substring
SELECT
  TransactionID,
  REPLACE(TransactionID, 'TR', 'Transaction ') AS FullTransaction
FROM TransactionHeader;
-- 'TR001' โ†’ 'Transaction 001'

-- CONCAT(a, b, c, ...) โ†’ gabungkan string
SELECT
  CONCAT(CustomerName, ' - ', City)    AS Info,
  CONCAT('Rp. ', Price)                AS Harga
FROM MsCustomer, MsProduct;

-- POSITION('char' IN col) โ†’ posisi karakter pertama
SELECT
  ProductName,
  POSITION('e' IN ProductName) AS PosHurufE
-- 'Berry' โ†’ 2 (karena 'e' ada di posisi ke-2)
FROM MsProduct;
๐Ÿ“Œ B. Fungsi Tanggal: YEAR ยท MONTH ยท DAY ยท DATE
DATE 1 YEAR ยท MONTH ยท DAY dari kolom tanggal Easy
date-year-month-day.sql
-- Ambil komponen tanggal dari TransactionDate
SELECT
  TransactionID,
  TransactionDate,
  YEAR(TransactionDate)    AS Tahun,
  MONTH(TransactionDate)   AS Bulan,
  DAY(TransactionDate)     AS Tanggal
FROM TransactionHeader;

-- Filter berdasarkan tahun
SELECT * FROM TransactionHeader
WHERE YEAR(TransactionDate) = 2023;

-- Filter berdasarkan bulan
SELECT * FROM TransactionHeader
WHERE MONTH(TransactionDate) = 12;    -- Bulan Desember

-- Filter kombinasi YEAR + MONTH
SELECT * FROM TransactionHeader
WHERE YEAR(TransactionDate)  = 2023
  AND MONTH(TransactionDate) = 6;     -- Juni 2023
DATE 2 DATE gabungan dengan JOIN Medium
date-join-complex.sql
-- Laporan per bulan: total transaksi tiap bulan
SELECT
  YEAR(th.TransactionDate)    AS Tahun,
  MONTH(th.TransactionDate)   AS Bulan,
  COUNT(th.TransactionID)     AS JumlahTransaksi,
  SUM(td.quantity * p.Price) AS TotalPendapatan
FROM  TransactionHeader th
JOIN  TransactionDetail  td ON th.TransactionID = td.TransactionID
JOIN  MsProduct          p  ON td.ProductID     = p.ProductID
GROUP BY
  YEAR(th.TransactionDate),
  MONTH(th.TransactionDate)
ORDER BY Tahun, Bulan;

-- Fungsi tanggal lainnya
SELECT
  NOW()                                AS SekarangLengkap,
  CURDATE()                            AS TanggalHariIni,
  CURTIME()                            AS WaktuSekarang,
  DATEDIFF(NOW(), '2023-01-01')      AS HariSejak2023,
  DATE_FORMAT(NOW(), '%d/%m/%Y')    AS FormatIndonesia;
๐Ÿ“Œ C. LIKE โ€“ Semua Pola Penting
LIKE 1 Semua variasi LIKE pattern Easy
like-patterns.sql
-- % = wildcard (0 atau lebih karakter apapun)
-- _ = wildcard (tepat 1 karakter apapun)

-- Mengandung kata 'Wild'
SELECT * FROM MsProduct WHERE ProductName LIKE '%Wild%';

-- Diawali 'Wild'
SELECT * FROM MsProduct WHERE ProductName LIKE 'Wild%';

-- Diakhiri 'Berry'
SELECT * FROM MsProduct WHERE ProductName LIKE '%Berry';

-- Nama punya spasi (minimal 2 kata)
SELECT * FROM MsCustomer WHERE CustomerName LIKE '% %';

-- Tepat 5 karakter (5 underscore)
SELECT * FROM MsProduct WHERE ProductID LIKE '_____';

-- Diawali 'P' lalu tepat 3 karakter
SELECT * FROM MsProduct WHERE ProductID LIKE 'P___';

-- NOT LIKE: tidak mengandung 'Expired'
SELECT * FROM MsProduct WHERE ProductName NOT LIKE '%Expired%';

-- Email dari Gmail
SELECT * FROM MsCustomer WHERE Email LIKE '%@gmail.com';
๐Ÿ“Œ D. ORDER BY โ€“ ASC dan DESC (dari PDF)
orderby-pdf-notes.sql
-- ASC = Ascending = Aโ†’Z / 0โ†’9 (DEFAULT jika tidak ditulis)
SELECT ProductName, Price
FROM   MsProduct
ORDER BY Price ASC;      -- harga dari terkecil ke terbesar

-- DESC = Descending = Zโ†’A / 9โ†’0
SELECT ProductName, Price
FROM   MsProduct
ORDER BY Price DESC;     -- harga dari terbesar ke terkecil

-- ORDER BY di UNION: harus di akhir query terakhir
SELECT ProductName, Price FROM MsProduct WHERE Price > 100000
UNION
SELECT ProductName, Price FROM MsProduct WHERE Price <= 100000
ORDER BY Price DESC;    -- โ† HANYA di sini, bukan di tengah
๐Ÿ“Œ E. INTERSECT & EXCEPT (dari PDF โ€“ Materi Quiz)
INTERSECT = seperti INNER JOIN tapi cek seluruh baris โ€“ hasilnya adalah baris yang ada di kedua query.
EXCEPT = kebalikan INTERSECT โ€“ hasilnya baris yang ada di query pertama tapi TIDAK ada di query kedua.
intersect-except.sql
-- โ•โ• INTERSECT: hanya baris yang ADA DI KEDUANYA โ•โ•
SELECT CustomerID FROM MsCustomer
WHERE  City = 'Jakarta'

INTERSECT

SELECT CustomerID FROM TransactionHeader;
-- โ†’ CustomerID dari Jakarta yang PERNAH transaksi

-- โ•โ• EXCEPT: ada di query pertama tapi TIDAK di kedua โ•โ•
-- Contoh dari PDF:
-- Table A id: 1,2,3 | Table B id: 2,3,4

-- A EXCEPT B โ†’ hasil: 1 (ada di A tapi tidak di B)
SELECT * FROM table_A
EXCEPT
SELECT * FROM table_B;

-- B EXCEPT A โ†’ hasil: 4 (ada di B tapi tidak di A)
SELECT * FROM table_B
EXCEPT
SELECT * FROM table_A;

-- โš ๏ธ MySQL tidak support INTERSECT/EXCEPT langsung
-- Gunakan alternatif ini di MySQL:

-- INTERSECT pakai INNER JOIN:
SELECT DISTINCT a.CustomerID
FROM      MsCustomer      a
INNER JOIN TransactionHeader b ON a.CustomerID = b.CustomerID
WHERE a.City = 'Jakarta';

-- EXCEPT pakai NOT IN / LEFT JOIN + IS NULL:
SELECT CustomerID FROM MsCustomer
WHERE  CustomerID NOT IN (
  SELECT DISTINCT CustomerID FROM TransactionHeader
);
โš ๏ธ
Perhatian MySQL! MySQL versi lama tidak mendukung INTERSECT dan EXCEPT secara langsung. Di MySQL 8.0+ sudah didukung. Kalau soal quiz pakai MariaDB/MySQL lama, gunakan INNER JOIN sebagai pengganti INTERSECT dan NOT IN / LEFT JOIN IS NULL sebagai pengganti EXCEPT.
๐Ÿ“Œ F. ALTER VIEW (dari PDF)
alter-view.sql
-- CREATE VIEW (buat baru)
CREATE VIEW v_WildProduct AS
SELECT ProductID, ProductName, Price
FROM   MsProduct
WHERE  ProductName LIKE '%Wild%';

-- ALTER VIEW (ubah definisi view yang sudah ada)
ALTER VIEW v_WildProduct AS
SELECT
  ProductID,
  UPPER(ProductName) AS ProductName,
  Price,
  CategoryID          -- kolom baru ditambah
FROM   MsProduct
WHERE  ProductName LIKE '%Wild%';

-- CREATE OR REPLACE VIEW (cara lain ubah view)
CREATE OR REPLACE VIEW v_WildProduct AS
SELECT ProductID, UPPER(ProductName) AS ProductName, Price
FROM   MsProduct
WHERE  ProductName LIKE '%Wild%';

-- DROP VIEW (hapus view)
DROP VIEW v_WildProduct;
DROP VIEW IF EXISTS v_WildProduct;
๐Ÿ“Œ G. CREATE INDEX & DROP INDEX (dari PDF)
INDEX membuat "daftar isi" untuk kolom sehingga pencarian lebih cepat. Tidak mengubah data, hanya mempercepat query.
index.sql
-- Sintaks PDF: CREATE INDEX nama ON tabel(kolom)
CREATE INDEX idx_productname
  ON MsProduct(ProductName);

-- Index multi-kolom
CREATE INDEX idx_customer_city
  ON MsCustomer(CustomerName, City);

-- UNIQUE Index
CREATE UNIQUE INDEX idx_email_unique
  ON MsCustomer(Email);

-- Sintaks PDF: DROP INDEX nama ON tabel
DROP INDEX idx_productname ON MsProduct;
๐Ÿ“Œ H. TEMPORARY TABLE (dari PDF)
TEMPORARY TABLE = tabel sementara yang hanya ada selama sesi koneksi berlangsung. Tidak muncul di daftar tabel permanen. Bisa di-SELECT, INSERT, UPDATE, DELETE seperti tabel biasa.
temporary-table.sql
-- Sintaks dari PDF
CREATE TEMPORARY TABLE temp_TopProduct (
  ProductID   CHAR(5)       NOT NULL,
  ProductName VARCHAR(100)  NOT NULL,
  TotalSold   INT           DEFAULT 0
);

-- Isi dari query
INSERT INTO temp_TopProduct
SELECT
  p.ProductID,
  p.ProductName,
  SUM(td.quantity) AS TotalSold
FROM  TransactionDetail td
JOIN  MsProduct         p ON td.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductName;

-- Pakai seperti tabel biasa
SELECT * FROM temp_TopProduct
WHERE  TotalSold > 50
ORDER BY TotalSold DESC;

-- Contoh dari PDF (tabel tutor dengan constraint)
CREATE TEMPORARY TABLE tutor (
  ID           CHAR(4)      CHECK(ID REGEXP('^ID[0-9][0-9]$')),
  NAMA_DEPAN   VARCHAR(20) NOT NULL,
  NAMA_BELAKANG VARCHAR(20) NOT NULL,
  CONSTRAINT fk_tutor
    FOREIGN KEY(ID) REFERENCES MsStaff(StaffID)
);
๐Ÿ“Œ I. UPDATE & DELETE โ€“ Ringkasan dari Catatan
update-delete-summary.sql
โ”โ”โ” UPDATE โ”โ”โ”
UPDATE MsProduct
SET    Price = Price * 1.1        -- naikkan 10%
WHERE  ProductName LIKE '%Wild%';

-- Update + YEAR filter
UPDATE TransactionHeader
SET    TransactionDate = CURDATE()
WHERE  YEAR(TransactionDate) < 2020;

โ”โ”โ” DELETE โ”โ”โ”
DELETE FROM MsProduct
WHERE  ProductName LIKE '%Expired%';

-- Delete berdasarkan YEAR
DELETE FROM TransactionHeader
WHERE  YEAR(TransactionDate) < 2020;

-- Delete dengan subquery
DELETE FROM TransactionDetail
WHERE  ProductID NOT IN (
  SELECT ProductID FROM MsProduct
);
๐Ÿ“Œ J. Tabel Rangkuman Semua Fungsi String & Date
FungsiKegunaanContohHasil
UPPER(col)Semua huruf kapitalUPPER('wild berry')'WILD BERRY'
LOWER(col)Semua huruf kecilLOWER('WILD')'wild'
REVERSE(col)Balik urutan hurufREVERSE('ABC')'CBA'
LENGTH(col)Panjang stringLENGTH('Wild')4
LEFT(col, n)n karakter dari kiriLEFT('ABCDEF', 3)'ABC'
RIGHT(col, n)n karakter dari kananRIGHT('ABCDEF', 3)'DEF'
SUBSTRING(col, s, n)Potong dari posisi s sepanjang nSUBSTRING('TR001', 3, 3)'001'
REPLACE(col, a, b)Ganti string a โ†’ bREPLACE('TR001','TR','INV-')'INV-001'
CONCAT(a, b, ...)Gabungkan stringCONCAT('Hello', ' ', 'World')'Hello World'
TRIM(col)Hapus spasi awal/akhirTRIM(' hi ')'hi'
POSITION(c IN col)Posisi karakter c pertamaPOSITION('e' IN 'Berry')2
YEAR(date)Ambil tahunYEAR('2023-06-15')2023
MONTH(date)Ambil bulan (1-12)MONTH('2023-06-15')6
DAY(date)Ambil hari (1-31)DAY('2023-06-15')15
NOW()Tanggal + waktu sekarangNOW()'2026-05-25 22:10:00'
CURDATE()Tanggal hari iniCURDATE()'2026-05-25'
DATEDIFF(a, b)Selisih hari antara a dan bDATEDIFF('2026-01-01','2023-01-01')1096
DATE_FORMAT(d, fmt)Format tanggal customDATE_FORMAT(NOW(),'%d/%m/%Y')'25/05/2026'
๐Ÿ“Œ K. Urutan Klausa SELECT (General Command Sequence dari PDF)
general-select-sequence.sql
-- URUTAN WAJIB (dari PDF DB Quiz 2, Sesi 5)
SELECT   column_name(s)          -- 1. Kolom apa saja yang ditampilkan
FROM     table_name              -- 2. Dari tabel mana
JOIN     another_table           -- 3. Gabung tabel lain
  ON     kondisi_join
WHERE    condition               -- 4. Filter baris
GROUP BY column_name(s)         -- 5. Kelompokkan
HAVING   kondisi_agregat        -- 6. Filter setelah group
ORDER BY column_name(s) ASC/DESC -- 7. Urutkan
LIMIT    n;                      -- 8. Batasi baris

-- โ•โ• PERBEDAAN UNION / UNION ALL / INTERSECT / EXCEPT โ•โ•
-- UNION          โ†’ gabung, hapus duplikat
-- UNION ALL      โ†’ gabung, simpan duplikat
-- INTERSECT      โ†’ hanya baris yang ADA DI KEDUANYA
-- EXCEPT         โ†’ baris di query 1 yang TIDAK ADA di query 2

โšก Quick Reference โ€“ Semua Perintah & Fungsi

UPPER(col) / LOWER(col)
Huruf besar / kecil
REPLACE(col,'a','b')
Ganti substring aโ†’b
LENGTH(col)
Panjang string
LEFT(col,n) / RIGHT(col,n)
n karakter kiri/kanan
SUBSTRING(col,start,len)
Potong string
CONCAT(a,b,c)
Gabung string
TRIM(col)
Hapus spasi awal/akhir
FORMAT(num, decimal)
Format angka dengan koma
col LIKE '%x%'
Mengandung x
col LIKE '% %'
Ada spasi (โ‰ฅ2 kata)
col BETWEEN a AND b
Nilai antara a dan b
col IN (val1,val2)
Cocok salah satu nilai
col IS NULL / IS NOT NULL
Cek nilai NULL
COUNT(*) / COUNT(col)
Hitung baris / non-null
SUM(col)
Total nilai
AVG(col)
Rata-rata nilai
MAX(col) / MIN(col)
Nilai terbesar/terkecil
GROUP BY col
Kelompokkan per nilai col
HAVING kondisi_agregat
Filter setelah GROUP BY
CASE WHEN...THEN...END
Kolom kondisional
JOIN...ON / LEFT JOIN
Gabung tabel
UNION / UNION ALL
Gabung hasil SELECT
ORDER BY col ASC/DESC
Urutkan hasil
LIMIT n OFFSET m
Paging: skip m, ambil n
ALTER TABLE...ADD/MODIFY
Ubah struktur tabel
CREATE VIEW v AS SELECT
Buat virtual tabel
CREATE OR REPLACE VIEW
Update view yang ada
DROP VIEW IF EXISTS v
Hapus view
UPDATE t SET col=val WHERE
Ubah data (pakai WHERE!)
DELETE FROM t WHERE
Hapus baris (pakai WHERE!)
TRUNCATE TABLE t
Hapus semua, reset AI
YEAR() / MONTH() / DAY()
Ambil bagian tanggal