Jumat, 23 November 2012

Learn SQL Join with Simple Way

Right now I give super simple SQL queries to learn joins like inner join, right join, left join. These SQL commands are suitable for most RDBMS like MySQL, Oracle, SQL Server, etc. Hope you enjoy it!

Kali ini saya memberikan query-query sederhana SQL untuk belajar join seperti inner join, right join, left join. Perintah-perintah SQL yang ditulis cocok untuk sebagian besar RDBMS seperti MySQL, Oracle, SQL Server, dll. Selamat belajar!

create table pegawai (
  nip varchar(3) primary key,
  nama varchar(50),
  atasan varchar(3)
);

insert into pegawai values
  ('001','ali','001'),
  ('002','budi','001'),
  ('003','buce','001'),
  ('004','cici','002'),
  ('005','dedi','002'),
  ('006','fifi','003');
 
create table gaji (
  nip varchar(3),
  gaji int(50)
);

insert into gaji values
  ('001',6000000),
  ('002',5000000),
  ('003',4000000),
  ('004',3000000),
  ('007',2000000),
  ('008',1000000);

-- inner join 
SELECT
  pegawai.nip,
  pegawai.nama,
  gaji.gaji
FROM pegawai
inner join gaji
  on pegawai.nip = gaji.nip

-- inner join dengan alias 
SELECT
  a.nip,
  a.nama,
  b.gaji
FROM pegawai AS a
inner join gaji as B
  on a.nip = b.nip
 
-- left join
SELECT
  pegawai.nip,
  pegawai.nama,
  gaji.gaji
FROM pegawai LEFT join gaji
  on pegawai.nip = gaji.nip
 
-- right join
SELECT
  pegawai.nip,
  pegawai.nama,
  gaji.gaji
FROM pegawai RIGHT join gaji
  on pegawai.nip = gaji.nip
 
-- contoh lain
-- menampilkan nama pegawai
-- yg gajinya di atas 4 jt
SELECT
  pegawai.nama
FROM pegawai
inner join gaji
  on pegawai.nip = gaji.nip
where gaji.gaji > 4000000 

-- contoh lagi
-- menampilkan nama pegawai
-- yg blm memiliki gaji
SELECT
  pegawai.nama
FROM pegawai
left join gaji
  on pegawai.nip = gaji.nip
where gaji.gaji is null

-- contoh inner join implisit
-- (tidak memakai perintah inner join)
SELECT
  pegawai.nip,
  pegawai.nama,
  gaji.gaji
FROM pegawai, gaji
WHERE pegawai.nip = gaji.nip

create table golongan (
  nip varchar(3),
  gol int default 1,
  tglSK date
);

insert into golongan values
  ('001',6, '2000-02-02'),
  ('002',5, '2000-02-02'),
  ('003',3, '2000-03-03'),
  ('004',3, '2000-03-03'),
  ('005',2, '2002-11-11'),
  ('006',1, '2002-11-11');
 
-- inner join lebih dari dua tabel
select
  pegawai.nip,
  pegawai.nama,
  golongan.gol,
  gaji.gaji
from pegawai
inner join golongan
  on pegawai.nip = golongan.nip
inner join gaji
  on pegawai.nip = gaji.nip

Tidak ada komentar: