ThePlace

Home ] Search ] Resources ] Site Map ] Contact Me ]
Dave's Information Technology Resource

Up ]

What are Databases? ] Relational Databases ] Data Modeling ] Designing and Implementing Databases ] Creating Database Applications ]

--- SQL - Querying Databases ---

 

The primary function of a databases is to support the retrieval and storage of information. 

Relational database management systems offer various tools for querying (retrieving) information:

bullet

Viewing one, some, or all fields from one or more tables and then Selecting ranges of data for retrieval.

bullet

Adding records to a table.

bullet

Changing records in a table.

bullet

Removing records from a table.

In addition, there are functions for creating tables and database structure.

 

Relational Algebra

In order to view data, there needs to be a process for identify "which" or "what" data you wish to retrieve. 

Since relational databases are composed of tables and fields, you can specify the values of fields that you wish to retrieve.

Relational algebra is used to correlate fields and the type of information to be retrieved.  These correlations include:

bullet

 =                the field is equal to the value, e.g. ‘lastname = “Hillman”’

bullet

 >, <            greater than, less than, e.g., ‘age  > 21’

bullet

 >=, <=       greater than or equal, less than equal, e.g., ‘weight <= 200’

bullet

 <>              not equal to, e.g., ‘sex <> “Male”’

bullet

 %               wildcard character, e.g., ‘lastname = “H%”’ retrieves lastname data starting with the letter “H”

bullet

 like             similar to, e.g., ‘lastname like “smith”’ retrieves lastname data such as “Smith”, “Smithy”, “SMITH”

bullet

 AND, OR, NOT                logical operators that combine conditions, e.g., ‘lastname = “Hillman” AND sex = “Male”’

Data Functions: Working with Selected Data

Many database management systems also allow you to apply various calculations and or computations to retrieved data including:

bullet

 Sum – add the value of all instances of a retrieved field

bullet

 Average – find the average value of returned data

bullet

 Count – how many data points retrieved

bullet

 Max and Min - get the maximum or minimum values of a field.

 

Structured Query Language - SQL

Structured Query Language (SQL) SQL is the ANSI (American National Standards Institute) standard relational database language used for managing objects, data, and security.  Many commercial database products use SQL syntax as a means to access and manage databases.

There are 6 basic statements in SQL:

  1. Select -- Retrieves columns and rows from a table or tables.

  2.  Insert -- Adds rows to a table.

  3. Update -- Updates columns in existing rows in a table.

  4. Delete -- Deletes rows from a table.

  5. Create -- Creates a new table.

  6. Select Into -- Creates new tables with data from an existing table.

 

The following sections describe the syntax for each of these statements.

Select

The select statement is used to retrieve data from one or more tables.  It can also be used to get information about data such as how many or an average.

Select — columns of data to be retrieved.

From — tables from which to retrieve rows

Where — criteria for returned data

Where operators include: =, >, <, >=, <=, <> (not equal) IN, BETWEEN..AND, LIKE

Group By — for aggregate queries, columns by which the data is to be grouped

Having — for aggregate queries, criteria that the aggregate value returned must have

Order By — sort order of the returned rows

The product or result of a SELECT statement is a table that contains the data specified in the SELECT statement.  In other words, the SELECT statement actually results in the creation of a set of records (sometimes called a recordset) consisting of fields based on the selection criteria.

The minimum number of records is: 0 - if no records are present or do not meet the criteria of the query, then the recordset is empty.

The minimum number of fields is: 1 - at least one field must be returned (this assumes at least one record is returned).

 

Examples of Select Statements:

bullet

SELECT * from employee;

bullet

Returns all the records from the table.

 

bullet

SELECT lastname, firstname, address, city, state, zip FROM employee WHERE state='MD' GROUP BY zip

bullet

The resulting recordset returns records where state is "MD" and then groups them by the zip field

 

Linking relationships can join tables.  For example:

bullet

 Two tables:

  1. employee (with studentid, lastname, firstname, address, etc..) -- the employee table has a field: employeeid

  2. project (projectid, emplyeeid) the project table has a field: employeeid

 

bullet

SELECT employee.lastname, employee.firstname FROM employee, project WHERE employee.employeeid = project.employeeid

bullet

This query joins two tables and provides the student names.

 

Using data functions such as count, avg, etc.:

bullet

SELECT COUNT(lastname) from employee;

bullet

This query returns a single record with one field that has the number or records based on the lastname field.

 

bullet

SELECT avg(salary) from employee;

bullet

This query returns a single record with one field that gives the average salary (all values of salary divided by the total number of records).

 

Insert

The insert statement is used to add data to a table.

Insert Into -- which table will have rows added

column list -- which columns will add data

Values (value list) -- values to be added to the table

Select -- returns rows to be added to the table

 

Example: INSERT INTO employee (lastname, firstname, address, city, state, zip) VALUES ('Smith', 'David', '111 Elm Street', 'Anycity', 'MD', '20872')

 

Update

The update statement is used to modify data already in the table.

Update — table to be updated

Set — columns to update and values

From — tables to be included in the update

Where — criteria to determine which columns will be updated

 

Example: UPDATE students SET address = '99 Elm St' WHERE lastname = 'Smith'

 

Delete

The delete statement is used to remove data from a table.

Delete From — specify table in which rows are to be deleted

Where — criteria for deletion

 

Example: DELETE FROM employee WHERE employeeid = 10

 

Create

The create statement is used to build new tables.

         Create Table — table to be created

column list — describes columns to be created in new table

 

Example: CREATE TABLE divisions (divisionid id NOT NULL , divisiondescription varchar (30) NULL )

 

Select Into

The select into statement is used to build new tables from existing tables.

         Select column list — columns to build the new table

Into — new table being created

From — table from which data is coming from

Where — criteria for data being selected

Group By — for aggregate queries, columns by which data is grouped

Having — for aggregate queries, criteria that must be met

Order By — sort order of returned rows

 

Example: SELECT lastname, firstname INTO localemployees FROM employee WHERE state = 'MD'

 

Some things to remember about using SQL...

bulletSQL is generally not case sensitive - but check with the particular implementation to be sure.
bulletAlways watch field types when constructing statements...
bullettext - enclosed in quotes/double quotes
bulletnumbers - none (usually)
bulletdate - #date#
bulletSQL statements are normally enclosed in double quotes when used in programs...
bullete.g.: "select lastname, firstname from members where userid = 3;"
bulletNote that text fields are enclosed in single quotes... "select lastname, firstname from members where lastname='Smith';"
bulletIn cases where a quote is included in the field, use a series of two single quotes...
bullet" select lastname, firstname from members where lastname='O''Reilly';"
bulletDates are stored with a single quote and #, e.g., '#10/12/99#'
bulletWhen constructing SQL statements, be very careful of where clauses, especially in update and delete statements.
bulletUse dot notation in join table situations to identify which tables and fields...e.g., members.lastname
bulletTest in the database application prior to running the query.
bulletLogical operators include AND, OR, NOT
bulletAlgebra Operators: =, <> (not equal), > , < , Like (for comparisons)
bulletUse the % for wild cards.
bulletSQL may be a standard, but there are differences in how it is implemented by various database programs.

Key words and SQL

As SQL can be used in a programming environment, there are certain words you should avoid using in SQL and in the naming of tables and data:

From the SQL 1992 standard and appendices:

AFTER, ALIAS, ASYNC, BEFORE, BOOLEAN, BREADTH,
COMPLETION, CALL, CYCLE, DATA, DEPTH, DICTIONARY, EACH, ELSEIF,
EQUALS, GENERAL, IF, IGNORE, LEAVE, LESS, LIMIT, LOOP, MODIFY,
NEW, NONE, OBJECT, OFF, OID, OLD, OPERATION, OPERATORS, OTHERS,
PARAMETERS, PENDANT, PREORDER, PRIVATE, PROTECTED, RECURSIVE, REF,
REFERENCING, REPLACE, RESIGNAL, RETURN, RETURNS, ROLE, ROUTINE,
ROW, SAVEPOINT, SEARCH, SENSITIVE, SEQUENCE, SIGNAL, SIMILAR,
SQLEXCEPTION, SQLWARNING, STRUCTURE, TEST, THERE, TRIGGER, TYPE,
UNDER, VARIABLE, VIRTUAL, VISIBLE, WAIT, WHILE, WITHOUT

also...

ABSOLUTE, ACTION, ADD, ALLOCATE, ALTER, ARE, ASSERTION, AT, BETWEEN,
BIT, BIT_LENGTH, BOTH, CASCADE, CASCADED, CASE, CAST, CATALOG,
CHAR_LENGTH, CHARACTER_LENGTH, COALESCE, COLLATE, COLLATION, COLUMN,
CONNECT, CONNECTION, CONSTRAINT, CONSTRAINTS, CONVERT, CORRESPONDING,
CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, CURRENT_USER,
DATE, DAY, DEALLOCATE, DEFERRABLE, DEFERRED, DESCRIBE, DESCRIPTOR,
DIAGNOSTICS, DISCONNECT, DOMAIN, DROP, ELSE, END-EXEC, EXCEPT,
EXCEPTION, EXECUTE, EXTERNAL, EXTRACT, FALSE, FIRST, FULL, GET,
GLOBAL, HOUR, IDENTITY, IMMEDIATE, INITIALLY, INNER, INPUT,
INSENSITIVE, INTERSECT, INTERVAL, ISOLATION, JOIN, LAST, LEADING,
LEFT, LEVEL, LOCAL, LOWER, MATCH, MINUTE, MONTH, NAMES, NATIONAL,
NATURAL, NCHAR, NEXT, NO, NULLIF, OCTET_LENGTH, ONLY, OUTER, OUTPUT,
OVERLAPS, PAD, PARTIAL, POSITION, PREPARE, PRESERVE, PRIOR, READ,
RELATIVE, RESTRICT, REVOKE, RIGHT, ROWS, SCROLL, SECOND, SESSION,
SESSION_USER, SIZE, SPACE, SQLSTATE, SUBSTRING, SYSTEM_USER,
TEMPORARY, THEN, TIME, TIMESTAMP, TIMEZONE_HOUR, TIMEZONE_MINUTE,
TRAILING, TRANSACTION, TRANSLATE, TRANSLATION, TRIM, TRUE, UNKNOWN,
UPPER, USAGE, USING, VALUE, VARCHAR, VARYING, WHEN, WRITE, YEAR, ZONE

and...

ACTION, ACTOR, AFTER, ALIAS, ASYNC, ATTRIBUTES, BEFORE, BOOLEAN,
BREADTH, COMPLETION, CURRENT_PATH, CYCLE, DATA, DEPTH, DESTROY,
DICTIONARY, EACH, ELEMENT, ELSEIF, EQUALS, FACTOR, GENERAL, HOLD,
IGNORE, INSTEAD, LESS, LIMIT, LIST, MODIFY, NEW, NEW_TABLE, NO,
NONE, OFF, OID, OLD, OLD_TABLE, OPERATION, OPERATOR, OPERATORS,
PARAMETERS, PATH, PENDANT, POSTFIX, PREFIX, PREORDER, PRIVATE,
PROTECTED, RECURSIVE, REFERENCING, REPLACE, ROLE, ROUTINE, ROW,
SAVEPOINT, SEARCH, SENSITIVE, SEQUENCE, SESSION, SIMILAR, SPACE,
SQLEXCEPTION, SQLWARNING, START, STATE, STRUCTURE, SYMBOL, TERM,
TEST, THERE, TRIGGER, TYPE, UNDER, VARIABLE, VIRTUAL, VISIBLE,
WAIT, WITHOUT

and..

CALL, DO, ELSEIF, EXCEPTION, IF, LEAVE, LOOP, OTHERS, RESIGNAL,
RETURN, RETURNS, SIGNAL, TUPLE, WHILE

Please note that this is not a complete list AND you can get away with using many of the "key words" listed above.

 

 

Home ] Up ] Computer Architecture ] Programming Bootcamp ] Visual BasicS ] Web Basics ] Web Multimedia ] Web Programming ] Advanced Web Topics ] Developing Web Sites ] XML Technology ] Web Glossary ]

Copyright © 1999 - 2005 
ThePlace - Written and Sponsored by Dave Hillman