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

Delphi Getting Started With SQL Part 1 PDF

The document introduces the basics of using SQL to access and manipulate data in databases, including using SELECT statements to retrieve data from tables, adding a WHERE clause to filter rows, and using calculations in the select list. It also provides instructions for connecting to an example InterBase database included with Delphi and running sample SQL statements in the ISQL tool to experiment with the concepts covered.

Uploaded by

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

Delphi Getting Started With SQL Part 1 PDF

The document introduces the basics of using SQL to access and manipulate data in databases, including using SELECT statements to retrieve data from tables, adding a WHERE clause to filter rows, and using calculations in the select list. It also provides instructions for connecting to an example InterBase database included with Delphi and running sample SQL statements in the ISQL tool to experiment with the concepts covered.

Uploaded by

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

Surviving Client/Server:

Getting Started With SQL Part 1


by Steve Troxell

D elphi incorporates some very


useful database components
that make developing database
make sure you’ve selected Local
Server, enter the path and filename
for the EMPLOYEE.GDB database,
databases. A database is a
collection of tables; in Paradox
each .DB file represents a table, in
applications a breeze. And because enter SYSDBA for the user name, and InterBase each .GDB file represents
Delphi ships with a local version of enter masterkey for the password a database and the tables are
Borland’s InterBase database (make sure you enter the password managed internally.
server, a great number of applica- in lower case). This is the default Second, let’s take a look at the
tion developers now have an easy, system administrator login for syntax of a SQL statement. A
inexpensive means of exploring the InterBase databases. typical SQL statement might be:
world of Client/Server technology Using the ISQL program is
right at their fingertips. For these simple: type in the SQL statement SELECT name, address
reasons, many fledgling Delphi you want to execute in the SQL FROM customers;
programmers may be introduced Statement window and click the Run
to Structured Query Language button to execute the statement. SQL itself is case-insensitive, but in
(SQL) for the first time. This article The results of your statement will this article SQL keywords are
is intended to introduce you to the appear in the ISQL Output window. shown in all uppercase and table
principal SQL data access Once you run an SQL statement, it names, column names, etc. are
statements: SELECT, INSERT, disappears from the SQL Statement shown in all lower case. SQL gener-
UPDATE and DELETE. These are the window. If you want to run it again ally requires a semi-colon at the
workhorses of SQL and by the end (and perhaps make small changes end of each statement, but in
of this article you’ll be able to to it), you can retrieve any certain tools (such as ISQL) it’s
effectively use SQL to accomplish a previous SQL statement by clicking optional.
wide variety of tasks. We’ll the Previous button. Third, you can break an SQL
continue to expand our knowledge statement across multiple lines by
of SQL in the next issue. SQL Preliminaries pressing RETURN anywhere you can
All of the examples in this article Before we get started, let’s look at legally place a space in the
use the sample InterBase database a few of the ground rules for work- statement.
EMPLOYEE.GDB that ships with ing with SQL. First, three new Finally, you can enclose literal
Delphi. You may find it helpful to terms: the familiar structures of strings with single quotes or
connect to this database through file, record, and field are called double quotes. We’ll use single
the Windows Interactive SQL table, row, and column in relational quotes here.
(ISQL) program that ships with
Delphi and try the examples as you
read about them. It’s also handy to Introducing The Column...
be able to experiment as ideas
come to you while reading the text.
This database is located in the
\IBLOCAL\EXAMPLES directory if
D elphi users seem to have settled down into several groups: firstly
occasional programmers or first-time programmers ( attracted by
Delphi’s ease of use), secondly professional full-time developers doing
you installed Delphi with the general Windows application building (enthralled by Delphi’s amazing
default directories. We will be productivity) and thirdly those putting together Client/Server systems
adding information in this (impressed by Delphi’s robustness and power). This column is aimed
database so you may want to make at the third group, but especially those who may be dipping a toe into
a copy of the EMPLOYEE.GDB file the waters of Client/Server for the first time.
and work with the copy only. Steve is involved in developing a variety of Client/Server systems in
his work at TurboPower Software, using different server databases, and
Using ISQL we are looking forward to learning from his experience over the months.
To use Windows ISQL, start the As well as SQL – an essential part of the Client/Server developer’s skill
ISQL program from the Delphi set – Steve plans to cover a variety of other topics and also provide lots
program group. From the File of hints and helps along the way. If there are things which you need
menu, select Connect to Database. some help with, why not drop us a line and let us know!
In the Database Connect dialog box,

12 The Delphi Magazine Issue 3


Reading Rows
SELECT is SQL’s data retrieval
statement and is probably the
most frequently used SQL
statement. The basic form of the
SELECT statement is:

SELECT <column(s)>
FROM <table(s)>;

For example, try the following


SELECT statement in ISQL (the
results are shown in Figure 1):

SELECT last_name, first_name


FROM employee;

We selected the last_name and


first_name columns from the
employee table. By default, SELECT
returns all the rows from the table,
but only shows data for the
columns we requested (called the ➤ ISQL in action
select list). If you wanted to see all
of the columns in a table, it would SELECT last_name, first_name FROM employee;
be cumbersome to enter the name
of every column in the SELECT LAST_NAME FIRST_NAME
==================== ===============
statement, so SQL provides a
convenient shortcut: an asterisk Nelson Robert
Young Bruce
can be used to indicate all columns. Lambert Kim
Try the following in ISQL: Johnson Leslie
Forest Phil
Weston K. J.
SELECT * FROM employee;

➤ Figure 1 (partial listing of rows)


Computed Columns
You can also show calculated
results with a SELECT statement. In SELECT last_name, salary / 12 FROM employee;
this case, you simply provide the
expression used to make the calcu- LAST_NAME
==================== ======================
lation in place of a column name in
the select list. The example below Nelson 8825
Young 8125
estimates the monthly earnings of Lambert 8562.5
each employee: Johnson 5386.25
Forest 6255
Weston 7191.078125
SELECT last_name, salary / 12
FROM employee;
➤ Figure 2 (partial listing of rows)

Take a look at the results of this


statement in Figure 2. Notice that There’s no reason why we couldn’t Many times you’re not interested
there isn’t a column name for the do the same thing to a regular in wading through all of the rows to
salary calculation. That’s because named column as well, if we get the information you want.
the data shown doesn’t exist as a wanted to reference the data by Usually all you want is a specific
named column in the table we something other than its defined row, or a set of rows with
selected from. A column without a column name. You might need to something in common. You use the
name is just not a very useful thing do this if you were selecting data WHERE clause to restrict the rows
to have, so we need to assign an from two or more tables that use returned by SELECT.
alias to the column (see Figure 3): the same column name. For example, the following SQL
statement selects all the
SELECT last_name, salary / 12 Selecting Subsets Of Rows employees in the Software
AS monthly_salary The selects we’ve looked at so far Development department (see
FROM employee; return all the rows in the table. Figure 4):

September 1995 The Delphi Magazine 13


SELECT * FROM employee
SELECT last_name, salary / 12 AS monthly_salary
WHERE dept_no = 621; FROM employee;

LAST_NAME MONTHLY_SALARY
The criteria defined by a WHERE ==================== ======================
clause is usually referred to as the
Nelson 8825
search condition. The SELECT state- Young 8125
ment returns only those rows that Lambert 8562.5
Johnson 5386.25
meet the search condition. WHERE Forest 6255
supports a variety of conditional Weston 7191.078125
operators and allows multiple
criteria to be logically combined
➤ Figure 3 (partial listing of rows)
using AND and OR. Some of the
common operations that can be
performed are listed in Figure 5. SELECT * FROM employee WHERE dept_no = 621;
Many SQL databases offer
additional operations. EMP_NO FIRST_NAME LAST_NAME PHONE_EXT HIRE_DATE
====== =============== ==================== ========= ===========
The following examples
illustrate some of the expressions 4 Bruce Young 233 28-DEC-1988
45 Ashok Ramanathan 209 1-AUG-1991
you can use to formulate search 83 Dana Bishop 290 1-JUN-1992
conditions. They are all valid 138 T.J. Green 218 1-NOV-1993
search conditions for the employee
table, so feel free to try them out in
➤ Figure 4 (partial listing of columns)
ISQL before continuing (try SELECT
* FROM employee using each of the
following WHERE clauses).
Operator Meaning
WHERE job_grade IN (1,3,4) AND
job_country = ’USA’ = Equal to
<> Not equal to
WHERE salary / 12 > 10000 > Greater than
< Less than
WHERE phone_ext IS NULL >= Greater than or equal to
<= Less than or equal to
WHERE hire_date BETWEEN BETWEEN x AND y Range: greater than or equal to <x> and
’1-1-90’ AND ’12-31-90’ less than or equal to <y>
IS NULL Contains null value
WHERE UPPER(first_name) IS NOT NULL Contains non-null value
LIKE ’ROBERT%’ IN (x,y,...) Value found in a list
NOT IN (x,y,...) Value not found in a list
It should be noted that the columns LIKE Matches a wildcard pattern
used in the WHERE clause do not
have to be part of the select list;
➤ Figure 5 Common SQL operators
they only have to be available in
the table defined in the FROM clause
of the SELECT statement. Suppose you needed to look up a characters (if any) preceded or
customer and all you could followed the word.
Wildcarding remember was that they were
You can use wildcards to select on located on Newbury Street or Sorting Rows
a character column matching a Avenue or Newbury something. You can sort the rows returned by
given pattern (amazingly enough, You could use the following SQL a SELECT statement by including an
this is sometimes referred to as statement: ORDER BY clause. ORDER BY simply
pattern matching). names the columns you want to
SQL supports two wildcard SELECT customer, address_line1 sort on. Suppose you wanted a list
characters: % is used to match any FROM customer of sales orders sorted by the
number of characters (including WHERE address_line1 amount of the order (see Figure 7
zero), and _ is used to match LIKE ’%Newbury%’; for the output):
exactly one character. You must
use the LIKE operator to use wild- As Figure 6 shows, this select finds SELECT cust_no, order_status,
cards in a character search, other- all rows containing the word total_value
wise the wildcards are taken Newbury anywhere in the column FROM sales
literally. address_line1, regardless of what ORDER BY total_value;

14 The Delphi Magazine Issue 3


Like WHERE, the columns defined SELECT customer, address_line1 FROM customer
in ORDER BY do not have to appear WHERE address_line1 LIKE ’%Newbury%’;
in the select list. This is true for
CUSTOMER ADDRESS_LINE1
InterBase but may not apply to ========================= ==============================
other SQL databases.
Buttle, Griffith and Co. 2300 Newbury Street
You can define the sort sequence
for each sort column by adding the
ASC (ascending) or DESC (descend-
➤ Figure 6
ing) keyword after the column
name in the ORDER BY clause. Here’s
how you would make the query
SELECT cust_no, order_status, total_value
above return a list of sales orders FROM sales
in order of decreasing amount: ORDER BY total_value;

CUST_NO ORDER_STATUS TOTAL_VALUE


SELECT cust_no, order_status, =========== ============ ===========
total_value
1003 waiting 0.00
FROM sales 1001 shipped 0.00
ORDER BY total_value DESC; 1006 shipped 47.50
1014 shipped 100.02
1010 shipped 210.00
As an alternative to specifying the
name of the column to sort on, you
➤ Figure 7 (partial listing of rows)
can specify the number of the
column from the select list. This is
useful if you’ve included an SELECT full_name, salary / 12 FROM employee ORDER BY 2;
unaliased computed column in the
FULL_NAME
select list. For example, suppose ===================================== ======================
you wanted a list of employees in
Bennet, Ann 1911.25
order by monthly salary (see Brown, Kelly 2250
Figure 8): O’Brien, Sue Anne 2606.25
Guckenheimer, Mark 2666.666666666667
Reeves, Roger 2801.71875
SELECT full_name, salary / 12
FROM employee
➤ Figure 8 (partial listing of rows)
ORDER BY 2;

Here the 2 in the ORDER BY means have to combine this information combine the rows such that
“order by the second column in the somehow into a single report. This dept_no in the employee table
select list”; that is, by the is where the concept of a “join” matches dept_no in the department
computed column salary / 12. comes into the picture. table” (in this case the department
If you use both a WHERE clause and A join can occur between two or table also happens to contain a
an ORDER BY clause in the same more tables where each pair of column called department). Take a
select statement, the WHERE clause tables can be linked by a common look at the results shown in Figure
must appear before the ORDER BY field. 9. The result of a join select is
clause, as in the following example: For example, departments are indistinguishable from a single
identified by the dept_no column in table select.
SELECT * FROM employee both the employee table and The WHERE clause defines the
WHERE dept_no = 621 department table, so this column association between the two
ORDER BY phone_ext; can be used to link the two tables tables. The linking columns are not
in a join. In SQL you can use the required to have the same name,
Selecting From WHERE clause to specify the link field but they must be compatible data
Multiple Tables (Joins) for a join between two tables. The types. As an alternative to the WHERE
One of the most powerful features select statement below produces clause, you can also define a join in
of the SELECT statement (and of SQL the employee roster we want: the FROM clause as follows:
itself) is the ease with which you
can combine data from multiple SELECT full_name, department SELECT full_name, department
tables into one informative view. FROM employee, department FROM employee JOIN department
For example, suppose you want WHERE employee.dept_no = ON employee.dept_no =
a roster of all employees by department.dept_no department.dept_no
department. Employee names are ORDER BY department; ORDER BY department;
stored in the employee table and
department names are stored in This means “show the selected You can join more than two tables
the department table, so you’ll columns from the given tables and by simply ANDing the join

September 1995 The Delphi Magazine 15


expressions together in the WHERE SELECT full_name, department FROM employee, department
clause (or concatenating JOINs in WHERE employee.dept_no = department.dept_no
the FROM clause). The linking col- ORDER BY department;

umns do not have to be the same FULL_NAME DEPARTMENT


for all tables in the join. For exam- ===================================== =========================
ple, to get a list of all employees O’Brien, Sue Anne Consumer Electronics Div.
assigned to a project and the name Cook, Kevin Consumer Electronics Div.
Lee, Terri Corporate Headquarters
of the projects they are assigned Bender, Oliver H. Corporate Headquarters
to, you must join the employee, Williams, Randy Customer Services
employee_project, and project Montgomery, John Customer Services

tables:
➤ Figure 9 (partial listing of rows)
SELECT full_name, proj_id,
proj_name
FROM employee,
SELECT full_name, proj_id, proj_name
employee_project, project
FROM employee, employee_project, project
WHERE employee.emp_no = WHERE employee.emp_no = employee_project.emp_no AND
employee_project.emp_no employee_project.proj_id = project.proj_id
ORDER BY full_name;
AND
employee_project.proj_id = FULL_NAME PROJ_ID PROJ_NAME
===================================== ======= ====================
project.proj_id
ORDER BY full_name; Baldwin, Janet MKTPR Marketing project 3
Bender, Oliver H. MKTPR Marketing project 3
Bishop, Dana VBASE Video Database
You can see the results in Figure 10. Burbank, Jennifer M. VBASE Video Database
One improvement we could Burbank, Jennifer M. MAPDB MapBrowser port
Fisher, Pete GUIDE AutoMap
make is to reduce the bulk of this Fisher, Pete DGPII DigiPizza
statement a little by assigning
aliases to the tables just as we
➤ Figure 10 (partial listing of rows)
assigned aliases to columns
previously. We do this in the same
fashion by following the actual Committing Your Work (this is yet another boon of SQL by
table name with its alias, however One of the key characteristics of helping preserve data integrity
we do not use the AS keyword in SQL is that when you add or modify through automatic means).
between. We’re going to redefine data in the SQL table, the changes
the employee, employee_project and are not permanently recorded in Adding New Rows
project tables to have the aliases a, the table and other users of the We use the INSERT statement to add
b and c respectively. So our final database will not see them, until a new row to a table. INSERT expects
select statement now looks like: you commit them. In this way you us to enumerate the values of each
can work with the data as much as column in the table for the new
SELECT full_name, proj_id, you like until you get it just the way row.
proj_name you want it and then commit it For example, the country table
FROM employee a, permanently to the database. identifies the currency used in a
employee_project b, In ISQL you commit your particular country and contains
project c changes by selecting Commit Work two columns: country and
WHERE a.emp_no = b.emp_no from the File menu. If you want to currency. To add a new country row
AND b.proj_id = c.proj_id undo your modifications, you can in this table we would use:
ORDER BY full_name; select Rollback Work from the File
menu. This will rollback all the INSERT INTO country
Summing Up SELECT changes you’ve made since the last VALUES (’SteveLand’,
SELECT is where most of the power time you committed your work. ’Twinkies’);
of SQL lies. There are even more Think of this as a refresh of the data
clauses and functionality to SELECT you’re working with. In this case Twinkies are the form
than were covered here, so check Be careful if you decide to of currency in SteveLand. Try
your manual. This was meant just experiment with these data entering this statement into ISQL
to show you the basic nuts-and- modification statements outside and then select all the rows from
bolts needed to do anything really the examples given. The tutorial country to see the result.
useful with SELECT. database provided with InterBase The data values must appear in
In the next issue we’ll cover a lot defines some data validation and the same order as the columns are
more on SELECT, but now that we’ve referential integrity constraints defined; the first value given will be
got a handle on looking at the data, that may give you errors if you inserted into the first column, the
we’ll turn to altering the data. don’t modify the data just right second value into the second

16 The Delphi Magazine Issue 3


column, and so on. Alternatively, the rows from the orders table that well. If you were in a generous
you can enter the values in any have a status of shipped. For each mood and wanted to double
order you like as long as you row we find, we are inserting a row everybody’s salary, you could try:
specify the column names after the into the shipped_orders table that
table name. The data values must consists of the order_num and or- UPDATE employee
then be in the order of the columns der_total columns from orders (re- SET salary = salary * 2;
as given. For example: alistically, we would probably
delete these rows from orders after Removing Rows
INSERT INTO country (currency, we’ve copied them). If there are Sooner or later, you’ll need to
country) any additional columns in remove some of the data from a
VALUES (’Clams’, shipped_orders, they default to null table. To delete rows we use the
’Troxellvania’); since we did not provide a value for DELETE statement. DELETE simply
them. Notice that the column uses a WHERE clause to identify the
Using this same syntax you can names in the read table do not have rows to delete from a given table.
insert data into only certain to match the column names in the Let’s say our company is
columns instead of all of them. Any write table. We only need to have downsizing and we now need to
columns not specifically included the same number of columns and remove the Software Development
in the INSERT receive a null value. of the same data type. department from the department
Try this in ISQL and then select all table. Try the following in ISQL and
rows to see what happens: Changing Rows then select all rows from the table
Now that we have a new customer, to see the results:
INSERT INTO customer (customer) let’s add some useful information.
VALUES To change the value of a column DELETE FROM department
(’Bigwig International’); within an existing row we use the WHERE dept_no = 621
UPDATE statement. Let’s add Joe
The results of this statement are Johnson as the contact for our new If the WHERE clause is omitted, then
shown in Figure 11. Notice that the customer. Try the following in ISQL all of the rows in the table are
customer column was set as we and examine the results: deleted.
specified, and all the other col-
umns except cust_no were set to UPDATE customer Conclusion
null. Cust_no was set to a new value SET contact_first = ’Joe’, There you have it: the real meat of
because of two advanced concepts contact_last = ’Johnson’ SQL. We’ve covered the principal
called triggers and generators; con- WHERE customer = statements of SQL and with these
cepts that are outside the scope of ’Bigwig International’; you can perform a great deal of the
this article, but we’ll cover them in common tasks of relational
a future issue. (Note: Bigwig International must databases. In the next issue we’ll
be spelled and cased exactly as you cover some more features of SELECT
Copying Rows originally entered it in the INSERT that simplify creating reports from
It is possible to combine the INSERT statement previously). SQL data.
and SELECT statements to allow you The SET clause specifies a list of
to copy specific columns from columns to modify and their new
existing rows in one table to values. The WHERE clause operates Steve Troxell is a Software
another table. In this case, you sim- just like the WHERE clause in the Engineer with TurboPower
ply omit the VALUES clause contain- SELECT statement and defines the Software where he is developing
ing the explicit values and replace rows to apply the change to. If you Delphi Client/Server applications
it with any legal SELECT statement omit the WHERE clause, the change using InterBase and Microsoft SQL
with the same number and type of will be applied to all rows in the Server for parent company Casino
columns that you are inserting. It’s table. Data Systems. Steve can be
difficult to illustrate this concept UPDATE can be used to set reached on CompuServe at
with the sample employee database columns with calculated values as 74071,2207
we’ve been using, so here is a
contrived example: ➤ Figure 11 (partial listing)

INSERT INTO shipped_orders SELECT * from customer


(order_num, amount)
CUST_NO CUSTOMER CONTACT_FIRST CONTACT_LAST
SELECT order_num, ======= ========================= =============== ===================
order_total FROM orders
1008 Anini Vacation Rentals Leilani Briggs
WHERE order_status =
1009 Max Max <null>
’shipped’; ...more rows...
1015 GeoTech Inc. K.M. Neppelenbroek
1016 Bigwig International <null> <null>
In this example, we are reading all

September 1995 The Delphi Magazine 17

You might also like