0% found this document useful (0 votes)
19 views

SQL (Structured Query Language) - Bahasa Kueri Terstruktur: o o o o o o o o o o o o o o

Uploaded by

Sharon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

SQL (Structured Query Language) - Bahasa Kueri Terstruktur: o o o o o o o o o o o o o o

Uploaded by

Sharon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

SQL (Structured Query Language) – Bahasa Kueri Terstruktur

 SQL (Structured Query Language) => Bahasa pemograman standar utk


menyimpan, memanipulasi, mengakses dan mengambil data dari
database.
 SQL adl Standar ANSI (American National Standards
Institute)/ISO(International Standardized Organization)
 Query: perintah utk meminta informasi dalam database yg dibuat
menggunakan Bahasa query seperti SQL.
o Mengeksekusi data query terhadap database.
o Mengambil data dari database
o Menginput data/catatan ke dalam database
o Memperbarui data/catatan dalam database
o Menghapus catatan/data dari database
o Membuat database baru
o Membuat tabel baru di dalam database
o Membuat prosedur yang disimpan di dalam database
o Membuat tampilan dalam database
o Mengatur izin pada tabel, prosedur, dan tampilan.
 Untuk membangun sebuah web site yg menampilkan data dari database:
o Program RDBMS database (ex: MS Access, Sql Server, MySql)
o Menggunakan Bahasa server-side scripting (PHP/ASP)
o Menggunakan SQL utk mendapatkan data yg diinginkan
o Menggunakan HTML/CSS utk melakukan style pada halaman.
 RDBMS (Relational Database Management System): dasar utk SQL dan
semua sistem database modern sprt MS SQL Server, IBM DB2, Oracle,
MySQL, Ms.Access.
 Data yg tersimpan di database pada RDBMS disebut Table.
 Tabel: kumpulan entri data yang terkait & terdiri dari kolom & baris.
 SQL Commands (perintah di dalam SQL):
o SELECT - extracts data from a database
o UPDATE - updates data in a database
o DELETE - deletes data from a database
o INSERT INTO - inserts new data into a database
o CREATE DATABASE - creates a new database
o ALTER DATABASE - modifies a database
o CREATE TABLE - creates a new table
o ALTER TABLE - modifies a table
o DROP TABLE - deletes a table
o CREATE INDEX - creates an index (search key)
o DROP INDEX - deletes an index

SELECT SYNTAX: memilih data dari database.


SELECT column1, column2, ...
FROM table_name;

SELECT CustomerName, City FROM Customers;


 Column1/column2: merupakan field name (judul baris) dari sebuah
tabel database.
SELECT ALL SYNTAX: memilih menampilkan semua data dari database.
SELECT * FROM table name;

SELECT * FROM Customers;


SELECT DISTINCT: digunakan utk mengembalikan hanya nilai yg berbeda.
SELECT DISTINCT column1, column2, ...
FROM table_name;

SELECT DISTINCT Country FROM Customers;

WHERE: DIGUNAKAN UTK MEMFILTER DATA DENGAN KONDISI


TERTENTU
SELECT column1, column2, ...
FROM table_name
WHERE condition;

SELECT * FROM Customers


WHERE Country='Mexico';
SQL memerlukan tanda kutip tunggal di sekitar nilai teks (sebagian besar
sistem basis data juga mengizinkan tanda kutip ganda).
Namun, UTK ANGKA tidak boleh diapit tanda kutip:

SELECT * FROM Customers


WHERE CustomerID=1;
OPERATOR IN THE WHERE CLAUSES

SELECT * FROM Customers


WHERE CustomerID > 80;

Operator Description Example

= Equal SELECT * FROM Products

WHERE Price = 18;

> Greater than SELECT * FROM Products

WHERE Price > 30; (data 30


tidak terambil)

< Less than SELECT * FROM Products

WHERE Price < 30;

>= Greater than or SELECT * FROM Products


equal
WHERE Price >= 30; (Data 30
masih terambil)

<= Less than or equal SELECT * FROM Products

WHERE Price <= 30;

<> Not equal. Note: In SELECT * FROM Products


some versions of
SQL this operator WHERE Price <> 18;
may be written as !
=

BETWEEN Between a certain SELECT * FROM Products


range
WHERE Price BETWEEN 50
AND 60;

LIKE Search for a pattern SELECT * FROM Customers

WHERE City LIKE 's%';


(memilih kota dengan huruf
awalan s)

IN To specify multiple SELECT * FROM Customers


possible values for a
column WHERE City IN ('Paris','London');
SQL ORDER BY: DIGUNAKAN UTK MENYORTIR DATA DALAM
ASCENDING (MENINGKAT) ATAU DESCENDING (MENURUN)
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

SELECT * FROM Products


ORDER BY Price;
SELECT * FROM Products
ORDER BY Price DESC;
SELECT * FROM Products
ORDER BY ProductName;
SELECT * FROM Products
ORDER BY ProductName DESC;
ORDER BY SEVERAL COLUMNS

SELECT * FROM Customers


ORDER BY Country, CustomerName;
USING BOTH ASC & DESC

SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;

SQL AND OPERATOR: Klausa WHERE dapat berisi satu atau


beberapa operator AND.

Operator AND digunakan untuk memfilter rekaman berdasarkan


lebih dari satu kondisi:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
SELECT *
FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';
AND VS OR

Operator AND menampilkan record jika semua kondisi TRUE.


Operator OR menampilkan catatan jika salah satu kondisinya TRUE.
SELECT * FROM Customers
WHERE Country= 'Germany'
AND City= 'Berlin'
AND PostalCode > 12000;
COMBINING AND & OR

SELECT * FROM Customers


WHERE Country = 'Spain' AND (CustomerName LIKE 'G
%' OR CustomerName LIKE 'R%');

SQL OR OPERATOR: Klausa WHERE dapat berisi satu atau lebih operator
OR.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

SELECT *
FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';

SQL NOT OPERATOR


Operator NOT digunakan bersama dengan operator lain untuk memberikan
hasil sebaliknya, ATAU HASIL NEGATIF.
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

SELECT * FROM Customers


WHERE NOT Country = 'Spain';
NOT LIKE: Select customers that does not start with the letter 'A':

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'A%';
NOT BETWEEN: Select customers with a customerID not between 10
and 60:
SELECT * FROM Customers
WHERE CustomerID NOT BETWEEN 10 AND 60;
NOT IN: Select customers that are not from Paris or London:
SELECT * FROM Customers
WHERE City NOT IN ('Paris', 'London');
NOT Greater Than

Select customers with a CustomerId not greater than 50:

SELECT * FROM Customers


WHERE NOT CustomerID > 50;
NOT Less Than

Select customers with a CustomerID not less than 50:

SELECT * FROM Customers


WHERE NOT CustomerId < 50;

SQL INSERT INTO Statement: insert data baru ke tabel


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

The following SQL statement inserts a new record in the


"Customers" table:
INSERT INTO Customers (CustomerName, ContactName,
Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
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
INSERT INTO table_name
VALUES (value1, value2, value3, ...);

Insert Data Only in Specified Columns


The following SQL statement will insert a new record, but only insert data in
the "CustomerName", "City", and "Country" columns (CustomerID will be
updated automatically):
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

Insert Multiple Rows


INSERT INTO Customers (CustomerName, ContactName,
Address, City, PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien
15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad
19B', 'Liverpool', 'L1 0AA', 'UK');
SQL NULL Values
A field with a NULL value is a field with no value. (Bidang dengan
nilai NULL adalah bidang tanpa nilai.)

How to Test for NULL Values?


Use the IS NULL or IS NOT NULL operators.

IS NULL Syntax
The IS NULL operator is used to test for empty values (NULL
values).

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


The IS NOT NULL operator is used to test for non-empty values
(NOT NULL values).

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

The SQL UPDATE


Digunakan utk memodifikasi data yg sudah ada dalam tabel.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

The following SQL statement updates the first customer


(CustomerID = 1) with a new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records will
be updated.
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The SQL DELETE Statement


Digunakan untuk menghapus data yg sudah ada di tabel.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Delete All Records


DELETE FROM table_name;

Delete a Table
DROP TABLE Customers;

SQL TOP, LIMIT,


FETCH FIRST or
ROWNUM Clause
SQL SELECT TOP Clause
DIGUNAKAN UTK MENENTUKAN JUMLAH RECORD YANG AKAN
DIKEMBALIKAN.
SELECT TOP 3 * FROM Customers;

LIMIT
The following SQL statement shows the equivalent example for
MySQL:
Example
Select the first 3 records of the Customers table:

SELECT * FROM Customers


LIMIT 3;

FETCH FIRST
The following SQL statement shows the equivalent example for
Oracle:

Example
Select the first 3 records of the Customers table:

SELECT * FROM Customers


FETCH FIRST 3 ROWS ONLY;

SQL TOP PERCENT Example


The following SQL statement selects the first 50% of the records
from the "Customers" table (for SQL Server/MS Access):

Example
SELECT TOP 50 PERCENT * FROM Customers;

ADD a WHERE CLAUSE


The following SQL statement selects the first three records from the
"Customers" table, where the country is "Germany" (for SQL
Server/MS Access):

Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

ADD the ORDER BY Keyword


Add the ORDER BY keyword when you want to sort the result, and
return the first 3 records of the sorted result.

For SQL Server and MS Access:

Example
Sort the result reverse alphabetically by CustomerName, and return
the first 3 records:

SELECT TOP 3 * FROM Customers


ORDER BY CustomerName DESC;
SELECT * FROM Customers
ORDER BY CustomerName DESC
LIMIT 3;

SQL Aggregate Functions


FUNGSI UTK MELAKUKAN PERHITUNGAN PADA SEKUMPULAN NILAI
UNTUK MENGENMBALIKAN SATU NILAI.
SERING DIGUNAKAN DENGAN KLAUSA GROUP BY PADA PERNYATAAN
SELECT.

The most commonly used SQL aggregate functions are:

 MIN() - returns the smallest value within the selected column


 MAX() - returns the largest value within the selected column
 COUNT() - returns the number of rows in a set
 SUM() - returns the total sum of a numerical column
 AVG() - returns the average value of a numerical column

The SQL MIN() and MAX()


Functions
The MIN() function returns the smallest value of the selected
column.

The MAX() function returns the largest value of the selected column.

SELECT MIN/MAX(column_name)
FROM table_name
WHERE condition;
SELECT MIN(Price)// MAX(Price)
FROM Products;

Set Column Name (Alias)


When you use MIN() or MAX(), the returned column will not have a
descriptive name. To give the column a descriptive name, use
the AS keyword:
SELECT MIN(Price) AS SmallestPrice
FROM Products;

Use MIN() with GROUP BY


Here we use the MIN() function and the GROUP BY clause, to return
the smallest price for each category in the Products table:
SELECT MIN(Price) AS SmallestPrice, CategoryID
FROM Products
GROUP BY CategoryID;

The SQL COUNT() Function


The COUNT() function returns the number of rows that matches a
specified criterion.

Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

SELECT COUNT(*)
FROM Products;

Specify Column
You can specify a column name instead of the asterix symbol (*).

If you specify a column name instead of (*), NULL values will not be
counted.

SELECT COUNT(ProductName)
FROM Products;
Add a WHERE Clause
You can add a WHERE clause to specify conditions:

SELECT COUNT(ProductID)
FROM Products
WHERE Price > 20;

Ignore Duplicates
You can ignore duplicates by using the DISTINCT keyword in
the COUNT() function.

If DISTINCT is specified, rows with the same value for the specified
column will be counted as one.

Example
How many different prices are there in the Products table:

SELECT COUNT(DISTINCT Price)


FROM Products;

Use an Alias
Give the counted column a name by using the AS keyword.

Example
Name the column "Number of records":

SELECT COUNT(*) AS [Number of records]


FROM Products;

Use COUNT() with GROUP BY


Here we use the COUNT() function and the GROUP BY clause, to return
the number of records for each category in the Products table:

SELECT COUNT(*) AS [Number of records], CategoryID


FROM Products
GROUP BY CategoryID;
The SQL SUM() Function
The SUM() function returns the total sum of a numeric column.

Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Example
Return the sum of all Quantity fields in the OrderDetails table:

SELECT SUM(Quantity)
FROM OrderDetails;
SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
Use an Alias:
SELECT SUM(Quantity) AS total
FROM OrderDetails;
SUM with GroupBy()
SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;
SUM with an EXPRESSIon
The parameter inside the SUM() function can also be an expression.

Use an expression inside the SUM() function:

SELECT SUM(Quantity * 10)


FROM OrderDetails;
Or
SELECT SUM(Price * Quantity)
FROM OrderDetails
LEFT JOIN Products ON OrderDetails.ProductID =
Products.ProductID;

The SQL AVG() Function


The AVG() function returns the average value of a numeric column.

SELECT AVG(column_name)
FROM table_name
WHERE condition;

SELECT AVG(Price)
FROM Products;
WHERE CategoryID = 1;
Use an alias
Name the column "average price":
SELECT AVG(Price) AS [average price]
FROM Products;

Higher Than Average


To list all records with a higher price than average, we can use
the AVG() function in a sub query:

Return all products with a higher price than the average price:

SELECT * FROM Products


WHERE price > (SELECT AVG(price) FROM Products);

Use AVG() with GROUP BY


Here we use the AVG() function and the GROUP BY clause, to return
the average price for each category in the Products table:

SELECT AVG(Price) AS AveragePrice, CategoryID


FROM Products
GROUP BY CategoryID;

The SQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.

There are two wildcards often used in conjunction with


the LIKE operator:

 The percent sign % represents zero, one, or multiple


characters
 The underscore sign _ represents one, single character

SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

The _ Wildcard
The _ wildcard represents a single character.

It can be any character or number, but each _ represents one, and


only one, character.

SELECT * FROM Customers


WHERE city LIKE 'L_nd__';

The % Wildcard
The % wildcard represents any number of characters, even
zero characters.

Return all customers from a city that contains the letter 'L':

SELECT * FROM Customers


WHERE city LIKE '%L%';

Starts With
To return records that starts with a specific letter or phrase, add
the % at the end of the letter or phrase.

Return all customers that starts with 'La':

SELECT * FROM Customers


WHERE CustomerName LIKE 'La%';

Ends With
To return records that ends with a specific letter or phrase, add
the % at the beginning of the letter or phrase.
Example
Return all customers that ends with 'a':

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';

Contains
To return records that contains a specific letter or phrase, add
the % both before and after the letter or phrase.

Example
Return all customers that contains the phrase 'or'

SELECT * FROM Customers


WHERE CustomerName LIKE '%or%';

Combine Wildcards
Any wildcard, like % and _ , can be used in combination with other
wildcards.

Example
Return all customers that starts with "a" and are at least 3
characters in length:

SELECT * FROM Customers


WHERE CustomerName LIKE 'a__%';

Without Wildcard
If no wildcard is specified, the phrase has to have an exact match to
return a result.

Example
Return all customers from Spain:

SELECT * FROM Customers


WHERE Country LIKE 'Spain';
SQL Wildcard Characters
Symbol Description

% Represents zero or more characters

_ Represents a single character

[] Represents any single character within the brackets *

^ Represents any character not in the brackets *

- Represents any single character within the specified range *

{} Represents any escaped character **

* Not supported in PostgreSQL and MySQL databases.


** Supported only in Oracle databases.

Microsoft Access Wildcards


The Microsoft Access Database has some other wildcards:

Symbol Description Example


* Represents zero or more characters bl* finds bl, black, blue, and blob
? Represents a single character h?t finds hot, hat, and hit
[] Represents any single character h[oa]t finds hot and hat, but not hit
within the brackets
! Represents any character not in the h[!oa]t finds hit, but not hot and hat
brackets

- Represents any single character c[a-b]t finds cat and cbt


within the specified range

# Represents any single numeric 2#5 finds 205, 215, 225, 235, 245,
character 255, 265, 275, 285, and 295

The SQL IN Operator


The IN operator allows you to specify multiple values in
a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.


SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

NOT IN
By using the NOT keyword in front of the IN operator, you return all
records that are NOT any of the values in the list.

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', 'UK');

IN (SELECT)
You can also use IN with a subquery in the WHERE clause.

With a subquery you can return all records from the main query that
are present in the result of the subquery.

Example
Return all customers that have an order in the Orders table:

SELECT * FROM Customers


WHERE CustomerID IN (SELECT CustomerID FROM Orders);

NOT IN (SELECT)
The result in the example above returned 74 records, that means
that there are 17 customers that haven't placed any orders.

Let us check if that is correct, by using the NOT IN operator.

Example
Return all customers that have NOT placed any orders in
the Orders table:

SELECT * FROM Customers


WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders);

You might also like