Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Menyisipkan Judul Report didalam Statement SQL

Wednesday, August 6, 2008
Inti dari tutorial ini adalah menunjukan bagaimana caranya menyisipkan string reguler didalam statement SQL. String reguler disini maksudnya adalah string yang bukan nilai dari sebuah table di dalam Database. Contoh :

SELECT 'Daftar Produk (Seluruh)' AS Judul, ProductID,ProductName
FROM Products

Judul ProductID ProductName
------------- ----------- ----------------------------------------
Daftar Produk 17 Alice Mutton
Daftar Produk 3 Aniseed Syrup
Daftar Produk 40 Boston Crab Meat
Daftar Produk 60 Camembert Pierrot
Daftar Produk 18 Carnarvon Tigers
Daftar Produk 1 Chai
. . . .
. . . .

77 rows selected

Statement SQL diatas akan menambahkan kolom JUDUL yang berisi nilai yang sama pada output query nya. nilai-nilai yang ada dibawah kolom JUDUL bukan merupakan nilai-nilai yang ada di table PRODUCTS, melainkan string biasa yang kita sertakan dalam Statement SQL nya. dibawah ini saya akan memperlihatkan contoh bagaimana metode ini dipakai untuk menyisipkan judul laporan yang berbeda kedalam SQL Statement menggunakan hanya satu komponen FastReport di Delphi.

Cara ini biasa saya gunakan untuk menghasilkan judul report berdasarkan parameter yang saya inputkan. misalnya saya akan menampilkan laporan daftar produk per supplier dan ingin agar judul report sesuai dengan nama supplier yang ingin saya cetak misalnya judul report nya ingin seperti ini : 'Daftar Produk Supplier : PT. ABC', 'Daftar Produk Supplier : PT. XYZ' dst dengan catatan struktur kolom dari report tersebut sama. Jadi parameternya saya sisipkan kedalam SQL Statement yang digunakan untuk pengambilan datanya. Sebagai contoh dibawah ini saya perlihatkan bagaimana caranya menyisipkan judul untuk report kedalam sebuah SQL statement menggunakan komponen FastReport dan ADOQuery di Delphi.

procedure TForm1.Button1Click(Sender: TObject);
begin
adoquery1.Close;
adoquery1.SQL.Clear;
adoquery1.SQL.Add('SELECT ');
adoquery1.SQL.Add('''Daftar Produk Supplier : ''+a.CompanyName as Judul,');
adoquery1.SQL.Add('B.ProductID,A.CompanyName,b.ProductName,');
adoquery1.SQL.Add('b.QuantityPerUnit,b.UnitPrice,b.UnitsInStock ');
adoquery1.SQL.Add('FROM suppliers a, Products b ');
adoquery1.SQL.Add('where a.SupplierID=b.SupplierID ');
adoquery1.SQL.Add('AND a.CompanyName = :CN');
adoquery1.Parameters[0].Value := combobox1.Text;
adoquery1.Prepared := true;
adoquery1.Open;

//kalau data ada
if adoquery1.RecordCount > 0 then
frxReport1.ShowReport();

end;


kamu bisa lihat didalam Statement SQL diatas saya sisipkan string 'Daftar Produk Supplier :' yang digabung dengan nilai CompanyName dari table Suppliers yang kemudian dialiaskan sebagai kolom/field Judul yang nantinya field/kolom Judul ini akan saya tempatkan di report sebagai judul report. agar lebih jelas kamu bisa lihat gambar dibawah ini :

Report Design
Report Design

Application Runtime
Application Runtime


Report Runtime
Report Runtime

Dengan metode ini kamu bisa memberikan judul report yang lebih detail tanpa harus memboroskan pemakaian komponen untuk mencetak berbagai report yang mempunyai struktur kolom yang sama.

Download Source Code Aplikasi ini disini.

SQL : Using subquery to resolving query problems

Sunday, July 13, 2008
When working with databases and records sometimes we find difficulties in displaying data from many tables using SQL join. For example you wish to include some aggregate columns from three tables below :

the structure of the products table :


ProductID text(15),
VendorID text(15),
Descriptions text(50),
UnitsInStock integer,
Price integer

Data in the products table :



ProductID VendorID Descriptions UnitsInStock
---------- -------- ------------------------------------------ ------------
SDB0001 V0001 MS SQL Server Database 2005 5
SDB0002 V0002 Oracle Database 10g Enterprise 6
SDB0003 V0003 MySQL 5.0 Enterprise Edition 8
SDBA0001 V0004 Navicat For MySQL Administration 6
SDBA0002 V0005 Dreamcoder 4.1 For MySQL Enterprise 4
SDBA0003 V0005 Dreamcoder 4.1 For MySQL Profesional 8
SDBA0004 V0005 Dreamcoder 4.1 For MS SQL Server Database 4





the structure of the Purchasing table :


ProductID text(15),
VendorID text(15),
PurchaseDate date,
Quantity integer

Data in the Purchasing table :



ProductID PurchaseDate Quantity
---------- ------------ --------
SDB0001 7/1/2008 10
SDB0002 7/1/2008 12
SDB0003 7/1/2008 12
SDBA0001 7/1/2008 8
SDBA0002 7/1/2008 3
SDBA0003 7/1/2008 8
SDBA0004 7/1/2008 8
SDB0001 7/2/2008 7
SDB0002 7/2/2008 9
SDB0003 7/2/2008 7
SDBA0001 7/2/2008 7
SDBA0002 7/2/2008 3
SDBA0003 7/2/2008 7
SDBA0004 7/2/2008 7




the structure of the sales table :


ProductID text(15),
VendorID text(15),
SalesDate date,
Quantity integer

Data in the sales table :



ProductID SalesDate Quantity
---------- ------------ --------
SDB0001 7/1/2008 8
SDB0002 7/1/2008 8
SDB0003 7/1/2008 9
SDBA0001 7/1/2008 4
SDBA0002 7/1/2008 1
SDBA0003 7/1/2008 2
SDBA0004 7/1/2008 5
SDB0001 7/2/2008 4
SDB0002 7/2/2008 7
SDB0003 7/2/2008 2
SDBA0001 7/2/2008 5
SDBA0002 7/2/2008 1
SDBA0003 7/2/2008 5
SDBA0004 7/2/2008 6


there is two productid that have the same values in each of sales and purchasing table. Now you want to display how many quantity bought, quantity sold, and quantity available now by joining three tables above so that query output give you the clear information concerning all products.



I will show you how this can confusing when its done by a query especially for SQL newbies. below is an example of wrong SQL statement that will give you incorrect information about the data :



SELECT a.productid, a.descriptions,
sum(b.quantity) AS prchqty,
sum(c.quantity) as salesqty, a.unitsinstock
FROM products AS a, purchasing AS b, sales c
WHERE a.productid=b.productid
and a.productid=c.productid
GROUP BY a.productid, a.descriptions, a.unitsinstock



query output:



productid descriptions prchqty salesqty unitsinstock
--------- ------------------------------------------ ------- -------- ------------
SDB0001 MS SQL Server Database 2005 34 24 5
SDB0002 Oracle Database 10g Enterprise 42 30 6
SDB0003 MySQL 5.0 Enterprise Edition 38 22 8
SDBA0001 Navicat For MySQL Administration 30 18 6
SDBA0002 Dreamcoder 4.1 For MySQL Enterprise 12 4 4
SDBA0003 Dreamcoder 4.1 For MySQL Profesional 30 14 8
SDBA0004 Dreamcoder 4.1 For MS SQL Server Database 30 22 4


the query output above giving incorrect information for the prchqty and salesqty column. it is caused by there are more than one productid which have the same values in each of the purchasing table and the sales table so that when you join the tables using productid column the query output will display the column quantity become twice from real quantity.



to resolving this problem you can use a view and or a subquery but in this tutorial I will only show how to use subqueries to resolving the problem. below is the right SQL statement which will give a correct information about the data (note : this query will not working in previous version of MySQL 6, paradox database, and interbase 6) :



SELECT a.productid, a.descriptions,
sum(b.quantity) AS prchqty, c.salesqty,a.unitsinstock
FROM products AS a, purchasing AS b,
(select productid,sum(quantity) as salesqty
from sales
group by productid) AS c

WHERE a.productid=b.productid
and a.productid=c.productid
GROUP BY a.productid, a.descriptions,
c.salesqty, a.unitsinstock


query output :



productid descriptions prchqty salesqty unitsinstock
--------- ------------------------------------------ ------- -------- ------------
SDB0001 MS SQL Server Database 2005 17 12 5
SDB0002 Oracle Database 10g Enterprise 21 15 6
SDB0003 MySQL 5.0 Enterprise Edition 19 11 8
SDBA0001 Navicat For MySQL Administration 15 9 6
SDBA0002 Dreamcoder 4.1 For MySQL Enterprise 6 2 4
SDBA0003 Dreamcoder 4.1 For MySQL Profesional 15 7 8
SDBA0004 Dreamcoder 4.1 For MS SQL Server Database 15 11 4


in the above query, string which in bold is subquery or which I call inline view. the subquery above will produce productid column and salesqty column which the data is taken from the sales table which then aliased as table C, so that each productid from the products table (A) will be joined to one productid in the purchasing table (B) and sales table (C).

SQL BETWEEN: Searching Between Two Specified Values (Range)

Monday, June 9, 2008

Syntax


expression [ NOT ] BETWEEN lower_value AND higher_value



The SQL BETWEEN Operator are used to display rows between two specified values. The lower value are placed before AND operator and the higher value are placed after AND operator.


For Example you have a table called Articles that contain the following Data:




ArticleID Title PageView PublishDate
--------- ------------------------- ----------- -------------------
1 SQL JOIN Example 43 2008-06-04 15:18:00
2 SQL BETWEEN Example 84 2008-06-07 15:23:00
3 SQL Where Example 0 2008-06-07 15:27:00
4 SQL: Find Duplicate Values 102 2008-05-29 15:30:00
5 SQL HAVING Example 50 2008-03-19 15:33:00





Using SQL Between on Numeric Data Type Field


The following SQL Statement example will return Articles that having PageView Between 50 and 100:




Select ArticleID,Title,PageView,PublishDate

from Articles

where PageView Between 50 and 100



Query Result:


ArticleID Title PageView PublishDate
--------- ------------------------- ----------- -------------------
2 SQL BETWEEN Example 84 2008-06-07 15:23:00
5 SQL HAVING Example 50 2008-03-19 15:33:00






Using SQL Between on Date Data Type Field


The following SQL Statement example will return Articles published between 29th May 2008 and 8th June 2008 :




Select ArticleID,Title,PageView,PublishDate

from articles

where PublishDate between '29-may-2008' and '08-jun-2008'



Query Result


ArticleID Title PageView PublishDate
--------- ------------------------- ----------- -------------------
1 SQL JOIN Example 43 2008-06-04 15:18:00
2 SQL BETWEEN Example 84 2008-06-07 15:23:00
3 SQL Where Example 0 2008-06-07 15:27:00
4 SQL: Find Duplicate Values 102 2008-05-29 15:30:00






you can use SQL Statement bellow if you work with a MS Access Database. it will produce the same result



Select ArticleID,Title,PageView,PublishDate

from articles

where PublishDate between #01/06/2008# and #08/06/2008#





To display rows outside the range you specified, you must omits NOT operator before BETWEEN operator. Example :




Select ArticleID,Title,PageView,PublishDate

from Articles

where PageView Not Between 50 and 100


Query Result


ArticleID Title PageView PublishDate
--------- ------------------------- ----------- -------------------
1 SQL JOIN Example 43 2008-06-04 15:18:00
3 SQL Where Example 0 2008-06-07 15:27:00
4 SQL: Find Duplicate Values 102 2008-05-29 15:30:00

Using SQL Outer Join

When you use SQL JOIN/INNER JOIN, the result are rows that only matches in both table based on Join condition you specified in the FROM clause. If you need to display all rows from at least one of the tables mentioned in the FROM clause, you can use SQL OUTER JOIN statement. There are 3 types of SQL Outer Join. Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:




LEFT JOIN or LEFT OUTER JOIN : Left Outer Join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.


RIGHT JOIN or RIGHT OUTER JOIN : A right outer join will return All rows from the right table and Null values are returned when there are no matching row in the left table.



FULL JOIN or FULL OUTER JOIN : A full outer join returns all rows in both the left and right tables. Null values given for any rows that has no match in both tables.



For example you have the following tables and data in your database:




Data in the Vendors table:


VendorID VendorName
--------- ------------------------------
V0001 Microsoft Corporation
V0002 Oracle Corporation
V0003 MySQL AB
V0004 PremiumSoft CyberTech Ltd.
V0005 Mentat Technologies
V0006 FastReport Inc.
V0007 CoreLab





Data in the Products table:


ProductID VendorID Description
---------- --------- -----------------------------------------
SDB0001 V0001 MS SQL Server Database 2005
SDB0002 V0002 Oracle Database 10g Enterprise
SDB0003 V0003 MySQL 5.0 Enterprise Edition
SDBA0001 V0004 Navicat For MySQL Administration
SDBA0002 V0005 Dreamcoder 4.1 For MySQL Enterprise
SDBA0003 V0005 Dreamcoder 4.1 For MySQL Profesional
SDBA0004 V0005 Dreamcoder 4.1 For MS SQL Server Database
SDBA0005 V0008 PostgreSQL Maestro
SDBA0006 V0008 Firebird Maestro
SDBA0007 V0008 SQLite Maestro



You noticed that Vendor V0008 doesn't exist in the Poducts table and V0006, V0007 doesn't exist in the Vendors Table. This rows will not be displayed if you use a regular SQL JOIN/INNER JOIN (where Vendors.VendorID=Products.VendorID). How to display all rows from the Vendors table although it doesnt exist on the Products table or the reverse?.




Left Join or Left Outer Join Example:

The Following SQL Statement will display all rows from the Vendors table and will display only rows from the Products table that match to the Vendors table based on VendorID field.



select Vendors.VendorID,products.ProductID,products.Description

from vendors LEFT JOIN products

on vendors.vendorid=products.vendorid



Query Result:


VendorID ProductID Description
--------- ---------- -----------------------------------------
V0001 SDB0001 MS SQL Server Database 2005
V0002 SDB0002 Oracle Database 10g Enterprise
V0003 SDB0003 MySQL 5.0 Enterprise Edition
V0004 SDBA0001 Navicat For MySQL Administration
V0005 SDBA0002 Dreamcoder 4.1 For MySQL Enterprise
V0005 SDBA0003 Dreamcoder 4.1 For MySQL Profesional
V0005 SDBA0004 Dreamcoder 4.1 For MS SQL Server Database
V0006 NULL NULL
V0007 NULL NULL






Right Join or Right Outer Join Example::

The Following SQL Statement will display all rows from the Products table and display only rows from the Vendors table that match to the Products table based on VendorID field.




select Vendors.VendorID,products.ProductID,products.Description

from vendors RIGHT JOIN products

on vendors.vendorid=products.vendorid



Query Result:


VendorID ProductID Description
--------- ---------- -----------------------------------------
V0001 SDB0001 MS SQL Server Database 2005
V0002 SDB0002 Oracle Database 10g Enterprise
V0003 SDB0003 MySQL 5.0 Enterprise Edition
V0004 SDBA0001 Navicat For MySQL Administration
V0005 SDBA0002 Dreamcoder 4.1 For MySQL Enterprise
V0005 SDBA0003 Dreamcoder 4.1 For MySQL Profesional
V0005 SDBA0004 Dreamcoder 4.1 For MS SQL Server Database
NULL SDBA0005 PostgreSQL Maestro
NULL SDBA0006 Firebird Maestro
NULL SDBA0007 SQLite Maestro




Full Join or Full Outer Join Example::

The Following SQL Statement will display all rows from both Vendors and Products table.




select Vendors.VendorID,products.ProductID,products.Description

from vendors FULL JOIN products

on vendors.vendorid=products.vendorid



Query Result:


VendorID ProductID Description
--------- ---------- -----------------------------------------
V0001 SDB0001 MS SQL Server Database 2005
V0002 SDB0002 Oracle Database 10g Enterprise
V0003 SDB0003 MySQL 5.0 Enterprise Edition
V0004 SDBA0001 Navicat For MySQL Administration
V0005 SDBA0002 Dreamcoder 4.1 For MySQL Enterprise
V0005 SDBA0003 Dreamcoder 4.1 For MySQL Profesional
V0005 SDBA0004 Dreamcoder 4.1 For MS SQL Server Database
NULL SDBA0005 PostgreSQL Maestro
NULL SDBA0006 Firebird Maestro
NULL SDBA0007 SQLite Maestro

SQL JOIN : Retrieving Data from many Tables

Joins are created when we display Data in queries that using more than one tables. we can connect a row in one table to another row in other table using the same value of both rows. Usualy this relation represented as Primary Key and Foreign Key relationship.


Joins allow an association between a field in one table or view with a field of the same data type in another table or view. Joins show how the data in one table relates to the data in another table. By using joins, data from two or more tables or queries based on logical relationships among the tables can be retrieved. Joins can be added, edited, or deleted to retrieve the data from the database.


For Example you have two tables called Products and Vendors that contain the following Data:



Data in table Vendors:


VendorID VendorName URL
--------- --------------------------- --------------------------
V0001 Microsoft Corporation http://www.microsoft.com
V0002 Oracle Corporation http://www.oracle.com
V0003 MySQL AB http://www.mysql.com
V0004 PremiumSoft CyberTech Ltd. http://www.navicat.com
V0005 Mentat Technologies http://www.mentattech.com



Data in table Products:


ProductID VendorID Description
---------- --------- -----------------------------------------
SDB0001 V0001 MS SQL Server Database 2005
SDB0002 V0002 Oracle Database 10g Enterprise
SDB0003 V0003 MySQL 5.0 Enterprise Edition
SDBA0001 V0004 Navicat For MySQL Administration
SDBA0002 V0005 Dreamcoder 4.1 For MySQL Enterprise
SDBA0003 V0005 Dreamcoder 4.1 For MySQL Profesional
SDBA0004 V0005 Dreamcoder 4.1 For MS SQL Server Database



Bellow is SQL JOIN Statement example to display ProductID, VendorName, and Description by Joining two tables above




select products.ProductID,vendors.VendorName,products.Description

from vendors, products

where vendors.vendorid=products.vendorid



Query Result:


ProductID VendorName Description
---------- -------------------------- -----------------------------------------
SDB0001 Microsoft Corporation MS SQL Server Database 2005
SDB0002 Oracle Corporation Oracle Database 10g Enterprise
SDB0003 MySQL AB MySQL 5.0 Enterprise Edition
SDBA0001 PremiumSoft CyberTech Ltd. Navicat For MySQL Administration
SDBA0002 Mentat Technologies Dreamcoder 4.1 For MySQL Enterprise
SDBA0003 Mentat Technologies Dreamcoder 4.1 For MySQL Profesional
SDBA0004 Mentat Technologies Dreamcoder 4.1 For MS SQL Server Database





Or you can use this form of SQL JOIN, will produce the same result



select products.ProductID,vendors.VendorName,products.Description

from vendors inner join products

on vendors.vendorid=products.vendorid



Query Result:


ProductID VendorName Description
---------- --------------------------- -----------------------------------------
SDB0001 Microsoft Corporation MS SQL Server Database 2005
SDB0002 Oracle Corporation Oracle Database 10g Enterprise
SDB0003 MySQL AB MySQL 5.0 Enterprise Edition
SDBA0001 PremiumSoft CyberTech Ltd. Navicat For MySQL Administration
SDBA0002 Mentat Technologies Dreamcoder 4.1 For MySQL Enterprise
SDBA0003 Mentat Technologies Dreamcoder 4.1 For MySQL Profesional
SDBA0004 Mentat Technologies Dreamcoder 4.1 For MS SQL Server Database

Sorting Data Using SQL Like Operator

Thursday, March 27, 2008

Operator Like digunakan dalam sebuah SQL Statement untuk mencari sebuah nilai dalam sebuah table yang mempunyai pola string atau karakter tertentu. operator Like ini ditempatkan setelah klausa where dalam sebuah SQL Statement. perbedaan antara operator Like dengan operator '=' adalah, operator '=' tidak bisa digunakan untuk mencari sebuah nilai yang tidak kita ketahui sebelumnya.



Operator Like ini biasa digunakan bersama dengan karakter '%' (Percent), '*' (Asterisk), '_' (Underscore), '?' (Quatation Marks),'#' (Number Sign),'-' (Hyphen),'[]' (Brackets) dan karakter '!' (Exclamation Point). Disini saya hanya akan membahas penggunaan Operator Like bersama dengan karakter '%', '*', '_' dan karakter '?'. Adapun fungsi dari pengunaan masing-masing karakter tersebut adalah sebagai berikut :



Karakter '*' (di Microsoft Access) atau Karakter '%' artinya adalah semua karakter. Jadi jika anda menuliskan 'SQL Like%' atau 'SQL Like*', itu berarti semua yang mengandung string SQL Like didepannya dan jika anda menuliskan '%SQL Like' berarti semua yang mengandung string 'SQL Like' di belakangnya.



Contoh penggunaan karakter % dalam statement SQL :



Select JudulBuku from Buku

Where JudulBuku like '%SQL Like%'


Contoh penggunaan karakter * dalam statement SQL untuk Microsoft Access :



Select JudulBuku from Buku

Where JudulBuku like '*SQL Like*'


SQL Statement diatas akan menghasilkan semua Data buku yang mengandung string 'SQL Like' didalam judulnya karena anda menambahkan karakter '%' atau '*' sebelum dan sesudah string 'SQL Like' setelah operator Like. Hasil Output SQL Statement Diatas bisa seperti dibawah ini :




JudulBuku

-----------------------------

Using SQL Like Operator

Penggunaan Operator SQL Like



Karakter '?' (di Microsoft Access) atau karakter '_' artinya adalah satu karakter. Sebagai contoh anda ingin menampilkan data buku yang karakter ke dua dalam judulnya adalah huruf 'S' anda bisa menuliskan Statement SQL nya sebagai berikut :


Contoh penggunaan karakter _ dalam statement SQL :



Select JudulBuku from Buku

Where JudulBuku like '_S%'


Contoh penggunaan karakter ? dalam statement SQL untuk Microsoft Access :



Select JudulBuku from Buku

Where JudulBuku like '?S*'



Perlu diperhatikan bahwa beberapa Database Software (RDBMS) seperti Oracle menerapkan aturan Case Sensitive (memperhatikan penggunaan huruf besar dan huruf kecil) terhadap nilai-nilai yang ada didalam table-nya jadi jika anda menyimpan data didalam table dengan nilai 'USING SQL LIKE OPERATOR' maka ketika mencarinya dengan menggunakan pola '%SQL Like%' dalam operator SQL Like maka query tidak akan menghasilkan kembalian judul buku seperti 'USING SQL LIKE OPERATOR
', 'PENGGUNAAN OPERATOR SQL LIKE' dan sebagainya, karena data disimpan dalam huruf kapital sedangkan string pencarian anda adalah huruf besar dan huruf kecil ('SQL Like'). Mudah-mudahan artikel ini bisa menambah wawasan anda tentang Syntax dasar statement SQL.

SQL: Summed Up Null Values in Oracle and SQL Server 2000

Sunday, March 16, 2008


Jika anda sering menggunakan SQL statement pasti anda pernah melakukan operasi perhitungan matematika terhadap field-field dalam table anda. tapi pernahkah anda bingung mendapatkan perhitungan yang tidak sesuai terhadap field yang bernilai NOT NULL dengan field yang bernilai NULL. misalnya field A bernilai 4 dan field B bernilai NULL, jika anda lakukan penjulahan dengan SUM(fieldA+fieldB) maka hasilnya akan NULL. untuk itu anda perlu menggunakan sebuah fungsi untuk menggantikan nilai NULL tadi dengan sebuah bilangan/angka agar bisa dilakukan operasi matematika terhadap field yang bernilai null tadi.




untuk tutorial ini saya menggunakan table di database Oracle dengan nama EMP yang ada di schema SCOTT dan saya transfer table ini ke database SQL Server jadi saya menggunakan table yang mempunyai data yang sama. meskipun begitu saya juga akan memberikan contoh untuk anda yang menggunakan Microsoft SQL Server 2000 sebagai Database Software anda. jika anda belum tahu struktur dari table EMP, ini dia strukturnya :



EMPNO NUMBER(4) NOT NULL,

ENAME VARCHAR2(10),

JOB VARCHAR2(9),

MGR NUMBER(4),

HIREDATE DATE,

SAL NUMBER(7,2),

COMM NUMBER(7,2),

DEPTNO NUMBER(2)



dan ini datanya :





Saya akan menghitung Salary + Commision masing-masing pegawai dengan SQL Statement berikut ini :




SELECT EMPNO, ENAME, JOB,

SAL, COMM, SUM(SAL+COMM) TOTAL_SALARY

FROM EMP

GROUP BY EMPNO, ENAME, JOB,

SAL, COMM




SQL Output :



Oracle without NVL

Maka salary pegawai yang tidak mempunyai komisi (komisi = NULL) tidak akan terhitung. untuk itu anda perlu menggunakan fungsi NVL() di Oracle atau fungsi ISNULL() jika anda menggunakan Database Software Microsoft SQL Server.



Syntax fungsi NVL() di Oracle :

NVL(input_value,replace_value_if_null)

Syntax fungsi ISNULL() di SQL Server 2000 :
ISNULL (input_value , replace_value_if_null)




fungsi NVL() atau fungsi ISNULL() akan menggantikan nilai NULL dengan nilai lainnya yang kita definiskan pada parameter kedua (replace_value_if_null) dengan catatan input_value dan replace_value_if_null mempunyai tipe data yang sama. anda akan mendapatkan pesan error jika anda menggunakan tipe data yang berbeda untuk dua parameter tersebut. sekarang saya akan merubah SQL Statement nya dengan menyertakan fungsi NVL() dan fungsi ISNULL() :




Dengan Fungsi NVL () :


SELECT EMPNO, ENAME, JOB, SAL, COMM,

SUM(nvl(SAL,0)+nvl(COMM,0)) TOTAL_SALARY

FROM EMP

GROUP BY EMPNO, ENAME, JOB, SAL, COMM





SQL Output :



Oracle with NVL

Dengan Fungsi ISNULL () :


SELECT EMPNO, ENAME, JOB, SAL, COMM,

SUM(ISNULL(SAL,0)+ISNULL(COMM,0)) TOTAL_SALARY

FROM EMP

GROUP BY EMPNO, ENAME, JOB, SAL, COMM





SQL Output :


SQL Server With ISNULL


dengan SQL Statement diatas maka pegawai yang tidak mempunyai komisi pun dapat terhitung salary-nya. Semoga bermanfaat.

Oracle SQL: Encrypt Strings using TRANSLATE Function


Scroll To Indonesia Version



If you are using Oracle as your Database Software to manage your datas, did you know that Oracle have a function to do simple string encryption. Although it was simple but the result is prety powerfull to encrypt any input string. in fact it can be used to encrypt any number data types. below i will give you an example how to encrypt a password that have a string data type and stored in a table called LOGIN that contain users login records to login to the application that you made for example. this table have the following structure :



USERID NUMBER,

USERNAME VARCHAR2(30),

PASSWORD VARCHAR2(30),

PROFILE VARCHAR2(15)



Syntax :
TRANSLATE(input_string,pattern_string1,pattern_string2)




Using TRANSLATE Function in SQL Insert Statement


for example you have 'Database Administrator' as your application login password. you can change the SQL statement for validate, inserting, or updating users login data in your application source code or you can add this SQL Statement to your application source code to encrypt the password before you store it on your application login table. this is how to use TRANSLATE function in the SQL Insert Statement :





INSERT INTO login

VALUES(

111,'ADMINISTRATOR',

TRANSLATE(

'Database Administrator',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*'),'DBA')



Each character in string 'Database Administrator' will be looked in pattern_string1
then this function will look for character in pattern_string2 which it's position is equal to the character in pattern_string1. in the example of SQL Statement above, character 'D' in string 'Database Administrator' have 14th position at pattern_string1 so the function will look for the character that have the 14th position at pattern_string2 so the result is character '|', and so on.



Using TRANSLATE Function in SQL Select Statement


This is used to retrieving data from LOGIN table. in this example is for checking user login data.





SELECT * FROM login

WHERE username='ADMINISTRATOR'

AND PASSWORD = TRANSLATE(

'Database Administrator',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*')



SQL Output :




you must use the same pattern_string as you use in SQL insert statement before.



Using TRANSLATE Function in SQL Update Statement


You may want to update your login password, for that purpose you need to update the record using SQL update statement. this is how to use TRANSLATE function in the SQL Update Statement :




UPDATE login SET password=TRANSLATE(

'oracle dba',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*')

WHERE userid=111



Result :





this way anyone who accidentally see your login table will never know what your really password is. there is no harm to be wary. i hope this article will be usefull.













Scroll To English Version


Oracle SQL: Enkripsi Strings menggunakan Fungsi TRANSLATE


Jika anda menggunakan Oracle sebagai Database Software untuk me-manage data-data anda, tahukah anda bahwa oracle mempunyai sebuah function untuk melakukan enkripsi string sederhana. meskipun begitu function ini cukup powerfull dalam meng-encrypt sebuah inputan string bahkan bisa juga digunakan untuk meng-encrypt inputan yang mempunyai tipe data number. dibawah ini adalah contoh sederhana untuk meng-encrypt password bertipe string yang akan disimpan di dalam sebuah table bernama LOGIN yang berisi data login user ke aplikasi. misalnya table ini mempunyai struktur sebagai berikut :




USERID NUMBER,

USERNAME VARCHAR2(30),

PASSWORD VARCHAR2(30),

PROFILE VARCHAR2(15)



Syntax :
TRANSLATE(input_string,pattern_string1,pattern_string2)



Using TRANSLATE Function in SQL Insert Statement


Misalnya password anda adalah 'Database Administrator'. anda bisa merubah atau menambahkan SQL Statement berikut ke source code aplikasi anda untuk melakukan validasi login user, insert user baru, atau update password user lama. berikut ini contoh penggunaan fungsi TRANSLATE di dalam SQL Insert Statement :




INSERT INTO login

VALUES(

111,'ADMINISTRATOR',

TRANSLATE(

'Database Administrator',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*'),'DBA')



setiap karakter dalam string 'Database Administrator' akan dicari pada pattern_string1 kemudian fungsi ini akan mencari karakter pada pattern_string2 yang posisi/letak karakternya sama dengan karakter pada pattern_string1. pada contoh SQL Statement diatas karakter 'D' pada string 'Database Administrator' mempunyai urutan/posisi ke-14 pada pattern_string1 kemudian fungsi akan mencari karakter yang mempunyai posisi ke-14 pada pattern_string2 sehingga hasilnya adalah karakter '|', dan seterusnya.



Using TRANSLATE Function in SQL Select Statement


sql statement ini digunakan untuk mendapatkan data dari table LOGIN. dalam contoh ini adalah untuk memeriksa data login user.




SELECT * FROM login

WHERE username='ADMINISTRATOR'

AND PASSWORD = TRANSLATE(

'Database Administrator',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*')



SQL Output :





pattern_string harus sama dengan pattern_string yang anda gunakan ketika anda melakukan insert data dengan SQL Insert.



Using TRANSLATE Function in SQL Update Statement


Misalnya anda akan merubah password login anda, untuk itu dibutuhkan SQL Update Statement. berikut ini contoh penggunaan fungsi TRANSLATE di dalam SQL Update Statement :




UPDATE login SET password=TRANSLATE(

'oracle dba',

'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321 zxcvbnmlkjhgfdsaqwertyuiop',

'~!@#$%^&*()_+|+_)(*&^*%#@!%%*&&)(*&!%#@$#_ )@*$^@%@$#!@#!@#_)(*')

WHERE userid=111


Result :




Dengan cara melakukan enkripsi seperti ini, orang lain yang secara tidak sengaja melihat table login anda, dia tidak akan tahu password anda sebenarnya. tidak ada salahnya lho untuk tetap berhati-hati. semoga artikel saya ini bermanfaat.

Delphi: Data Manipulation Using SQL Statement

Tuesday, March 11, 2008

Scroll to English Version


Manipulasi Data Menggunakan SQL Statement di Delphi


Aku menggunakan sebuah table di Microsoft Access dengan nama poducts pada database tutorial.mdb dan disimpan di C:\DelphiTutorial\sqldml. tutorial ini menjelaskan bagaimana cara melakukan manipulasi data menggunakan sql statement dengan komponen ADOCommand di delphi 7. hal ini mencakup statement sql select,sql insert, sql update dan sql delete. berikut ini struktur dari table products :




productid
text(10),
description text(50),
price number(long integer)




  • Masuk ke Delphi 7.
  • Buat sebuah project baru, simpan di C:\DelphiTutorial\sqldml dengan nama
    sqldml.dpr.
  • tambahkan sebuah komponen ADOConnection (ada di tab ADO) set property
    ConnectionStringnya menjadi :




Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=tutorial.mdb;Persist Security Info=False





  • tambahkan sebuah komponen ADOCommand (ada di tab ADO) set property Connectionnya menjadi ADOConnection1.



SQL Insert statement



Pertama-tama saya akan mengisi table products dengan beberapa record agar perubahan data didalam table karena manipulasi data dapat terlihat.




  • tambahkan tiga buah komponen Edit masing-masing beri nama eproductid, edescription, dan eprice dan sebuah komponen Button biarkan komponen button dengan nama defaultnya.

  • set property Caption Button1 menjadi 'Save'.

  • dobel klik button1, kemudian tambahkan kode perintah berikut pada code editor delphi :






with ADOCommand1 do begin

CommandText := 'insert into products values(:a,:b,:c)';

Parameters[0].Value := eproductid.Text;

Parameters[1].Value := edescription.Text;

Parameters[2].Value := eprice.Text;

Execute;

end;


application.messagebox('Data berhasil disimpan','Informasi',mb_ok);




  • run applikasi dengan menekan F9, kemudian isikan beberapa record ke dalam table.




SQL Select Statement


Sebenarnya fungsi utama ADOCommand ini adalah untuk mengeksekusi statement sql yang tidak mengembalikan hasil (result sets) seperti statement SQL insert,SQL update, SQL delete dan statement DDL (Data Definition language) misalnya statement Create Table, Create Procedure, dll. sedangkan contoh statement sql yang mengembalikan hasil (result sets) adalah statement sql select.



kita akan melakukan pencarian record pada table products berdasarkan field description. Untuk menerima hasil kembalian (result sets) dari statement sql ini kita akan menggunakan komponen ADODataSet.




  • tambahkan sebuah komponen edit, beri nama esearch dan sebuah komponen button dan beri nama bsearch.

  • Ubah property caption dari button bsearch menjadi 'Search'.

  • dobel klik tombol bsearch, kemudian tambahkan kode perintah berikut pada code editor delphi :





with ADOCommand1 do begin

CommandText := 'select * from products where description = :desc';

Parameters[0].Value := ecari.Text;

ADODataset1.Recordset := execute;

end;

MessageDlg('Ditemukan '+ inttostr(ADODataset1.recordcount) + ' Record(s)', mtInformation, [mbOk], 0);



Coba lakukan pencarian data barang yang telah dientri sebelumnya dengan cara menginputkan deskripsi barang tersebut pada kotak edit esearch dan tekan tombol Search.



SQL Update Statement


Idenya begini : saya akan menambahkan fitur pencarian sebelum input data dan menambahkan fitur update pada tombol button1.




  • klik edit eproductid, pada object inspector klik tab Events, cari event OnKeyDown, dobel klik, kemudian tambahkan kode perintah berikut ini :






if key = vk_return then

begin

with ADOCommand1 do begin

CommandText := 'select * from products where productid = :pid';

Parameters[0].Value := eproductid.Text;

ADODataset1.Recordset := execute;

end;



if ADODataset1.RecordCount > 0 then


if messagedlg('Data produk dengan id '''+eproductid.Text

+''' sudah ada'+chr(10)

+'apakah anda akan merubah data
tersebut',mtconfirmation,[mbok,mbcancel],1) = mrok then

begin

edescription.Text :=
ADODataset1.FieldValues['description'];

eprice.Text := ADODataset1.FieldValues['price'];

edescription.SetFocus;


button1.Caption := 'Update';

{ bdelete.Enabled := true; }

end

else

begin

{ button1.Caption := 'Save'; }

eproductid.SelectAll;

exit;

end



else if ADODataset1.RecordCount < 1 then

begin

{ bdelete.Enabled := false; }

button1.Caption := 'Save';

edescription.clear;

eprice.clear;

end;



edescription.SetFocus;


end;



Pada listing kode diatas ada perintah untuk merubah caption dari tombol button1 yaitu kode perintah dengan teks yang saya tebalkan. caption tersebut akan menetukan mode manipulasi data yang akan dilakukan. biar lebih jelas ubah dulu listing kode perintah pada button1 menjadi seperti dibawah ini :





if button1.Caption='Save' then

begin

with ADOCommand1 do begin

CommandText := 'insert into products values(:a,:b,:c)';


Parameters[0].Value := eproductid.Text;

Parameters[1].Value := edescription.Text;

Parameters[2].Value := eprice.Text;

Execute;

end;

application.messagebox('Data berhasil disimpan','informasi',mb_ok);


end

else if button1.Caption='Update' then

with ADOCommand1 do begin

CommandText := 'update products set description = :a, price = :b where productid = :c';

Parameters[0].Value := edescription.Text;

Parameters[1].Value := eprice.Text;

Parameters[2].Value := eproductid.Text;


execute;

application.messagebox('Perubahan berhasil disimpan','informasi',mb_ok);

end;



eproductid.Clear;

edescription.Clear;

eprice.Clear;


eproductid.SetFocus;




run aplikasi, coba masukkan kode produk yang telah disimpan sebelumnya, maka akan ditampilkan messagebox yang berisi konfirmasi untuk update record atau tidak.



SQL Delete Statement



  • tambahkan sebuah komponen button, beri nama bdelete dan ubah Captionnya menjadi 'Delete'.


  • ubah property Enable button bdelete menjadi False

  • dobel klik tombol bdelete, kemudian tambahkan kode perintah berikut pada code editor delphi :






if messagedlg('Hapus data barang '''+eproductid.Text

+'''',mtconfirmation,[mbok,mbcancel],1) = mrok then


begin

with ADOCommand1 do begin

CommandText := 'delete from products '+

'where productid = :pid';

Parameters[0].Value := eproductid.Text;

execute;

end;

eproductid.Clear;

edescription.Clear;


eprice.Clear;

button1.Caption := 'Save';

bdelete.Enabled := false;

eproductid.SetFocus;

end;



setelah anda menginputkan kode ini pada code editor delphi, selanjutnya anda hilangkan semua tanda '{' dan '}' (blok komentar) pada listing kode program Event OnKeyDown edit eproductid agar tombol bdelete bisa aktif pada saat mode update record dan non aktif pada saat mode insert record. Semoga bermanfaat.












Scroll to Indonesian Version

I use a table in Microsoft Access called products in a file called tutorial.mdb and saved in c:\DelphiTutorial\sqldml. this tutorial is about how to manipulate data using sql statement with ADOCommand component in Delphi 7. this is included sql select statement, sql insert statement, sql update statement and sql delete statement. lets get started.



the following is data structure from products table :




productid
text(10),
description text(50),
price number(long integer)




  • Run Delphi.
  • Create new project then save as sqldmp.dpr in c:\DelphiTutorial\sqldml.
  • Add an ADOConnection component, set its ConnectionString Property to :






Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=tutorial.mdb;Persist Security Info=False





  • Add an ADOCommand component, set its Connection property to ADOConnection1.


SQL Insert statement



First of all i will fill the table with some data so we can see the changes that sql statement do to the table's data.




  • Add three Edit component eproductid, edescription, and eprice and a Button component, Button1.


  • Change Button1 Caption property to 'Save'.

  • double klick Button1, then add the following code to the Delphi's code editor :





with ADOCommand1 do begin

CommandText := 'insert into products values(:a,:b,:c)';

Parameters[0].Value := eproductid.Text;

Parameters[1].Value := edescription.Text;

Parameters[2].Value := eprice.Text;


Execute;

end;

application.messagebox('Data saved successfully','Information',mb_ok);



  • Run application, fill the table with some data by pressing Button1.



SQL Select Statement


Actually the main purpose of ADOCommand component is to execute sql statements that don't return a result sets including SQL Insert statement, SQL Update statement, SQL delete statement and DDL statement (Data Definition Language) like Create Table, Create Procedure, etc.



To retrieve data using sql select statement i use an ADODataSet component along with ADOCommand component.




  • Add an Edit Component, esearch and a Button component, bsearch.

  • Change the Caption of bsearch button to 'Search'.

  • Double click bsearch, then add the following code to the Delphi's code editor :




with ADOCommand1 do begin

CommandText := 'select * from products where description = :desc';

Parameters[0].Value := ecari.Text;

ADODataset1.Recordset := execute;

end;

MessageDlg('Found '+ inttostr(ADODataset1.recordcount) + ' Record(s)', mtInformation, [mbOk], 0);



After writing the code above, run application then try searching specific record in the Products table by entering product description in the Edit text box esearch then press 'Search' button.




SQL Update Statement


the idea is : i will add searching record feature before entering the data and add updating feature on button1(Save button) button.




  • klick eproductid, in the object inspector klick Events tab, look for OnKeyDown event, double klick, then add the following code :





if key = vk_return then

begin

with ADOCommand1 do begin

CommandText := 'select * from products where productid = :pid';

Parameters[0].Value := eproductid.Text;

ADODataset1.Recordset := execute;

end;



if ADODataset1.RecordCount > 0 then

if messagedlg('Product with id '''+eproductid.Text

+''' already exist'+chr(10)

+'do you want to change the data
',mtconfirmation,[mbok,mbcancel],1) = mrok then

begin

edescription.Text :=
ADODataset1.FieldValues['description'];


eprice.Text := ADODataset1.FieldValues['price'];

edescription.SetFocus;

button1.Caption := 'Update';

{ bdelete.Enabled := true; }

end

else

begin

{ button1.Caption := 'Save'; }

eproductid.SelectAll;


exit;

end


else if ADODataset1.RecordCount < 1 then

begin

{ bdelete.Enabled := false; }

button1.Caption := 'Save';

edescription.clear;

eprice.clear;


end;



edescription.SetFocus;

end;



in the code listing above there are a command (the bold one) to change the caption of button1. that caption will determine manipulation mode to the data that will be perform. for more clearly, change the code listing in the button1 as follow :





if button1.Caption='Save' then

begin


with ADOCommand1 do begin

CommandText := 'insert into products values(:a,:b,:c)';

Parameters[0].Value := eproductid.Text;

Parameters[1].Value := edescription.Text;

Parameters[2].Value := eprice.Text;

Execute;


end;

application.messagebox('Data saved successfully','informasi',mb_ok);

end

else if button1.Caption='Update' then

with ADOCommand1 do begin

CommandText := 'update products set description = :a, price = :b where productid = :c';

Parameters[0].Value := edescription.Text;


Parameters[1].Value := eprice.Text;

Parameters[2].Value := eproductid.Text;

execute;

application.messagebox('Changes saved successfully','informasi',mb_ok);

end;



eproductid.Clear;


edescription.Clear;

eprice.Clear;

eproductid.SetFocus;




run application, try to input product id that have entered earlier, then a message box will appear displaying confirmation to update the record or no.



SQL Delete Statement




  • Add a button, bdelete and change the Caption to 'Delete'.

  • change Enable to False

  • double klick bdelete button, then add the following code to the Delphi's code editor :






if messagedlg('Delete products '''+eproductid.Text

+''' data',mtconfirmation,[mbok,mbcancel],1) = mrok then

begin

with ADOCommand1 do begin

CommandText := 'delete from products '+

'where productid = :pid';

Parameters[0].Value := eproductid.Text;

execute;


end;

eproductid.Clear;

edescription.Clear;

eprice.Clear;

button1.Caption := 'Save';

bdelete.Enabled := false;

eproductid.SetFocus;

end;



After writing that code above in delphi's code editor, next, remove
the '{' and '}' sign (comment block)
in OnKeyDown event eproductid code listing in order to activate bdelete button on update record mode and deactivate it on insert record mode.


SQL : Using Column Alias to Clarify Field Header

Friday, March 7, 2008

Scroll to English Version


SQL: Menggunakan Column Alias untuk memperjelas Field Header


Jika table anda mempunyai field yang kurang deskripstip anda mungkin akan
mempertimbangkan untuk menggunakan tips yang akan saya berikan ini. sebenarnya tips ini untuk anda yang sering atau terbiasa menggunakan sql editor/ atau DBA (Database Administration) Tools untuk melakukan query data. Misalnya anda mempunyai sebuah table bernama Persons dengan struktur sebagai berikut (saya gunakan struktur di Oracle) :




FNAME VARCHAR2(15),

LNAME VARCHAR2(15),

GENDER CHAR(1),

BIRTHDATE DATE



dan table tersebut mempunyai data sebagai berikut :




FNAME LNAME GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73


coba anda gunakan SQL statement dibawah ini :





select fname,lname,gender,birthdate from persons



maka hasilnya adalah :




SQL> select fname,lname,gender,birthdate from persons;

FNAME LNAME GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73

disitu terlihat bahwa kolom FNAME dan LNAME kurang deskriptip. agar lebih jelas dalam output query anda bisa menggunakan column alias. berikut ini contoh syntax statement sql di beberapa database SQL.



SQL statement in Oracle, MySQL, Paradox




select fname "First Name", lname "Last Name",gender,birthdate

from persons



output query-nya :





SQL> select fname "First Name",
2 lname "Last Name", gender, birthdate
3 from persons;

First Name Last Name GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73




SQL statement in Microsoft Access and Microsoft SQL Server




select fname as [First Name], lname as [Last Name],gender,birthdate

from persons



Maka output query-nya akan sama dengan output sql yang saya gunakan di oracle, MySQL dan Paradox sebelumnya.













Scroll to Indonesian Version

If you have tables that the field are less descriptive, you may want to consider this tips that i will explain below. actually this tips is for you who often use sql editor or DBA (Database Administration) Tools to do queries. for example you have a table called Persons with the following structure (i use a structure in oracle database) :





FNAME VARCHAR2(15),

LNAME VARCHAR2(15),

GENDER CHAR(1),

BIRTHDATE DATE



and this table have the following data :



FNAME LNAME GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73


try use this SQL Statement below :




select fname,lname,gender,birthdate from persons



The SQL statement result output are :



SQL> select fname,lname,
2 gender,birthdate from persons;

FNAME LNAME GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73


in the sql statement result output above we can see that FNAME and LNAME column are less descriptive. for more clearly column header in the query output you can use a column aliases. the following is an example of sql statement syntax for using column aliases in several sql database engine.



SQL statement in Oracle, MySQL, Paradox




select fname "First Name", lname "Last Name",

gender,birthdate from persons



The SQL statement result output :





SQL> select fname "First Name",

2 lname "Last Name", gender, birthdate
3 from persons;

First Name Last Name GENDER BIRTHDATE
--------------- --------------- ---------- ---------
KURT COBAIN M 20-FEB-67
IGOR CAVALERA M 04-SEP-70
AMY LEE F 13-DEC-81
COREY TAYLOR M 18-DEC-73



SQL statement syntax in Microsoft Access and Microsoft SQL Server




select fname as [First Name], lname as [Last Name],gender,birthdate

from persons



sql statement above will bring the same result output as sql statement that we use in Oracle, MySQL and paradox previously.

Menampilkan Record Duplikat dengan SQL

Sunday, February 10, 2008

scroll to Indonesian Version


Search for duplicate records sometimes we needed in work in an IT area. Although duplication is impossible to happen at the tables that have good referential integrity and constraint, but in our IT reality sometimes we make our table contain duplicated records.



the SQL Syntax to search for duplicate record in MySQL, Microsoft Access, Oracle, SQL Server and others much the same to or is same precisely because SQL syntax i will mention under this is a standard SQL statement syntax.



For example i use a table named Employees in MySQL database and the table have the following structure : employee_id varchar (10), name varchar (30), and the table have the following data :
































employee_id name
8105048BR Yana
8205049BR Yana
8015052BR Denny
8005043BR Denny
8105047BR Adi F
8005050BR Sody S


At the example above we notice that there are four employees having the same name. To display the duplicated name using SQL statement in MySQL, Microsoft Access, Oracle, SQL Server and others, the SQL statement is as follows :





select name, count(*) from employees

group by name

having count(*) > 1




the SQL statement above will display the list of Name that having count greater than one record. In this example is Yana and Denny. below are the output from the SQL statement above :
















name count(*)
Denny 2
Yana 2







scroll to English Version


Mencari record duplikat terkadang kita butuhkan dalam pekerjaan di bidang IT. Walaupun duplikasi tidak mungkin terjadi pada tabel yang mempunyai referential integrity dan constraint yang baik, namun dalam kenyataannya kita sering membuat tabel yang berisi data-data duplikat.



Syntax SQL untuk mencari record duplikat di MySQL, Microsoft Access, Oracle, SQL Server dan lain-lain hampir sama atau sama persis karena syntax SQL yang akan saya sebutkan dibawah ini adalah syntax statement SQL standar.



Sebagai contoh saya menggunakan sebuah tabel bernama Karyawan di MySQL strukturnya sebagai berikut : nik varchar(10), nama varchar(30), dan mempunyai data-data sebagai berikut di :
































nik nama
8105048BR Yana
8205049BR Yana
8015052BR Denny
8005043BR Denny
8105047BR Adi F
8005050BR Sody S



Pada contoh diatas terdapat empat record yang mempunyai nama yang sama. Untuk menampilkan row duplikat tersebut dengan SQL di MySQL, Microsoft Access, Oracle, SQL Server dan lain-lain, statement SQL-nya sebagai berikut :



select nama, count(*) from karyawan

group by nama

having count(*) > 1




Statement SQL diatas akan menampilkan daftar Nama yang jumlahnya lebih dari satu, dalam contoh ini adalah Yana dan Denny. dibawah ini adalah output dari statement SQL diatas :
















nama count(*)
Denny 2
Yana 2

Belajar Syntax Dasar Statement SQL

Setelah melihat-lihat ke beberapa forum Programming, banyak thread yang menanyakan tentang syntax statement SQL dasar.
Untuk itu saya mencoba menulis tutorial singkat ini mudah-mudahan temen-temen sesama penghobi programming bisa mendapat tambahan pengetahuan di SQL programming.



Semua statement SQL ini bisa berfungsi di semua DBMS/RDBMS karena ini adalah syntax statement SQL standar.
Untuk tutorial ini saya menggunakan sebuah table di Microsoft Access dan MySQL dengan nama Tbarang dan struktur datanya sebagai berikut :



Struktur table Tbarang di Microsoft Access :

kodeitem text(10), deskripsi text(50), harga number(10), kategori text(6), diskon number(2), statusjual text(1)




Struktur table Tbarang di MySQL :

kodeitem varchar(10), deskripsi varchar(50), harga integer(10), kategori varchar(6), diskon int(2), statusjual char(1)



dan datanya sebagai berikut :












































































kodeitem deskripsi harga kategori Diskon StatusJual
EBVB2001 Visual Basic 6 Black Book 735000 SWEB 0 Y
EBBD1001 Mastering Delphi 7 E-Book 850000 SWEB 0 Y
SW2001 Microsoft Visual Basic.Net 2006 3200000 SW 0 Y
SW1001 Borland Delphi 7 Enterprise Edition 3000000 SW 0 Y
SW5001 Dreamcoder for MySQL Administration Enterprise 2100000 DBA 0 Y
SW6002 FastReport Studio 3.23 Enterprise Edition 3200000 UTL 0 Y
SW1002 Borland Delphi 2006 Enterprise Edition 3600000 SW 0 Y
SW2002 Microsoft Office 2007 3200000 SW 0 Y



Select Statement



Statement Select digunakan untuk menampilkan data dari satu atau beberapa tabel.



Contoh syntax SQL untuk menampilkan seluruh data yang ada di table barang :





select * from Tbarang



Contoh syntax SQL untuk menampilkan seluruh data yang mempunyai kategori SWEB (Software E-Book) :





select * from Tbarang
where kategori = 'SWEB'



Contoh syntax SQL untuk menampilkan deskripsi dan harga barang dengan kategori SW (Software).





select deskripsi,harga from Tbarang
where kategori = 'SW'



Contoh syntax SQL untuk menampilkan Deskripsi dan Harga dengan Kategori SW (Software) dan mempunyai Harga lebih dari tiga juta.





select deskripsi,harga from Tbarang
where kategori = 'SW' and harga > 3000000



Insert Statement



Statement Insert digunakan untuk Menambah data kedalam sebuah tabel.


Contoh syntax SQL untuk menambah data kedalam table Tbarang dengan menyebutkan nama field.
Jumlah nilai (values) harus sesuai dengan jumlah dan tipe data dari urutan nama field yang disebutkan.






insert into tbarang (kodeitem, deskripsi, harga, kategori, diskon, statusjual)
values('SW3001','PHP Designer 2008',2000000,'UTL',0,'Y')


Contoh syntax SQL untuk menambah data kedalam table Tbarang tanpa menyebutkan nama field :





insert into tbarang
values('SW1003','Borland Delphi 6 Enterprise Edition',2800000,'SW',0,'Y')



Contoh syntax SQL untuk menambah data kedalam field kodeitem dan deskripsi di table Tbarang :





insert into tbarang (kodeitem, deskripsi)
values('SW2003','Microsoft Visual Studio.Net 2006')



Data dari table Tbarang setelah statement Insert :



































































































kodeitem deskripsi harga kategori Diskon StatusJual
EBVB2001 Visual Basic 6 Black Book 735000 SWEB 0 Y
EBBD1001 Mastering Delphi 7 E-Book 850000 SWEB 0 Y
SW2001 Microsoft Visual Basic.Net 2006 3200000 SW 0 Y
SW1001 Borland Delphi 7 Enterprise Edition 3000000 SW 0 Y
SW5001 Dreamcoder for MySQL Administration Enterprise 2100000 DBA 0 Y
SW6002 FastReport Studio 3.23 Enterprise Edition 3200000 UTL 0 Y
SW1002 Borland Delphi 2006 Enterprise Edition 3600000 SW 0 Y
SW2002 Microsoft Office 2007 3200000 SW 0 Y
SW2003 Microsoft Visual Studio.Net 2006        
SW3001 PHP Designer 2008 2000000 UTL 0 Y
SW1003 Borland Delphi 6 Enterprise Edition 2800000 SW 0 Y


Update Statement


Statement Update digunakan untuk merubah nilai satu atau beberapa field dari sebuah table.



Contoh syntax SQL untuk merubah seluruh diskon dari table Tbarang (update seluruh data / tanpa kondisi) :





Update tbarang set diskon=5



Contoh syntax SQL untuk merubah nilai diskon barang yang mempunyai harga lebih dari tiga juta (update satu field dengan menggunakan satu kondisi) :





Update tbarang set diskon=10 where harga > 3000000



Contoh syntax SQL untuk merubah nilai diskon,dan statusjual barang yang mempunyai harga lebih dari tiga juta (update lebih dari satu field dengan menggunakan satu kondisi) :





Update tbarang set diskon=0,statusjual='T'
where harga > 3000000



Data dari table Tbarang setelah statement Update :



































































































kodeitem deskripsi harga kategori Diskon StatusJual
EBVB2001 Visual Basic 6 Black Book 735000 SWEB 5 Y
EBBD1001 Mastering Delphi 7 E-Book 850000 SWEB 5 Y
SW2001 Microsoft Visual Basic.Net 2006 3200000 SW 0 T
SW1001 Borland Delphi 7 Enterprise Edition 3000000 SW 5 Y
SW5001 Dreamcoder for MySQL Administration Enterprise 2100000 DBA 5 Y
SW6002 FastReport Studio 3.23 Enterprise Edition 3200000 UTL 0 T
SW1002 Borland Delphi 2006 Enterprise Edition 3600000 SW 0 T
SW2002 Microsoft Office 2007 3200000 SW 0 T
SW2003 Microsoft Visual Studio.Net 2006     5  
SW3001 PHP Designer 2008 2000000 UTL 5 Y
SW1003 Borland Delphi 6 Enterprise Edition 2800000 SW 5 Y


Delete Statement


Statement Delete digunakan untuk menghapus record dari sebuah table.


Contoh syntax SQL untuk Menghapus data barang yang sudah tidak dijual lagi (statusjual ='T') :





delete from tbarang where statusjual='T'



Data dari table Tbarang setelah statement Delete :




































































kodeitem deskripsi harga kategori Diskon StatusJual
EBVB2001 Visual Basic 6 Black Book 735000 SWEB 5 Y
EBBD1001 Mastering Delphi 7 E-Book 850000 SWEB 5 Y
SW1001 Borland Delphi 7 Enterprise Edition 3000000 SW 5 Y
SW5001 Dreamcoder for MySQL Administration Enterprise 2100000 DBA 5 Y
SW3001 PHP Designer 2008 2000000 UTL 5 Y
SW1003 Borland Delphi 6 Enterprise Edition 2800000 SW 5 Y
SW2003 Microsoft Visual Studio.Net 2006     5  

SQL Dinamis Dengan Parameter Di Microsoft Access

Thursday, February 7, 2008


Jika anda sering menggunakan SQL di Microsoft Access anda mungkin pernah merasa malas, capek (dsb..)
untuk masuk ke menu Query Design untuk merubah statement SQL objek Query anda.




Misalkan anda ingin menampilkan data barang-barang dari vendor tertentu di tabel Barang
berdasarkan kode vendor yang anda cantumkan setelah klausa where di dalam
statement SQL anda. Misalnya statement SQL anda seperti ini :





Select * from barang where vendor_id='V0001'




Anda bisa menampilkan data barang-barang dari vendor yang lain tanpa harus melakukan modifikasi
SQL dengan cara menggunakan parameter sebagai inputan untuk kondisi pencarian setelah klausa where.
Di bawah ini adalah contoh statement SQL dengan satu parameter yang diberi nama vid.





Select * from barang where vendor_id=:vid



Ketika Query tersebut dijalankan Microsoft Acess akan menampilkan kotak dialog Parameter, anda hanya
perlu menginputkan kode vendor pada kotak dialog tersebut.



ParameterDiaolog.jpg

Recent Comments

Tags Cloud

Blogumulus by Roy Tanck and Amanda Fazani