'SQL' frills!

Having a look at table structure and constraints

Check on SQL92 - how do we view a table description? Oracle version is desc.


(and "for update") Different implementations of SQL have divergent approaches to security. {check all of the following for SQL compliance/Oracle tainting} Most of the following commands assume that the person entering them has a "superuser" status on the system.

Creating a user

The command to create a new user is generally something like:

create user username identified by password;

This still doesn't allow the user (even though he/she exists) to talk to SQL. You need to do something like:

grant create session to username;

grant must also be used to provide resources that the user can utilise. Details are at present beyond the scope of this tutorial. {to update}. A user can also grant access to other users, allowing them to share tables that he/she owns. Privileges may be the right to simply read the table or view, or perform potentially damaging operations such as updates, deletes, or inserts. (Other privileges that may be granted on tables include things called alter, index and reference privileges).

Deleting all the information about a user

This is simply accomplished using:

drop user username cascade;

The cascade option is particularly nasty, deleting all the objects in the (now defunct) schema that belonged to the user.

Database administrators

These god-like creatures have a vast array of security options that they administer. We won't go into them all. The word any features prominently in many such commands.


Previously we mentioned that we cannot simply delete rows if this deletion would "orphan" rows in a dependent table (a table that references a column of the current table using foreign key). The sharp edged sword that allows us to perform this sweeping deletion (and also kills the orphans) is the use of the cascade constraints instruction. An example:

drop table tablename cascade constraints;

Simple and lethal.


{xref sql.htm} We've already briefly mentioned the constraint keyword. Here we flesh things out:

Static constraints

The commonly used not null is an example of a static constraint. We know how to invoke this constraint - we specify not null in the definition of the table. What we haven't yet learnt is how to modify the not null constraint on a table - add or remove this constraint. We use alter table, thus:

alter table tablename modify (
          colname1 NOT NULL,
          colname2 NULL,

where colname1 will acquire the NOT NULL constraint, and colname2 will lose it!

Another static constraint - the CHECK constraint

SQL can also check a whole host of other constraints, under the general heading of check constraints. These are implemented using the check clause, and example of which is:

create table tablename (
          colname1 char(4)
          check (
                    colname1 between 1 and 1234

In this rather artificial example, we ensure that the character string colname1 is numeric in the range 2 to 1233 inclusive.

check constraints are quite flexible - they can check ranges, equality, or use the in statement to select from a list of options, but cannot use subqueries or aggregate values in their definition. As with null above, alter table statements can apply new check constraints, and check constraints can be given their own names (something you should always apply rigorously). You can also combine individual checks within a constraint using the logical operators and, or and not.

Something to avoid

The command

alter table disable constraint constraint_name

will turn off constraints. The catch is that if you then abuse the data, and try and turn on the constraint again using alter table enable constraint constraint_name, the command will fail if even one data value violates the constraint!

Dynamic Constraints

We've also previously encountered a dynamic constraint - the keyword unique! You can deduce that the primary key constraint is also dynamic, as it depends on its argument being unique. Likewise, a foreign key is an example of a dynamic constraint. A recursive key is a dynamic constraint that 'turns back' and references the same table!

Copying from one table to another

We have encountered the insert statement. Did you know that it can be used to copy rows from one table into another one? Thus:

insert into tableA ( list of columns )
            select list of columns
            from tableB

It is conventional not to enclose the select statement in parenthesis! You are permitted to (for example) use a where clause in the select statement.

Aliases, constants and the like


Although aliases are used with incredible frequency in most SQL, they are for the most part tiresome and confusing conveniences. Choose your column and table names with caution (make them mnemonic), stick to the rules, and you'll rarely have to burden yourself with aliases. Consider the following:

select ForeName, Surname, IdNumber from tablename;

Now compare it with the following (which uses aliases:

select ForeName aforename, Surname asurn, IdNumber anid from tablename;

Not only is the above statement difficult to read, not only does it provide us with a host of new names that we have to remember and reconcile, but even worse, if we leave out a single comma, the whole select statement will be hideously mucked up!

Our rule is:

Use as few aliases as you can get away with (often, none) .. Rule #5

Note that it is also possible to create aliases for table names. For example, where we select from several tables, we had two tables with the same column name. Now, the sensible way of referring to the two columns is (for example) DrugRegimen.Dosing and DrugDosing.Dosing, but one could also, in the select statement create an alias for each table name. Guaranteed to confuse if used often enough.

One place where aliases are actually very useful is where you are making a view, and have a whole lot of bolshy users of that view who insist on certain peculiar names for the columns. Aliases make acceding to their unreasonable requests a piece of cake!


SQL aficionados will probably be very distressed that we still haven't covered constants in SQL! Most SQL manuals cover these on page 1.

We believe that programs should be used for what they're best at. Programs that manage databases using SQL should do just that. They shouldn't be used as statistical packages, or word processors. Our fervent hope is that sometime in the next several centuries, designers will catch onto this seemingly obvious concept, and stop burdening us with spacetime guzzling monster programs that try and do a bit of everything. Export your tables to a word processor, and do the formatting job properly, rather than messing around inserting laborious separators and rows of
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - es !

We'll even turn it into a rule:

Even if a hippo has been to Fred Astair for a hundred years,
it still won't be employed as a dancing instructor
.. Rule #6.

Okay, having got that off our chests, here's an example of how you use constants:

select col1, col2, 'blahblah' from table

This will provide us with an ugly "constant" column entitled 'BLAHBLAH and containing the value blahblah for each and every row. If you need a single quote, render it as two single quotes side by side - the first quote acts as an escape character for the second one. (But we know this)!

Secondary keys

Okay, we promised to tell you what a secondary key is. A secondary key is a datum that identifies records in a set that share the same property, that is, a subset. This is of some importance in hierarchical databases, but not in relational ones. Forget the term!


Related to constants (and often used with them) is the process of concatenation. All this means is joining up two strings, side by side. The main problem with concatenation is that it makes a mess of your nice ordered database columns (enough reason to avoid it). Here's an example:

select col1 || col2 || 'blahblah' from table

The output from this ugly thing will be rendered as lines without the usual column spacing, and every column juxtaposed to the next one. Okay, you can bung in spaces ' ' between ' ' each ' ' column. Hmm.

Null Values

A NULL in a database denotes (shock, horror!) a missing value. Such things have a way of happening.

Nulls pose the following problems:

There is only one rule for NULL values, and that is:

Avoid NULL values. Okay, you should also avoid anthrax and casual sex. .. Rule #7

If, however, you through some defect in your psychological makeup cannot do so (avoid the NULLs, that is) or you've inherited a database stuffed with NULLs, then you can do a variety of things:

Quick NULL fixes

If you know exactly what you're doing, you might want to take your data and in calculations use another value for NULL. This sort of approach should be taken with appropriate fear and trembling. Here's an example of the coalesce function that does the dirty deed, in this case replacing all NULLs in calculations with the value zero:

select avg ( coalesce (columname, 0)) from tablename;

You should only apply the above approach if you are sure that the substitution is appropriate, which is rarely the case! Note that different SQL dialects have different synonyms for coalesce - for example, Oracle uses nvl.

Even more contrary is to replace a known value with NULL ! SQL92 provides the nullif( columname, targetvalue) function to do so. Some SQL implementations lack this function, if not the functionality.

Data coercion, conversion and truncation, including dates

Data coercion

Most SQLs try to be helpful, "automatically" converting certain data types to others. For example if your SQL expects a number and encounters the string '345' it will use the corresponding numeric value. Likewise for dates. Most times this coercion does no harm.

Explicit conversions

Most SQLs come with a bundle of proprietary functions for converting one data type to another. Here are a few examples (from Oracle): {Here have a section on SQL92 conventions re dates, and how other SQLs ignore/abuse them}

Decode, Stats, Maths and String manipulation


One useful wrinkle of SQL is the ability to 'decode' a data value, replacing it with another value. The syntax is unfortunately a bit turgid and error prone:

            decode (
            'OD', 'once daily',
            'BD', 'twice daily',
            'TDS', 'three times a day',
            'QID', 'four times a day',
            'I am confused'
from DrugDosing;

The intent is obvious - go through the table Frequency and replace occurrences of the various codes (OD, BD, etc) with their English equivalents, defaulting to 'I am confused' if there is no match. A useful little function that shouldn't cause trouble if you remember to put in a default value, and only keep two items to a line when you write the code, as we did above.

Statistics and Maths

We have learned how to perform arithmetic on columns and the basic grouping functions that exist in SQL. Alas, not content with these, most vendors of SQL databases have added their own proprietary extensions, playing around with variances, standard deviations and so on.. Our comments above apply!

You will find functions that do:

String handling

We've previously talked about case conversion. Unfortunately, when it comes to complex string manipulation, each vendor again does his merry thing. We find:


{Here look at the value of these, and also why they're not part of core SQL}

More silliness (to examine!)

1. ((Hierarchical views (p536) ))

2. Better definition of relational calculus, relational algebra.

3. ((The force option with views (p517)))

4. ((Oracle snapshots (pty)))

5. [decode p87. DONE]

6. exists / not exists. p422. *****

7. ((Oracle (? SQL equiv) uid, sysdate, user, ))

8. Have a tiny note on the all keyword (redundant)

9. (eschew the oracle currval and nextval operators.)

10. ((Trees, Celko and hierarchical subqueries.))

11. SQL generating SQL. NB. ***

12. ((oracle space and storage directives!? (initial, next, minextents, maxextents, pctincrease)))

13. (Sharing using synonyms.)

14. Triggers, transaction logs. !!

15. Data scrubbing. **

Next - A worked example (to do) Home

Date of First Draft: 2001/11/11 Date of Last Update: 2001/-/- Web page author: jo@anaesthetist.com