SQL

Home

Developing queries

  1. Build up a query according to the steps you think are necessary for the logical processing and write an appropriate clause for each step
    1. Write the FROM clause by deciding which table(s) the data will come from.
    2. Write the WHERE clause, first by identifying any join conditions if there is more than one table in the SELECT clause, and then by asking whether the rows should be restricted in any way. Terms like 'except', 'in', 'provided that', 'where', 'greater than', etc. Are pointers to possible predicates. Note that it can be helpful to test this clause (with the FROM clause) by adding SELECT * to give a query which you can run to check the results.
    3. Write the GROUP BY clause by checking whether the data needs to be grouped in any way. The need for set functions may be indicated by terms like 'total', 'average', 'number of', 'how many', 'maximum', etc. (Though remeember these terms may also be applied to the whole table without grouping), and then you need to find the grouping columns which may be indicated by terms like 'each', 'every' etc.
    4. Write the HAVING clause after checking whether the groups need restricting in any way. Predicates similar to thise identified in the WHERE clause may occur, used with either grouping columns or set functions noted for the GROUP BY clause.
    5. Write the SELECT clause by deciding what columns (names, functions, expressions) should appear in the final table.
  2. Gather the clauses together into a correctly organised query; for some queries you may have to resolve naming ambiguities by means of qualified column names or aliases.
  3. Run the query, if possible testing the query using data for which you know the result; if the test does not give you the results you expect, return to the first 2 stages.

To do: add composite queries to the above, SELECT FROM WHERE, SELECT FROM GROUP BY HAVING WHERE

Back to top     Back to Index     Home     Serious Stuff

© 2001. Copyright Sue Nethercott.