• Tidak ada hasil yang ditemukan

Module 10. SQL (Structured Query Language) Slamet Kacung, S.Kom., M.Kom.

N/A
N/A
Protected

Academic year: 2022

Membagikan "Module 10. SQL (Structured Query Language) Slamet Kacung, S.Kom., M.Kom."

Copied!
30
0
0

Teks penuh

(1)

Slamet Kacung, S.Kom., M.Kom.

Module 10.

SQL (Structured Query Language)

(2)

Capaian Pembelajaran

 Mahasiswa mampu mebuat Data Definition Language (DDL)

 Mahasiswa mampu membuat Data Manipulation Language (DML)

 Mahasiswa mampu membuat relasi antar tabel (Join)

 Mahasiswa mampu membuat Fungsi Agregasi (Agregate Function)

 Mahasiswa mampu membuat Sub Query

(3)

Materi SQL

 Introduction

 Data Definition Language (DDL)

 Data Manipulation Language (DML)

 Basic Structure

 Rename Operations

 String Operations

 Joined Relations (Query)

 Aggregate Functions

 Sub Query

(4)

Tujuan

 Menjelaskan bahasa formal yang digunakan pada basis data relasional

 Menjelaskan SQL sebagai bahasa yang standar

 Memberikan beberapa contoh teknik pembuatan query, Sub

Query dengan menggunakan SQL

(5)

Pengertian

 Query adalah perintah-perintah untuk mengakses data pada sistem basis data

 SQL adalah bahasa query baku untuk DBMS

 SQL diambil sebagai perintah baku sejak tahun 1992

 Awalnya diterapkan pada DBMS besar seperti Oracle,

sekarang juga pada DBMS berbasis PC seperti PostgreSQL, MySQL, MS. Access.

 SQL bersifat sebagai bahasa tingkat tinggi (high level).

Pemakai hanya menyebutkan hasil yang diinginkan dan

optimasi pelaksanaan query dilakukan oleh DBMS.

(6)

Pengertian (1)

SQL dapat disisipkan ke bahasa pemrograman yang lain seperti Java, Borland Delphi, Visual Basic, dll.

Bahasa SQL terbagi dalam dua bagian besar, yaitu: DDL (Data Definition Language) dan DML (Data Manipulation Language)

DDL mendefinisikan struktur basis data, seperti pembuatan basis data, tabel, dsb. Contoh: CREATE DATABASE dan CREATE TABLE.

DML merupakan bagian untuk memanipulasi basis data seperti: pengaksesan data, penghapusan, penambahan dan pengubahan data.

Contoh: INSERT, UPDATE, dan DELETE.

(7)

DDL

Perintah SQL untuk definisi data:

CREATE untuk membentuk basis data, taable atau index

ALTER untuk mengubah struktur table

DROP untuk menghapus basis data, table atau index

CREATE DATABASE

Untuk membentuk basis data

Sintaks: CREATE DATABASE nama_database

Contoh: CREATE DATABASE BANK

CREATE TABLE

Untuk membentuk table dari basis data

Untuk menyebutkan spesifikasi dan batasan atribut

(8)

DDL (1)

Contoh CREATE TABLE:

CREATE TABLE EMPLOYEE

( FNAME CHAR(15) NOT NULL LNAME CHAR(15) NOT NULL SSN CHAR(9) NOT NULL

BDATE DATE

ADDRESS CHAR(30) SEX CHAR

SALARY DECIMAL(10.2)

DNO CHAR(10) );

(9)

DDL (2)

ALTER TABLE

Digunakan untuk mengubah struktur table

Contoh kasus: misalkan ingin menambahkan kolom JOB pada table EMPLOYEE dengan tipe karakter selebar 12.

Perintah:

ALTER TABLE EMPLOYEE ADD JOB CHAR(12);

(10)

DDL (3)

 CREATE INDEX

 Membentuk berkas index dari table

 Index digunakan untuk mempercepat proses pencarian

 Sintaks:

CREATE [UNIQUE] INDEX nama_index ON nama_table(kolom1, kolom2, …. )

 Contoh:

CREATE INDEX EMPLOYEENDX ON EMPLOYEE(SSN)

(11)

DDL (4)

 Menghapus Basis Data

DROP DATABASE

Sintaks: DROP DATABASE nama_database

Contoh: DROP DATABASE COMPANY

 Menghapus Table

DROP TABLE

Sintaks: DROP TABLE nama_table

Contoh: DROP TABLE EMPLOYEE

 Menghapus Berkas Index

DROP INDEX

Sintaks: DROP INDEX nama_index

Contoh: DROP INDEX EMPLOYEENDX

(12)

DML

 Bahasa untuk mengakses basis data

 Bahasa untuk mengolah basis data

 Bahasa untuk memanggil fungsi-fungsi agregasi

 Bahasa untuk melakukan query

 Jenis-jenis query:

 Sederhana

 Join

 Bertingkat

(13)

Contoh Skema

(14)

Basic Structure

 SQL is based on set and relational operations with certain modifications and enhancements

A typical SQL query has the form: select A1, A2, ..., An from r1, r2, ..., rm where P

A is represent attributes

r is represent relations

P is a predicate.

 This query is equivalent to the relational algebra expression.

A1, A2, ..., An(P (r1 x r2

x ... x rm))

 The result of an SQL query is a relation.

(15)

Query Sederhana

 Bentuk umum SQL

SELECT [ALL|DISTINCT]

nama_kolom_kolom_tabel [INTO nama_tabel]

FROM nama_nama_tabel [WHERE predikat]

[GROUP BY ekspresi]

[ORDER BY nama+kolom_tabel]

(16)

Select Clause

The select clause corresponds to the projection operation of the relational algebra. It is used to list the attributes desired in the result of a query.

Find the names of all branches in the loan relation select branch-name from loan

In the “pure” relational algebra syntax, the query would be:

branch-name(loan)

An asterisk in the select clause denotes “all attributes”

select * from loan

NOTE: SQL does not permit the ‘-’ character in names, so you would use, for example, branch_name instead of branch-name in a real implementation. We use ‘-

’ since it looks nicer!

NOTE: SQL names are case insensitive, meaning you can use upper case or lower case.

You may wish to use upper case in places where we use bold font

(17)

Select Clause (1)

SQL allows duplicates in relations as well as in query results.

To force the elimination of duplicates (menghilangkan duplikasi penampilan output yang sama) insert the keyword distinct after select.

Find the names of all branches in the loan relations, and remove duplicates

select distinct branch-name from loan

The keyword all specifies that duplicates not be removed.

select all branch-name from loan

Menampilkan isi tabel customer

select * from customer

Menampilkan semua fname dari tabel customer

select customer_name from customer

(18)

Select Clause (2)

Menampilkan account number dan balance dari kantor cabang (branch_name)

“Pondok Kelapa”

select account_number, balance from account

where branch_name = “Pondok Kelapa”;

Perintah diatas dapat juga dituliskan dengan menggunakan qualified column names sebagai berikut:

select account.account_number, account.balance from account

where branch_name = “Pondok Kelapa”;

(19)

Select Clause (3)

The select clause can contain arithmetic expressions involving the operation, +, –, * , and /, and operating on constants or attributes of tuples.

The query:

select loan-number, branch-name, amount 100

from loan

would return a relation which is the same as the loan relations, except that the attribute amount is multiplied by 100.

(20)

Where Clause

The where clause corresponds to the selection predicate of the relational algebra. If consists of a predicate involving attributes of the relations that appear in the from clause.

The find all loan number for loans made a the Perryridge branch with loan amounts greater than $1200.

select loan-number from loan

where branch-name = ‘Perryridge’ and amount > 1200

Comparison results can be combined using the logical connectives and, or, and not.

Comparisons can be applied to results of arithmetic expressions.

(21)

Where Clause (1)

SQL Includes a between comparison operator in order to simplify where clauses that specify that a value be less than or equal to some value and greater than or equal to some other value.

Find the loan number of those loans with loan amounts between $90,000 and

$100,000 (that is, $90,000 and $100,000)

select loan-number from loan

where amount between 90000 and 100000

(22)

Rename Operation

 The SQL allows renaming relations and attributes using the as clause:

old-name as new-name

 Find the name, loan number and loan amount of all

customers; rename the column name loan-number as loan-id.

select customer-name, borrower.loan-number as loan-id, amount from borrower, loan

where borrower.loan-number = loan.loan-number

(23)

String Operation

SQL includes a string-matching operator for comparisons on character strings.

Find the names of all customers whose street includes the substring “Main”.

select customer-name

from customer

where customer-street like ‘%Main%’

SQL supports a variety of string operations such as

concatenation (using “||”)

converting from upper to lower case (and vice versa)

finding string length, extracting substrings, etc.

(24)

Join Relation

 List in alphabetic order the names of all customers having a loan in Perryridge branch

select distinct customer-name from borrower inner join loan

on borrower.loan-number = loan.loan-number where branch-name =

‘Perryridge’

order by customer-name

We may specify desc for descending order or asc for

ascending order, for each attribute; ascending order is the default.

E.g. order by customer-name desc

(25)

Ordering

 List in alphabetic order the names of all customers having a loan in Perryridge branch

select distinct customer-name from borrower, loan

where borrower.loan-number = loan.loan-number and branch-name

= ‘Perryridge’

order by customer-name

We may specify desc for descending order or asc for

ascending order, for each attribute; ascending order is the default.

E.g. order by customer-name desc

(26)

Aggregate Function

 These functions operate on the multiset of values of a column of a relation, and return a value

avg: average value

min: minimum value

max: maximum value

sum: sum of values

count: number of values

(27)

Aggregate Function (1)

Find the average account balance at the Perryridge branch.

select avg (balance)

from account

where branch-name = ‘Perryridge’

Find the number of tuples in the customer relation.

select count (*) from customer

Find the number of depositors in the bank.

select count (distinct customer-name)

from depositor

(28)

Aggregate Function - Group By

Find the number of depositors for each branch.

select branch-name, count (distinct customer-name)

from depositor, account

where depositor.account-number = account.account-number group by branch-name

Note: Attributes in select clause outside of aggregate functions must appear in

group by list

(29)

Aggregate Function – having clause

Find the names of all branches where the average account balance is more than

$1,200.

select branch-name, avg (balance) from account

group by branch-name

having avg (balance) > 1200

Note: predicates in the having clause are applied after the formation of groups

whereas predicates in the where clause are applied before forming groups

(30)

Sub Query

 Mencari nama dan gaji dari seorang pegawai, yang memiliki gaji paling kecil

SELECT Fname, Salary FROM Employee

WHERE Salary = (SELECT min(Salary)

FROM Employee)

Referensi

Dokumen terkait