Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

4

C H A P T E R

SQL Statement
Primer









In This Cha pter

I

n this c hapter, I’m go ing to sho w yo u so me o f the key SQL
statements that yo u will be using when yo u develo p yo ur

applic atio ns. These statements will allo w yo u to c reate tables,
views, and indexes. The rest o f the statements c an be used to
add, remo ve, c hange, and retrieve ro ws fro m yo ur database.

The Select statement
The Insert statement
The Delete statement
The Update statement

Using SQL Statements
A detailed kno wledge o f SQL isn’t nec essary fo r mo st pro grammers. Ho wever, it will be impo ssible to write a database
pro gram witho ut kno wing a little bit abo ut the language. The
statements I’m go ing to c o ver in this c hapter apply to all o f
the database systems that will be disc ussed in this bo o k.
Note

SQL for Dummies: If you really w ant to learn m ore about
the SQL language, read the book SQL for Dum m ies, 3 rd
Edition, by Allen G. Taylor. This is a good introduction to the
SQL language and covers all of the essential elem ents of

the language. More advanced users should refer to the
database vendor’s docum entation for their extensions to
the SQL language.

SQL statements
The SQL language c o nsists o f a series o f statements that perfo rm spec ific tasks (see Table 4-1). There are statements to
c reate databases and tables, statements to add and delete
ro ws in a table, and statements to retrieve ro ws fro m a table o r
set o f tables. There are o ther statements that deal with data
sec urity and data integrity. These statements are c o nstruc ted
ac c o rding to a set o f c o mplex rules that vary slightly fro m o ne
database system to ano ther. Ho wever, fo r mo st users, these
differenc es aren’t all that impo rtant.

The Create Table
statement
The Create Index
statement
The Create View
statement










50

Part I ✦ Database Programming Fundamentals

Table 4-1
Some Common SQL Statements
Statement Name

Description

Create Index


Builds an index on a set of colum ns on a table.

Create Table

Builds an em pty table in a database.

Create View

Builds a view.

Delete

Rem oves row s from a table.

Drop Index

Deletes an index from a database.

Drop Table


Deletes a table from a database.

Drop View

Rem oves a view from a database.

Insert

Adds row s to a table.

Select

Retrieves row s from a table.

Update

Changes the data values of one or m ore colum ns in the table.

Data definition language statements

The Create Table , Drop Table, Create View , Drop View Create Index , and Drop
Index statements are kno wn as Data De finitio n Language (DDL) statements, while
the Insert, Delete , Update , and Select statements are kno wn as Data Manipulatio n
Language (DML) statements. In mo st database systems to day, yo u rarely exec ute
DDL statements when yo u want to c reate a database struc ture. Instead, yo u use a
utility supplied with the database system that allo ws yo u to fill in all o f the info rmatio n into a table, o r yo u use a wizard that will help yo u c reate yo ur table o r index.

This do esn’t mean that the DDL statements aren’t used. It merely means that yo u
enter the info rmatio n in a different fashio n. The database utility usually inc ludes a
feature that will allo w yo u to generate the SQL statements fro m the definitio ns yo u
entered. Then yo u might use these SQL statements to c reate a c o py o f the database
o n ano ther c o mputer o r inc lude them in yo ur applic atio n if yo u want yo ur users to
be able to c reate the database struc tures o n the fly.

SQL data types
Eac h c o lumn in a table must have a data type asso c iated with it. The data type yo u
c ho o se fo r a c o lumn must be c o mpatible with a Visual Basic variable data type.
Table 4-2 lists so me o f the mo st c o mmo n data types used by SQL, alo ng with their
equivalent data types in Visual Basic .


Chapter 4 ✦ SQL Statement Primer

Table 4-2
Some Common SQL Data Types
SQL Data Type

Visual Basic Data Type

Description

Char

String

A fixed-length string of characters.

Date

Date


A value containing a date and tim e
value. (Available w ith Oracle only.)

Datetim e

Date

A value containing a date and tim e
value. (Available w ith SQL Server only.)

Decim al

Currency

An exact num eric value of the specified
size.

Float

Double


A 64-bit floating-point num ber.

Int

Long

A 32-bit integer.

Money

Currency

An exact num eric value. (Available w ith
SQL Server only).

Num ber

Currency


An exact num eric value. (Available w ith
Oracle only.)

Real

Single

A 32-bit floating-point num ber.

Sm allint

Integer

A 16-bit integer.

Varchar

String

Variable-length character string.


These data types c an be lo o sely gro uped into fo ur main types: exac t numeric values,
flo ating po int values, string values, and date values. Mo st database servers also o ffer
many o ther data types to c ho o se fro m.
CrossReference

For m ore detailed inform ation about the data types available in a particular
database, see Chapter 23, “Overview of SQL Server,” Chapter 26, “Overview of
Oracle 8 i,” or Chapter 29, “Overview of Microsoft Jet.”

Exact numeric data types
Exact nume ric data type s represent numbers by using an exac t value. These data
types generally fall into two sub c lasses: inte ge r value s and packe d de cimal value s.
Integer values sto re their numbers as a binary value. This o ffers mo re effic ient
sto rage fo r large numbers than when yo u use a pac ked dec imal value.
Tip

M oney, money, money: If you need to perform calculations using currency values,
you should alw ays use an exact num eric data type.

51

52

Part I ✦ Database Programming Fundamentals

Pac ked dec imal values sto re numbers as a string o f numeric digits. Fo ur bits are
used to represent a value fro m zero to nine. Mo st database servers will allo w yo u to
determine the number o f digits yo u want when yo u spec ify the data type.
The advantage o f exac t numeric values is that when yo u perfo rm arithmetic with
them, yo u never lo se ac c urac y. This isn’t true with flo ating po int values.

Floating point data types
Flo ating po int data type s represent numbers by breaking them into two piec es: a
mantissa and an e xpo ne nt. Flo ating po int numbers are expressed in terms o f a value
time 10 to so me po wer. Fo r instanc e, the value 12,345 is written as 1.234 × 105 and
o ften displayed o n the c o mputer as 1.2345E5, where E means 10 raised to this
po ser. In this example, the mantissa is 1.2345 and the expo nent is 5.

Bec ause o f the way they are sto red, flo ating po int numbers are o nly ac c urate to so
many dec imal plac es. This allo ws yo u to represent very large numbers with muc h
less sto rage than what wo uld be required if yo u sto red every single digit. Generally,
single value s have abo ut five dec imal plac es o f ac c urac y, while do uble value s are
ac c urate to abo ut ten dec imal plac es.
Tip

M aybe, maybe not: You’ll probably never need to use a floating point data type in
your database, because m ost people don’t appreciate adding 1,000,000.02 + 0.01
and getting 1,000,000 because the floating point value stored only 5 digits of
inform ation in the m antissa.

String data types
String data type s ho ld c harac ter info rmatio n. There are two different types o f c harac ter strings: fixe d-le ngth and variable -le ngth. The fixed-length strings always reserve
the same amo unt o f spac e in a table whether yo u sto re o ne c harac ter in the c o lumn
o r fifty. Variable-length strings, o n the o ther hand, sto re o nly the c harac ters yo u
have in the string, plus so me additio nal info rmatio n that ho lds the length o f the
string.

In general, yo u sho uld c ho o se variable-length strings o ver fixed-length strings. This
tends to save spac e in yo ur database, espec ially if the amo unt o f data yo u sto re in
the c o lumn varies signific antly fro m o ne ro w to the next. Using variable-length
strings also allo ws yo u to c reate yo ur strings with a larger maximum size. This is
useful in situatio ns where yo u may have an unusually large value that yo u do n’t
want to trunc ate, suc h as a perso n’s name.
Fixed-length strings are go o d when the size o f eac h value remains relatively c o nstant, as with a two -c harac ter abbreviatio n fo r a state o r a pro duc t identifier c o de.
This is espec ially true fo r small strings where the extra o verhead to keep trac k o f
the true length o f the string o c c upies mo re spac e then the string itself.

Chapter 4 ✦ SQL Statement Primer

Date data types
Date data type s are almo st always unique to a partic ular database system. Even
tho ugh there isn’t muc h c o mpatibility amo ng the database vendo rs’ implementatio ns, the alternatives are wo rse. Yo u c o uld allo c ate an eight-c harac ter string and
use the first fo ur c harac ters fo r the year, the next two fo r the mo nth, and the last
two fo r the year. Yo u c o uld also use an integer value to trac k the number o f days
sinc e 1900 o r sinc e the day yo ur o rganizatio n was c reated.

Bo th o f these metho ds have a drawbac k: the lac k o f integrated suppo rt fo r the values
by the database server. If yo u sto re yo ur date values as a c harac ter string instead o f a
date data type, when yo u use an interac tive query to o l, all yo u’ll see is the raw, unfo rmatted value. When using these values with Visual Basic , yo u’ll have to manually c o nvert yo ur values to and fro m a Date variable in o rder to take advantage o f the wide
range o f date and time func tio ns already inc luded in Visual Basic . In the lo ng run,
using the supplied date data types fro m the database server is a muc h better idea.

Testing SQL statements
One o f the advantages o f SQL is that the same language c an be used interac tively
o r embedded in yo ur applic atio n. This means that yo u c an c o de and test yo ur SQL
statements using an interac tive query to o l and then add them to yo ur pro gram.
While the query to o ls differ depending o n the database system yo u’re using, they
all do the same thing. Yo u enter yo ur statement and c lic k o n a butto n to exec ute it.
The results will then be displayed o n yo ur c o mputer.
Fo r the examples in this c hapter, I’m go ing to use the SQL Server database and the
Query Analyzer to o l to run the queries against the bo o k’s sample database. Ho wever,
o nc e yo u c reate and lo ad the sample database in yo ur database system o f c ho ic e,
yo u will be able to use the c o rrespo nding query to o l to run the same examples.

The Select statement
Of the statements in the SQL language, the Select statement is the mo st c o mmo nly
used. Its purpo se is to identify the ro ws yo u want to retrieve fro m the database.
Here is the syntax fo r this statement:

Select []
[,]...
From [, ] ...
[Where ]
[Order By [Asc|Desc]
[, [Asc|Desc] ]...

53

54

Part I ✦ Database Programming Fundamentals

where

::= All | Distinct | Top
::= * | [ [As] ]
::= | . |
( [Distinct] ) |
::= Count | Max | Min | Sum
and

is an alternate name of a column or table.
is a valid expression.
is a valid number.
The Select statement is the mo st c o mplic ated statement in SQL. The abo ve syntax
represents o nly a small part o f the full Select statement syntax. Ho wever, yo u will
rarely need anything beyo nd these c lauses when building yo ur applic atio n. A Select
statement is c o mpo sed o f a series o f c lauses, suc h as From , Where , and so o n. Only
the From c lause is required. I’m go ing to disc uss ho w the basic Selec t statement
wo rks, and then disc uss eac h o f the c lauses that wo rk with it.

Simple Select statements
To use a Select statement, all yo u need to do is identify the table and the c o lumns
yo u want to retrieve fro m the database. Immediately fo llo wing the Select keywo rd
is the list o f c o lumns yo u want to retrieve, and the From c lause spec ifies the name
o f the table yo u want to ac c ess.

Retrieving all columns
The fo llo wing statement retrieves all o f the c o lumns fro m the Custo mers table in
the sample database yo u’ll find in the CD-ROM:

Select *
From Customers
The asterisk (*) implies that yo u want to retrieve every c o lumn fro m the table.
Running this statement in Query Analyzer sho uld generate results similar to tho se
sho wn in Figure 4-1.

Retrieving a list of columns
If yo u o nly need a few spec ific c o lumns, then yo u sho uld replac e the asterisk with
the list o f c o lumn names yo u want returned, as sho wn here:

Select CustomerId, Name, Zip
From Customers
Eac h c o lumn name sho uld be separated fro m the previo us c o lumn by a c o mma (see
Figure 4-2).

Chapter 4 ✦ SQL Statement Primer

Figure 4-1: Running a sim ple query to retrieve all colum ns from the Custom er table

Figure 4-2: Running a sim ple query w ith a list of colum ns

55

56

Part I ✦ Database Programming Fundamentals

Selecting a subset of a table
Returning an entire table is no t terribly useful in an applic atio n pro gram. Typic ally,
yo u will want to retrieve o nly a single ro w o r a handful o f ro ws that are related to
so me o ther value. This is where the Where c lause c o mes into play. The Where
c lause allo ws yo u to spec ify a searc h expressio n that identifies the set o f ro ws yo u
want to return.
Note

Where oh where is my favorite clause: If the Select statem ent is the m ost com m only used statem ent in the SQL language, the Where clause is the m ost
com m only used clause. It is used in a num ber of other statem ents, including the
Delete and Update statem ents.

Using simple search expressions
The tric k to using a Where c lause is to c reate a searc h expressio n that will o nly
return the ro w o r ro ws yo u want. Fo r instanc e, let’s assume that yo u want all o f the
info rmatio n abo ut a c usto mer 431. The info rmatio n is sto red in the Custo mers
table. Thus, the searc h expressio n CustomerId = 431 wo uld retrieve all o f this
info rmatio n. Sinc e Custo merId c o lumn is the primary key fo r the Custo mers table,
o nly a single ro w will be returned by the fo llo wing Select statement (see Figure 4-3):

Select *
From Customers
Where CustomerId = 431
Note

Searching for expressions with all the wrong operators: SQL supports all of the
sam e operators that Visual Basic includes (= , < , > , < = , > = , < > , Not , And, and Or)
to m ake it easy to build an expression. SQL also supports a few other operators,
such as In (discussed in Nested Queries below ) and Like, w hich is used to m atch
a specified pattern, and w hich m ay include w ild card characters. Of course, parentheses m ay also be used to ensure that the expression is evaluated properly.

Only tho se ro ws c o ntaining a Custo merId value o f 431 will be returned. Sinc e
Custo merId is the primary key o f this table, yo u kno w that eac h value o f Custo merId
is unique, so at mo st, o ne ro w will be returned. No te that if yo u spec ify a value fo r
Custo merId that isn’t in the table, no ro ws will be returned.
Of c o urse, if yo u use an expressio n that is true fo r multiple ro ws, then multiple
ro ws will be returned. The fo llo wing Select statement may return multiple ro ws
fro m the Custo mers table, sinc e there may be multiple ro ws where the State c o lumn
c o ntains the value “MD” (see Figure 4-4):

Select *
From Customers
Where State = “MD”

Chapter 4 ✦ SQL Statement Primer

Figure 4-3: Selecting inform ation about Custom erId 431

Figure 4-4: Selecting custom ers from Maryland

57

58

Part I ✦ Database Programming Fundamentals

M ore complex search expressions
Searc h expressio ns c an be as c o mplic ated as yo u want. Yo u c an use And , Or, and
Not to c o mpile multiple simple expressio ns to gether to narro w the searc h. The fo llo wing Select statement returns all o f the c usto mers who were added to the
database sinc e 1999 and who also live in Califo rnia (see Figure 4-5):

Select *
From Customers
Where State = “CA” And DateAdded >= “1-January-1999”

Figure 4-5: Retrieving all the custom ers living in California w ho w ere added since
1999

Note

Waiting for it to end: Alw ays try to include at least one colum n in your search
expression that is part of an index. Otherw ise, the database server w ill have to
search through every row in the table to find the row s you w ant. While searching
the w hole table can be fairly quick for sm all tables, it can take a long tim e for large
tables.

Chapter 4 ✦ SQL Statement Primer

Sorting results
By default, the Select statement do esn’t return ro ws in any partic ular o rder. In
many c ases this isn’t a pro blem, but if yo u want to display these ro ws to the user,
yo u might find it benefic ial to so rt them befo re they’re displayed with the Order By
c lause.

Order By fo llo ws the Where c lause and inc ludes the list o f c o lumns that yo u want
to use to so rt the results. If yo u fo llo w a c o lumn name with the key Asc o r Desc ,
that partic ular c o lumn will be so rted in asc ending o r desc ending o rder, respec tively. If yo u do n’t spec ify either keywo rd, the data will be so rted in asc ending
o rder. In the statement belo w, I’m go ing to retrieve all o f the c usto mers who live
in No rth Caro lina and so rt them by their name (see Figure 4-6):

Select *
From Customers
Where State = “NC”
Order By Name

Figure 4-6: Sorting row s retrieved from a table

59

60

Part I ✦ Database Programming Fundamentals

No te that sinc e the data in the Name field is sto red first name then last name, the
results are so rted by the perso n’s first name.
CrossReference

For m ore inform ation about foreign keys and keys in general, refer to Chapter 2,
“Indexes and Keys.”

Using multiple tables
The Select statement allo ws yo u to c o mbine info rmatio n fro m multiple tables into a
single “virtual table.” This “virtual table” c an’t be updated, but it makes it easier
when yo u need to c o llec t info rmatio n yo u want to display in yo ur applic atio n.
Note

Join operations: The technical term for com bining the row s and colum ns in tw o
or m ore tables is know n as a join operation.

The wrong way to use two tables
The Select statement allo ws yo u to spec ify a list o f tables in the From c lause.
Ho wever, the results are pro bably no t what yo u wo uld expec t. Co nsider the fo llo wing tables. Eac h table has three ro ws, with two c o lumns in eac h ro w. Eac h letter
represents a spec ific value in a partic ular c o lumn.

Table A: {{A, I}, {B, J}, {C, K}}
Table B: {{X, I}, {Y, J}, {Z, K}}
If yo u spec ify two tables in the From c lause, the Select perfo rm wo uld lo o k like this
and yo u’ll get the fo llo wing result:

Select *
From A, B
No te that the Se le ct o peratio n matc hed every ro w in the first table with eac h ro w
in the sec o nd. This c reated a table with nine ro ws, eac h ro w having fo ur c o lumns.
While there may be c ases where yo u want this result, I c an’t think o f any o ff the
to p o f my head.

{{A, I, X, I}, {A, I, Y, J}, {A, I, Z, K},
{B, J, X, I}, {B, J, Y, J}, {B, J, Z, K},
{C, K, X, I), {C, K, Y, J}, {C, K, Z, K}}

The right way to use two tables
Generally when you want to use two tables, it is because the
two tables are related to each other. This means that the
tables have one or more columns in common. These columns could
be part of a foreign key relationship. Suppose that Table A and

Chapter 4 ✦ SQL Statement Primer

Table B have the Column2 in common, which is the second column
in each table. Then the following Select statement would allow
you to join the two tables together based on the rows that have
a common value in their second column:
Select *
From A, B
Where A.Column2 = B.Column2
This Select statement wo uld then generate the fo llo wing result:

{{A, I, X, I}, {B, J, Y, J}, {C, K, Z, K}}
No te that even tho ugh Co lumn2 values are identic al, they are repeated twic e
bec ause the ro ws were appended to eac h o ther. Also , if yo u lo o k bac k at the previo us set o f results, yo u will find these three ro ws buried. The Where c lause merely
filtered o ut the ro ws where the values in Co lumn2 didn’t matc h.
Note

Equijoins: A join that uses the Where clause to m atch colum n values in different
tables is know n as an equijoin, w hich is short for equality join.

Resolving column names
In the abo ve example, I had two tables with the same c o lumn name. In o rder to
kno w whic h c o lumn is asso c iated with whic h table, it is nec essary to qualify the
c o lumn name by using the table name, as sho wn in the example belo w:

Select LastName, StateName
From Customers, States
Where Customers.State = States.State
To make life easier, yo u may want to use table aliase s, which allo w yo u to define an
alternate name fo r yo ur table. The table aliases are specified in the From clause by fo llo wing the table name with the alternate name yo u want to use fo r the table. Perso nally,
I prefer to use sho rt o ne- o r two -character abbreviatio ns fo r table aliases, but yo u can
cho o se whatever size name yo u want. Using table aliases, I can rewrite the previo us
query as fo llo ws:

Select LastName, StateName
From Customers C, States S
Where C.State = S.State
No te that using table aliases c an sho rten the expressio n in the Where c lause. While
this do esn’t save muc h in this partic ular example, it c an make a big differenc e in a
very c o mplex Where c lause.

61

62

Part I ✦ Database Programming Fundamentals

Nested queries
Of all the things yo u c an do with the Select statement, ne ste d que rie s are the mo st
c o mplex. In a nested query, yo u use a sec o nd (o r third o r fo urth) Select statement
nested inside yo ur main statement. Typic ally, nested queries are used to return a
set o f values that c an be used with the In o perato r.

Selecting rows using the In operator
So metimes yo u want to c o mpare a c o lumn to a list o f values, as sho wn in the query
belo w:

Select *
From Customers
Where State = “ND”
Or State = “SD”
Or State = “MN”
While this is fairly easy to write, imagine the pro blems yo u might have if yo u had a
list o f 15 o r 20 different values to find. An alternative to writing a bunc h o f different
c lauses is the In o perato r. The In o perato r allo ws yo u to c o mpare a c o lumn against
a set o f values, as sho wn in the query belo w. It will return a list o f c usto mer names
that live in No rth Dako ta, So uth Dako ta, o r Minneso ta (see Figure 4-7).

Select *
From Customers
Where State In (“ND”, “SD”, “MN”)

Sets of values
Yo u c an also c reate a set o f values using a Select statement that c an be used with
the In o perato r. Co nsider the fo llo wing query, whic h answers the questio n, “Whic h
c usto mers are in the same ZIP c o de as any o f the c usto mers that have been added
sinc e 1 January 1999?”:

Select Name, Zip
From Customers
Where Zip In (Select Zip
From Customers
Where DateAdded >= “1-January-1999”)
While this query is so mewhat c o ntrived, it gives yo u an alternate way to c reate a
set o f values. Yo u may also think that this query is similar to the o ne listed belo w,
but it isn’t:

Select Name, Zip
From Customers
Where DateAdded >= “1-January-1999”

Chapter 4 ✦ SQL Statement Primer

Figure 4-7: Finding custom ers in m ultiple states

The two queries c o uld o nly be identic al if eac h ZIP c o de had o nly o ne c usto mer.
Tip

Complex to write, complex to debug: Nested queries often take a w hile to
debug. The syntax errors w ill drive you nuts. I suggest that you avoid using them
unless you can’t do the query any other w ay. Unfortunately, there are som e questions that you m ight w ant to ask that can only be answ ered using nested queries.

Using functions
Yo u c an also inc lude vario us func tio ns in yo ur Select statement. Fo r instanc e, the
fo llo wing Select statement c o unts the number o f Custo mers who live in the state o f
Maryland (see Figure 4-8):

Select Count(CustomerId)
From Customers
Where State = “MD”

63

64

Part I ✦ Database Programming Fundamentals

Figure 4-8: Counting the custom ers from Maryland

Other func tio ns that yo u c an use inc lude Min , Max, and Average , whic h will c o mpute the minimum, maximum, o r average o f a partic ular value ac ro ss all o f the ro ws
selec ted fro m the database.
Tip

Not in my program, you don’t: You probably aren’t going to use functions in your
application program . How ever, using functions in an interactive query program
m ay help you decide if your program is w orking. You can use the Count function
to determ ine the num ber of row s that you just added to your table, or you can use
it to count the num ber of row s your program updated. Som etim es, just a quick
check can help you identify if you actually processed all of the row s you thought
you had.

Inserting Rows into a Table
The SQL Insert statement is used to add o ne o r mo re ro ws to a table. Here is the
syntax fo r this statement:

Insert [Into] [( [, } ...])]
( [,]...) |
As ]

[ Values

Chapter 4 ✦ SQL Statement Primer

where

is the name of where you want to insert new rows.
is the name of a column in the table.
is a value that you wish to insert into a column.
is a valid Select statement.
The Insert statement adds a ro w into the spec ified table. Yo u c an spec ify a list o f
c o lumns fo r whic h yo u will assign the values o r use the list o f c o lumns spec ified
when the table was c reated. Yo u c an either explic itly spec ify the list o f values in the
Value c lause o r use the As keywo rd to spec ify a Select statement that will retrieve
values fro m ano ther table.
Using the Value c lause, yo u will spec ify the list o f values to be inserted into the
table. The po sitio n o f eac h value c o rrespo nds to the o rder o f the c o lumns spec ified
in the Insert statement, o r if the list c o lumns were no t spec ified, the values will c o rrespo nd to the o rder o f the c o lumns in the table definitio n.
Using the As c lause with a Select statement allo ws yo u to po pulate a table with data
fro m ano ther table. Like the Value c lause, the c o lumns retrieved in the Select statement must matc h up with the c o lumns spec ified after the table name.
Tip

Testing with copied data: When you are testing code that deletes or updates data
in a table, it is often useful to create a tem porary table w ith a copy of your test data
and use that table for your testing. This allow s you to easily refresh your data after
your program deletes the w rong inform ation. Using the Insert statem ent w ith the
As clause m akes this very easy to do.

A simple Insert statement
Here’s a very simple Insert statement:

Insert Into Customers
(CustomerId, Name, Street, City, State, Zip, Phone,
EmailAddress, DateAdded, DateUpdated, MailingList,
Comments)
Values (99999, “Christopher J. Freeze”, “1234 Main Street”,
“Beltsville”, “MD”, 20705, “(800) 555-5555”,
“CFreeze@JustPC.net”, “1-January-2000”, “1-January-2000”,
1, “”)
It adds a single ro w o f info rmatio n into the Custo mers table (see Figure 4-9). No te
that I explic itly spec ify eac h o f the c o lumns in the table. Eac h o f the values listed in
the Values c lause c o rrespo nds to the c o lumn listed in after the table name.

65

66

Part I ✦ Database Programming Fundamentals

Figure 4-9: Adding a single row to the Custom ers table

The Insert statement listed belo w is identic al to the previo us o ne, but it assumes
that the o rder o f the c o lumns as defined in the database is the same as the o rder o f
the data in the Value c lause.

Insert Into Customers
Values (99999, “Christopher J. Freeze”, “1234 Main Street”,
“Beltsville”, “MD”, 20705, “(800) 555-5555”,
“CFreeze@JustPC.net”, “1-January-2000”, “1-January-2000”,
1, “”)
Note

To run once is good, to run twice is bad: Running this statem ent m ore than once
w ill cause an error. Since the Custom erId field is the prim ary key for the table and
each row m ust have a unique value, attem pting to add another row w ith the sam e
value w ill cause an error.

Chapter 4 ✦ SQL Statement Primer

Deleting Rows from a Table
The Delete statement is used to remo ve o ne o r mo re ro ws fro m a table. Here is the
syntax fo r this statement:

Delete From
[Where ]
where

is the name of the database table from which you want
to delete the rows.
is an expression that is used to determine which
rows to delete.
The Delete statement is the o ppo site o f the Insert statement. It is used to remo ve
ro ws fro m a table. The Delete statement uses the Where c lause fro m the Select
statement to identify whic h ro ws sho uld be deleted.
Tip

Deleting rows: When deleting a specific row from a table, use the prim ary key in
the Where clause to identify the specific row you w ant to delete.

A Sample Delete Statement
The fo llo wing Delete statement will delete the ro w I just added (see Figure 4-10):

Delete From Customers
Where CustomerId = 99999
Yo u c o de the Where c lause the same way yo u wo uld the Select statement. In this
c ase, I o nly want to delete the o ne ro w, so I need to c o de the Where c lause to selec t
the spec ific ro w I want to delete.
The Delete statement c an also be very dangero us. The fo llo wing statement will
delete all o f the ro ws in the Custo mers table:

Delete From Customers
No te that the o nly differenc e between this statement and the previo us o ne is the
missing Where c lause.

67

68

Part I ✦ Database Programming Fundamentals

Figure 4-10: Deleting a single row from the Custom ers table

Caution

Don’t delete everything: It is very easy to delete everything from a table. For that
reason, you should exercise extrem e caution w henever you use the Delete statem ent. Alw ays use the Where clause w hen using the Delete statem ent. Failure to
do so w ill delete all of the row s in your table. Unless you are deleting data as part
of a transaction (see Chapter 16, “Transactions” for m ore inform ation), you can’t
recover any deleted records.

Updating Rows in a Table
The Update statement allo ws yo u to c hange values in o ne o r mo re c o lumns in o ne
o r mo re ro ws. Here is the syntax fo r this statement:

Update
Set = [, = ] ...
Where
where

is the name of the table you want to update.
is a column name in the table you want to update.

Chapter 4 ✦ SQL Statement Primer

is an expression containing the new value for the
column.
is true for the rows you want to update in the
table.
The Update statement allo ws yo u to c hange any value in any ro w in a table. Like the
Delete statement, yo u need to inc lude a Where c lause to iso late the effec ts o f this
statement o nly to the ro ws yo u want to update. Otherwise, yo u wo uld apply the
c hange to all o f the ro ws in the table.

A Sample Update Statement
The fo llo wing Update statement will searc h fo r all ro ws that have a Null value fo r
DateUpdated in the Custo mers table and replac e the value with a valid date (see
Figure 4-11).

Update Customers
Set DateUpdated = “1-January-1997”
Where DateUpdated Is Null

Figure 4-11: Changing Nulls to a valid date

69

70

Part I ✦ Database Programming Fundamentals

The Create Table Statement
The Create Table statement is used to build a new table in yo ur database.
Note

There’s more to this statement than meets the eye: Nearly all database vendors
have added m any vendor-specific extensions to the Create Table statem ent that
I’ll cover in m ore detail w hen I focus on the specific database system s in Chapters
23, 26, and 29.

Here is the syntax fo r this statement:

Create Table ( [, ]...)
where

::= [Null | Not Null ]
and

is the name of your table.
is the name of a column in your table.
is a valid data type.
The Create Table statement allo ws yo u to define the c o llec tio n o f c o lumns that
make up a table. The table must no t already exist in yo ur database, o r yo u’ll get an
erro r message when yo u try to c reate it.
Eac h c o lumn must be assigned a valid data type. Table 4-2 earlier in this c hapter
lists so me o f the c o mmo n data types available fo r a relatio nal database.
CrossReference

Tip

For m ore detailed inform ation about the data types available in a particular
database, see Chapter 23, “Overview of SQL Server,” Chapter 26, “Overview of
Oracle 8 i ,” or Chapter 29, “Overview of Microsoft Jet.”

Gone with the table: To rem ove a table from your database, use the Drop Table
< tablenam e> SQL statem ent. This statem ent w ill also delete any indexes associated w ith the table. Just be certain that you really w ant to delete the table, since it
can’t be undeleted.

The fo llo wing SQL statement c reates the Custo mers table fo r SQL Server:

Create Table Customers (CustomerId Int Not Null,
Name Varchar(64), Street Varchar(64), City Varchar(64),
State Char(2), Zip Int, Phone Varchar(32),

Chapter 4 ✦ SQL Statement Primer

EMailAddress Varchar(128), DateAdded Datetime,
DateUpdated Datetime, MailingList Bit,
Comments Varchar(256))
No te that I dec lare the value Custo merId as Not Null , sinc e this c o lumn is the
primary key fo r this table.

The Create Index Statement
The Create Index statement is used to add an index to a table in yo ur database.
Caution

Choose carefully, my child: Picking the right set of indexes can be difficult. You
should use an index on the prim ary key of a table, especially if you plan to retrieve
row s based on the prim ary key. How ever, adding any other indexes can severely
im pact your database’s perform ance, since each tim e you add a row to the
database, the database server has to update all of the indexes. The m ore indexes
you have, the longer it w ill take to update your data.

Here is the syntax fo r this statement:

Create [Unique] Index On (
[, ]...)
where

is the name of your index.
is the name of your table.
is the name of a column in your table.
The Create Index statement adds an index to yo ur table using the spec ified c o lumns.
Using an index c an impro ve the perfo rmanc e o f queries that use tho se c o lumns at
the c o st o f additio nal wo rk the database server must do eac h time any o f the values
in the spec ified c o lumns are c hanged.
Inc luding the keywo rd Unique means that the set o f values inc luded in the index
will be unique in the table. This is a useful feature if yo u need to ensure that yo u
do n’t have two o r mo re ro ws with the same value in the indexed c o lumns.
Tip

Index be gone: To rem ove an index from your table, use the Drop Index < indexnam e> SQL statem ent.

71

72

Part I ✦ Database Programming Fundamentals

A Sample Create Index Statement
The fo llo wing SQL statement c reates a Unique index o n the Custo merId field o f the
Custo mers table:

Create Unique Index CustomerIndex
On Customers (CustomerId)
This ensures that eac h value o f Custo merId in the table will be unique and also that
queries using the Custo merId c o lumn in the Where c lause will run faster.

The Create View Statement
The Create View statement c reates a virtual table that c an be used like any o ther
table in yo ur database. Here is the syntax fo r this statement:

Create View [( [, ]...)]
As
where

is the name of your view.
is the name of a column in your view.
is valid select statement that returns the
information in your view.
CrossReference

For m ore inform ation about view s, refer to “View s” in Chapter 2.

The virtual table that the Create View statement defines in yo ur database is indistinguishable fro m a regular table fo r any o peratio ns invo lving a Select statement.
The virtual table c an o ften be updated, depending o n ho w the view was c reated.
In o rder to update a view, the Select statement must o nly referenc e a single table
kno wn as the base table , and it must no t return any c alc ulated values using func tio ns and/ o r mathematic al fo rmulas. Also , any c o lumns no t explic itly inc luded in
the view must be able to ac c ept Null values. When yo u try to add a ro w to a view,
any c o lumns in the base table that are no t part o f the view will be set to Null .
Tip

Bye-bye view: To rem ove a view from your table, use the Drop View < view nam e>
SQL statem ent.

The fo llo wing SQL statement c reates a view that c o nsists o f the c usto mer’s name
and the Custo merId c o lumn:

Create View CustomerNames As
Select Name, CustomerId
From Customers

Chapter 4 ✦ SQL Statement Primer

Figure 4-12 sho ws the results o f using a Select statement against the view. This view
c an be updated, sinc e the c o lumns that are no t inc luded will ac c ept Null values. This
tec hnique is kno wn as ve rtical partitio ning, sinc e o nly so me o f the c o lumns are made
available to the user.

Figure 4-12: Preventing som eone from seeing custom er inform ation beyond the
custom er’s nam e and Custom erId

Yo u c an also use a Where c lause to retrieve o nly so me o f the ro ws in a table. This
tec hnique is kno wn as ho riz o ntal partitio ning. Ho rizo ntal partitio ning is useful if yo u
need to c reate a view where o nly so me o f the ro ws in the table are retrieved. The
fo llo wing SQL statement c reates a view c o ntaining o nly the c usto mers fo und in
Maryland (see Figure 4-13):

Create View MdCustomers As
Select *
From Customers
Where State = “MD”
No te that this view is updateable, sinc e all o f the c o lumns fro m the base table are
present. Also , even tho ugh the view is restric ted so that o nly c usto mers fro m
Maryland will be returned, yo u c an insert ro ws using a different value fo r State.
Thus, it is po ssible to add a ro w to the view that yo u will be unable to later retrieve.

73

74

Part I ✦ Database Programming Fundamentals

Figure 4-13: Restricting the view to only the custom ers from Maryland

Thoughts on Using SQL to Speed
Your Development Process
The Create Table , Create View , and Create Index statem ents are know n as Data Definition
Language (DDL) statem ents, w hile the Insert , Delete , Update , and Select statem ents are
know n as Data Manipulation Language (DML) statem ents. In m ost database system s
today, you rarely execute DDL statem ents w hen you w ant to create a database structure.
Instead, you use a utility supplied w ith the database system that allow s you to fill in all of
the inform ation into a table or use a w izard that w ill help you create your table or index.
This doesn’t m ean that the DDL statem ents aren’t used. It m erely m eans that you enter the
inform ation in a different fashion. The database utility usually includes a feature that w ill
allow you to generate the SQL statem ents from the definitions you entered. Then you m ight
use these SQL statem ents to create a copy of the database on another com puter or include
them in your application if you w ant your users to be able to create the database structures
on the fly. Visual Basic includes several object m odels that isolate the program m er from the
underlying SQL statem ents. So, w hile you m ay not need to know how to use the SQL statem ents to w rite a database application, you m ay find yourself backed into a corner, in term s
of the technology.

Chapter 4 ✦ SQL Statement Primer

Sim ply using an interactive query tool to retrieve inform ation from your database w ill help
you understand if your program is w orking properly or not. You can use the Select statem ent to return row s from a table and you can verify that they w ere updated properly. When
used w ith the Count function, you can find out if your program processed the correct num ber of row s.
The Insert and Create Table statem ents can be used together to create test copies of a
table, w ith w hich you can test updating and deleting row s repeatedly until you are satisfied
that your program is running correctly.
Most database vendors supply a rich environm ent for executing SQL statem ents. Using this
environm ent, it is possible to w rite m ulti-statem ent SQL program s called stored procedures
that perform fairly com plex operations. Since these stored procedures run totally on the
database server, they m ay run significantly faster than executing them one statem ent at a
tim e from your local com puter. This is an im portant concept to keep in m ind w hen developing a database application, and one that I’ll explore in m ore depth w hen I talk about the
stored procedures.
Also, keep in m ind that m any OLE DB providers translate the activities you perform into SQL
statem ents that are sent to the database server for execution. This happens even if you
don’t explicitly include SQL statem ents in your program . So, in cases w here every cycle
counts, you m ight consider coding the SQL statem ents yourself rather than letting the
provider do the w ork.
Another thing to keep in m ind is that this chapter contains just enough inform ation to get
you started in learning how to use SQL. Since I feel that the best w ay to learn is by doing, I
suggest you take the tim e to use Query Analyzer, SQL*Plus, or any other interactive SQL utility program to practice building and executing SQL statem ents. While I believe in the KISS
rule (Keep it Sim ple Stupid!), there are tim es w here it is appropriate to use very com plex
SQL statem ents. And the best w ay to w rite com plex SQL statem ents that w ork is by practicing w riting sim ple SQL statem ents.

Summary
In this c hapter yo u learned:

✦ abo ut the SQL statements and data types.
✦ ho w to use the Select statement to retrieve info rmatio n fro m yo ur database.
✦ ho w to use the Insert, Delete, and Update statements to manipulate the data
in yo ur database.

✦ ho w to use the Create Table statement to c reate a new table.

75

76

Part I ✦ Database Programming Fundamentals

✦ ho w to use the Create Index to allo w the database to find spec ific ro ws in
yo ur table mo re quic kly.

✦ ho w to use the Create View statement to c reate a virtual table that c an be
used just like a real table, but who se c o ntents are dynamic ally c reated fro m
o ther tables in the database.