delphi - getting started with sql - part 1

Upload: juanmdq

Post on 14-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    1/6

    Delphi incorporates some veryuseful database componentsthat make developing databaseapplications a breeze. And becauseDelphi ships with a local version ofBorlands InterBase databaseserver, a great number of applica-tion developers now have an easy,inexpensive means of exploring theworld of Client/Server technology

    right at their fingertips. For thesereasons, many fledgling Delphiprogrammers may be introducedto Structured Query Language(SQL) for the first time. This articleis intended to introduce you to theprincipal SQL data accessstatements: SELECT, INSERT,UPDATE and DELETE. These are theworkhorses of SQL and by the endof this article youll be able toeffectively use SQL to accomplish awide variety of tasks. Well

    continue to expand our knowledgeof SQL in the next issue.

    All of the examples in this articleuse the sample InterBase databaseEMPLOYEE.GDB that ships withDelphi. You may find it helpful toconnect to this database throughthe Windows Interactive SQL(ISQL) program that ships withDelphi and try the examples as youread about them. Its also handy tobe able to experiment as ideas

    come to you while reading the text.This database is located in the\ IBLOCAL\EXAMPLES directory ifyou installed Delphi with thedefault directories. We will beadding information in thisdatabase so you may want to makea copy of the EMPLOYEE.GDB fileand work with the copy only.

    Using ISQLTo use Windows ISQL, start theISQL program from the Delphiprogram group. From the Filemenu, select Connect to Database.In theDatabase Connectdialog box,

    Su r vi vi n g Cl i en t / Ser ver :

    Gett ing Started With SQL Part 1by Stev e Trox e l l

    make sure youve selected LocalServer, enter the path and filenamefor the EMPLOYEE.GDB database,enter SYSDBA for the user name, andenter masterkey for the password(make sure you enter the passwordin lower case). This is the defaultsystem administrator login forInterBase databases.

    Using the ISQL program is

    simple: type in the SQL statementyou want to execute in the SQLStatement window and click theRunbutton to execute the statement.The results of your statement willappear in the ISQL Outputwindow.Once you run an SQL statement, itdisappears from the SQL Statementwindow. If you want to run it again(and perhaps make small changesto it), you can retrieve anyprevious SQL statement by clickingthe Previousbutton.

    SQL Preliminaries

    Before we get started, lets look ata few of the ground rules for work-ing with SQL. First, three newterms: the familiar structures offile, record, and field are calledtable, row, and column in relational

    databases. A database is acollection of tables; in Paradoxeach .DB file represents a table, inInterBase each .GDB file representsa database and the tables aremanaged internally.

    Second, lets take a look at thesyntax of a SQL statement. Atypical SQL statement might be:

    SELECT name, address

    FROM customers;

    SQL itself is case-insensitive, but inthis article SQL keywords areshown in all uppercase and tablenames, column names, etc. areshown in all lower case. SQL gener-ally requires a semi-colon at theend of each statement, but incertain tools (such as ISQL) itsoptional.

    Third, you can break an SQL

    statement across multiple lines bypressing RETURN anywhere you canlegally place a space in thestatement.

    Finally, you can enclose literalstrings with single quotes ordouble quotes. Well use singlequotes here.

    Int roducing The Column...

    Delphi users seem to have settled down into several groups: firstlyoccasional programmers or first-time programmers ( attracted by

    Delphis ease of use), secondly professional full-time developers doinggeneral Windows application building (enthralled by Delphis amazingproductivity) and thirdly those putting together Client/Server systems(impressed by Delphis robustness and power). This column is aimedat the third group, but especially those who may be dipping a toe intothe waters of Client/Server for the first time.

    Steve is involved in developing a variety of Client/Server systems inhis work at TurboPower Software, using different server databases, andwe are looking forward to learning from his experience over the months.As well as SQL an essential part of the Client/Server developers skillset Steve plans to cover a variety of other topics and also provide lots

    of hints and helps along the way. If there are things which you needsome help with, why not drop us a line and let us know!

    12 The Delphi M agazine Issue 3

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    2/6

    Reading Row s

    SELECT is SQLs data retrievalstatement and is probably themost frequently used SQLstatement. The basic form of theSELECT statement is:

    SELECT

    FROM ;

    For example, try the followingSELECT statement in ISQL (theresults are shown in Figure 1):

    SELECT last_name, first_name

    FROM employee;

    We selected the last_name andfirst_name columns from theemployee table. By default, SELECTreturns all the rows from the table,but only shows data for thecolumns we requested (called theselect list). If you wanted to see allof the columns in a table, it wouldbe cumbersome to enter the nameof every column in the SELECTstatement, so SQL provides aconvenient shortcut: an asteriskcan be used to indicateall columns.Try the following in ISQL:

    SELECT * FROM employee;

    Computed Columns

    You can also show calculatedresults with a SELECT statement. Inthis case, you simply provide theexpression used to make the calcu-lation in place of a column name inthe select list. The example belowestimates the monthly earnings ofeach employee:

    SELECT last_name, salary / 12

    FROM employee;

    Take a look at the results of thisstatement in Figure 2. Notice thatthere isnt a column name for thesalary calculation. Thats becausethe data shown doesnt exist as anamed column in the table weselected from. A column without aname is just not a very useful thingto have, so we need to assign analias to the column (see Figure 3):

    SELECT last_name, salary / 12

    AS monthly_salary

    FROM employee;

    SELECT last_name, salary / 12 FROM employee;

    LAST_NAME==================== ======================

    Nelson 8825Young 8125Lambert 8562.5Johnson 5386.25Forest 6255Weston 7191.078125

    Figure 2 (part ial l ist in g o f row s)

    SELECT last_name, first_name FROM employee;

    LAST_NAME FIRST_NAME==================== ===============

    Nelson RobertYoung BruceLambert KimJohnson LeslieForest PhilWeston K. J.

    Figure 1 (part ial l ist in g o f row s)

    ISQL in act io n

    Theres no reason why we couldntdo the same thing to a regularnamed column as well, if wewanted to reference the data bysomething other than its definedcolumn name. You might need todo this if you were selecting datafrom two or more tables that usethe same column name.

    Select ing Subsets Of Row s

    The selects weve looked at so farreturn all the rows in the table.

    Many times youre not interestedin wading through all of the rows toget the information you want.Usually all you want is a specificrow, or a set of rows withsomething in common. You use theWHERE clause to restrict the rowsreturned by SELECT.

    For example, the following SQLstatement selects all theemployees in the SoftwareDevelopment department (seeFigure 4):

    Septem ber 1995 The Delphi M agazine 13

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    3/6

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    4/6

    Like WHERE, the columns definedin ORDER BY do not have to appearin the select list. This is true forInterBase but may not apply toother SQL databases.

    You can define the sort sequencefor each sort column by adding theASC (ascending) or DESC (descend-

    ing) keyword after the columnname in theORDER BY clause. Hereshow you would make the queryabove return a list of sales ordersin order of decreasing amount:

    SELECT cust_no, order_status,

    total_value

    FROM sales

    ORDER BY total_value DESC;

    As an alternative to specifying thename of the column to sort on, youcan specify the number of thecolumn from the select list. This isuseful if youve included anunaliased computed column in theselect list. For example, supposeyou wanted a list of employees inorder by monthly salary (seeFigure 8):

    SELECT full_name, salary / 12

    FROM employee

    ORDER BY 2;

    Here the 2 in the ORDER BY meansorder by the second column in theselect list; that is, by thecomputed column salary / 12.

    If you use both aWHEREclause andan ORDER BY clause in the sameselect statement, the WHERE clausemust appear before the ORDER BYclause, as in the following example:

    SELECT * FROM employee

    WHERE dept_no = 621ORDER BY phone_ext;

    Selecting FromM ult iple Tables (Joins)One of the most powerful featuresof theSELECTstatement (and of SQLitself) is the ease with which youcan combine data from multipletables into one informative view.

    For example, suppose you wanta roster of all employees bydepartment. Employee names arestored in the employee table anddepartment names are stored inthe department table, so youll

    have to combine this informationsomehow into a single report. Thisis where the concept of a joincomes into the picture.

    A join can occur between two ormore tables where each pair oftables can be linked by a commonfield.

    For example, departments areidentified by thedept_no column inboth the employee table and

    department table, so this columncan be used to link the two tablesin a join. In SQL you can use theWHEREclause to specify the link fieldfor a join between two tables. Theselect statement below producesthe employee roster we want:

    SELECT full_name, department

    FROM employee, department

    WHERE employee.dept_no =

    department.dept_no

    ORDER BY department;

    This means show the selectedcolumns from the given tables and

    combine the rows such thatdept_no in the employee tablematches dept_no in the departmenttable (in this case the departmenttable also happens to contain acolumn called department). Take alook at the results shown in Figure9. The result of a join select isindistinguishable from a singletable select.

    The WHERE clause defines the

    association between the twotables. The linking columns are notrequired to have the same name,but they must be compatible datatypes. As an alternative to theWHEREclause, you can also define a join intheFROM clause as follows:

    SELECT full_name, department

    FROM employee JOIN department

    ON employee.dept_no =

    department.dept_no

    ORDER BY department;

    You can join more than two tablesby simply ANDing the join

    SELECT cust_no, order_status, total_valueFROM salesORDER BY total_value;

    CUST_NO ORDER_STATUS TOTAL_VALUE=========== ============ ===========

    1003 waiting 0.001001 shipped 0.001006 shipped 47.501014 shipped 100.021010 shipped 210.00

    Figure 7 (part ial l ist in g o f row s)

    SELECT full_name, salary / 12 FROM employee ORDER BY 2;

    FULL_NAME===================================== ======================

    Bennet, Ann 1911.25Brown, Kelly 2250OBrien, Sue Anne 2606.25Guckenheimer, Mark 2666.666666666667Reeves, Roger 2801.71875

    Figure 8 (part ial l ist in g o f row s)

    SELECT customer, address_line1 FROM customerWHERE address_line1 LIKE %Newbury%;

    CUSTOMER ADDRESS_LINE1========================= ==============================

    Buttle, Griffith and Co. 2300 Newbury Street

    Figu re 6

    Septem ber 1995 The Delphi M agazine 15

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    5/6

    expressions together in the WHEREclause (or concatenating JOINs inthe FROM clause). The linking col-umns do not have to be the samefor all tables in the join. For exam-ple, to get a list of all employeesassigned to a project and the nameof the projects they are assigned

    to, you must join the employee,employee_project, and projecttables:

    SELECT full_name, proj_id,

    proj_name

    FROM employee,

    employee_project, project

    WHERE employee.emp_no =

    employee_project.emp_no

    AND

    employee_project.proj_id =

    project.proj_id

    ORDER BY full_name;

    You can see the results in Figure 10.One improvement we could

    make is to reduce the bulk of thisstatement a little by assigningaliases to the tables just as weassigned aliases to columnspreviously. We do this in the samefashion by following the actualtable name with its alias, howeverwe do not use the AS keyword in

    between. Were going to redefinetheemployee,employee_projectandproject tables to have the aliasesa,b and c respectively. So our finalselect statement now looks like:

    SELECT full_name, proj_id,

    proj_name

    FROM employee a,

    employee_project b,

    project c

    WHERE a.emp_no = b.emp_no

    AND b.proj_id = c.proj_idORDER BY full_name;

    Sum ming Up SELECT

    SELECT is where most of the powerof SQL lies. There are even moreclauses and functionality to SELECTthan were covered here, so checkyour manual. This was meant justto show you the basic nuts-and-bolts needed to do anything reallyuseful with SELECT.

    In the next issue well cover a lotmore onSELECT, but now that wevegot a handle on looking at the data,well turn to altering the data.

    Comm itting Your Work

    One of the key characteristics ofSQL is that when you add or modify

    data in the SQL table, the changesare not permanently recorded inthe table and other users of thedatabase will not see them, untilyou commit them. In this way youcan work with the data as much asyou like until you get it just the wayyou want it and then commit itpermanently to the database.

    In ISQL you commit yourchanges by selecting Commit Workfrom theFile menu. If you want to

    undo your modifications, you canselect Rollback Work from the Filemenu. This will rollback all thechanges youve made since the lasttime you committed your work.Think of this as a refresh of the datayoure working with.

    Be careful if you decide toexperiment with these datamodification statements outsidethe examples given. The tutorialdatabase provided with InterBasedefines some data validation andreferential integrity constraintsthat may give you errors if youdont modify the data just right

    (this is yet another boon of SQL byhelping preserve data integritythrough automatic means).

    Adding New Row s

    We use theINSERT statement to adda new row to a table.INSERTexpectsus to enumerate the values of eachcolumn in the table for the newrow.

    For example, the country tableidentifies the currency used in aparticular country and containstwo columns: country andcurrency. To add a new country row

    in this table we would use:

    INSERT INTO country

    VALUES (SteveLand,

    Twinkies);

    In this case Twinkies are the formof currency in SteveLand. Tryentering this statement into ISQLand then select all the rows fromcountry to see the result.

    The data values must appear inthe same order as the columns aredefined; the first value given will beinserted into the first column, thesecond value into the second

    SELECT full_name, proj_id, proj_nameFROM employee, employee_project, projectWHERE employee.emp_no = employee_project.emp_no ANDemployee_project.proj_id = project.proj_id

    ORDER BY full_name;

    FULL_NAME PROJ_ID PROJ_NAME===================================== ======= ====================

    Baldwin, Janet MKTPR Marketing project 3Bender, Oliver H. MKTPR Marketing project 3Bishop, Dana VBASE Video DatabaseBurbank, Jennifer M. VBASE Video DatabaseBurbank, Jennifer M. MAPDB MapBrowser portFisher, Pete GUIDE AutoMapFisher, Pete DGPII DigiPizza

    Figure 10 (part ial l ist ing of row s)

    SELECT full_name, department FROM employee, departmentWHERE employee.dept_no = department.dept_noORDER BY department;

    FULL_NAME DEPARTMENT===================================== =========================

    OBrien, Sue Anne Consumer Electronics Div.Cook, Kevin Consumer Electronics Div.Lee, Terri Corporate HeadquartersBender, Oliver H. Corporate Headquarters

    Williams, Randy Customer ServicesMontgomery, John Customer Services

    Figure 9 (part ial l ist ing of row s)

    16 The Delphi M agazine Issue 3

  • 7/30/2019 Delphi - Getting Started With SQL - Part 1

    6/6

    column, and so on. Alternatively,you can enter the values in anyorder you like as long as youspecify the column names after thetable name. The data values mustthen be in the order of the columnsas given. For example:

    INSERT INTO country (currency,country)

    VALUES (Clams,

    Troxellvania);

    Using this same syntax you caninsert data into only certaincolumns instead of all of them. Anycolumns not specifically includedin the INSERT receive a null value.Try this in ISQL and then select allrows to see what happens:

    INSERT INTO customer (customer)

    VALUES

    (Bigwig International);

    The results of this statement areshown in Figure 11. Notice that thecustomer column was set as wespecified, and all the other col-umns except cust_no were set tonull.Cust_nowas set to a new valuebecause of two advanced conceptscalled triggersand generators; con-

    cepts that are outside the scope ofthis article, but well cover them ina future issue.

    Copying Rows

    It is possible to combine theINSERTandSELECT statements to allow youto copy specific columns fromexisting rows in one table toanother table. In this case, you sim-ply omit the VALUES clause contain-ing the explicit values and replace

    it with any legal SELECT statementwith the same number and type ofcolumns that you are inserting. Itsdifficult to illustrate this conceptwith the sample employee databaseweve been using, so here is acontrived example:

    INSERT INTO shipped_orders

    (order_num, amount)

    SELECT order_num,

    order_total FROM orders

    WHERE order_status =

    shipped;

    In this example, we are reading all

    the rows from theorders table thathave a status ofshipped. For eachrow we find, we are inserting a rowinto the shipped_orders table thatconsists of the order_num and or-der_total columns fromorders (re-alistically, we would probablydelete these rows from orders after

    weve copied them). If there areany additional columns inshipped_orders, they default to nullsince we did not provide a value forthem. Notice that the columnnames in the read table do not haveto match the column names in thewrite table. We only need to havethe same number of columns andof the same data type.

    Changing Row s

    Now that we have a new customer,lets add some useful information.To change the value of a columnwithin an existing row we use theUPDATE statement. Lets add J oeJohnson as the contact for our newcustomer. Try the following in ISQLand examine the results:

    UPDATE customer

    SET contact_first = Joe,

    contact_last = Johnson

    WHERE customer =

    Bigwig International;

    (Note: Bigwig International mustbe spelled and cased exactly as youoriginally entered it in the INSERTstatement previously).

    The SET clause specifies a list ofcolumns to modify and their newvalues. The WHERE clause operatesjust like the WHERE clause in theSELECT statement and defines therows to apply the change to. If you

    omit the WHERE clause, the changewill be applied to all rows in thetable.

    UPDATE can be used to setcolumns with calculated values as

    well. If you were in a generousmood and wanted to doubleeverybodys salary, you could try:

    UPDATE employee

    SET salary = salary * 2;

    Removing Row s

    Sooner or later, youll need toremove some of the data from atable. To delete rows we use theDELETE statement. DELETE simplyuses a WHERE clause to identify therows to delete from a given table.

    Lets say our company isdownsizing and we now need toremove the Software Developmentdepartment from the departmenttable. Try the following in ISQL andthen select all rows from the tableto see the results:

    DELETE FROM department

    WHERE dept_no = 621

    If the WHERE clause is omitted, thenall of the rows in the table aredeleted.

    Conclusion

    There you have it: the real meat ofSQL. Weve covered the principalstatements of SQL and with these

    you can perform a great deal of thecommon tasks of relationaldatabases. In the next issue wellcover some more features ofSELECTthat simplify creating reports fromSQL data.

    Steve Troxell is a Soft w a re

    Engineer w ith TurboPo w er

    Sof tw a re whe re he is developing

    Delph i Clien t/Server a pplicat ions

    using Inte rBase an d Microsof t SQLServer for pa rent compa ny Casino

    Dat a System s. Steve can be

    reached on CompuServe at

    74071,2207

    SELECT * from customer

    CUST_NO CUSTOMER CONTACT_FIRST CONTACT_LAST======= ========================= =============== ===================

    1008 Anini Vacation Rentals Leilani Briggs

    1009 Max Max ...more rows...1015 GeoTech Inc. K.M. Neppelenbroek1016 Bigwig International

    Figu re 11 (part ial list ing )

    Septem ber 1995 The Delphi M agazine 17