Structured Query Language/SELECT: Fundamentals

The SELECT command retrieves data from one or more tables or views. It generally consists of the following language elements:

With the exception of the first two elements all others are optional. The sequence of language elements is mandatory. At certain places within the command there may start new SELECT commands - in a recursive manner.

Projection (specify resulting columns)
In the projection part of the SELECT command, you specify a list of columns, operations working on columns, functions, fixed values, or new SELECT commands.

The DBMS will retrieve ten rows, each of which consists of four columns.

We can mix the sequence of columns in any order or retrieve them several times.

The asterisk '*' is an abbreviation for the list of all columns.

For numeric columns, we can apply the usual numeric operators +, -, * and /. There are also many predefined functions depending on the data type: power, sqrt, modulo, string functions, date functions.

Uniqueness via keyword DISTINCT
It is possible to compact the result in the sense of unique values by using the keyword DISTINCT. In this case, all resulting rows, which would be identical, will be compressed to one row. In other words: duplicates are eliminated - just like in set theory.

Aliases for Column names
Sometimes we want to give resulting columns more descriptive names. We can do so by choosing an alias within the projection. This alias is the new name within the result set. GUIs show the alias as the column label.

Functions
There are predefined functions for use in projections (and at some other positions). The most frequently used are:
 * count( |'*'): Counts the number of resulting rows.
 * max: The highest value in of the resultset. Also applicable on strings.
 * min: The lowest value in of the resultset. Also applicable on strings.
 * sum: The sum of all values in a numeric column.
 * avg: The average of a numeric column.
 * concat(, ): The concatenation of two columns. Alternatively the function may be expressed by the '||' operator:  || 

Standard SQL and every DBMS offers many more functions.

We must differentiate between those functions which return one value per row like concat and those which return only one row per complete resultset like max. The former one may be mixed in any combination with column names, as shown in the very first example of this page. With the later ones, there exists a problem: If we mix them with a regular column name, the DBMS recognises a contradiction in the query. On the one hand it should retrieve precisely one value (in one row), and on the other hand, it should retrieve a lot of values (in a lot of rows). The reaction of DBMS differs from vendor to vendor. Some throw an error message at runtime - in accordance with the SQL standard -, others deliver suspicious results.

SELECT within SELECT
If we really want to see the result of a result-set-oriented-function in combination with columns of more than one row, we can start a very new SELECT on a location where - in simple cases - a column name occurs. This second SELECT is an absolutely independent command. Be careful: It will be executed for every resulting row of the first SELECT!

Table Names
The Keyword FROM is used to specify the table on which the command will work. This table name can be used as an identifier. In the first simple examples prefixing column names with the table name identifier can be used but isn't required. In the later more complex command, the table name identifier is a needed feature.

Restriction (specify resulting rows)
In the WHERE clause, we specify some 'search conditions' which are among the named table(s) or view(s). The evaluation of this criteria is - mostly - one of the first things during the execution of a SELECT command. Before any row can be sorted or displayed, it must meet the conditions in the clause.

If we omit the clause, all rows of the table are retrieved. Else the number of rows will be reduced according to the specified criteria. If we specify 'weight < 70', for example, only those rows are retrieved where the weight column stores a value less than 70. The restrictions act on rows of tables by evaluating column values (sometimes they act on other things like the existence of rows, but for the moment we focus on basic principles). As a result, we can imagine that the evaluation of the 'where clause' produces a list of rows. This list of rows will be processed in further steps like sorting, grouping, or displaying certain columns (projection).

Comparisons
We compare variables, constant values, and results of function calls with each other in the same way as we would do in different programming languages. The only difference is that we use column names instead of variables. The comparison operators must match the given data types they have to operate on. The result of the comparison is a boolean value. If it is 'true', the according row will be processed furthermore. Some examples:
 * 'weight = 70' compares the column 'weight' with the constant value '70' whether the column is equal to the constant value.
 * '70 = weight': same as before.
 * 'firstname = lastname' compares two columns - each of the same row - for equality. Names like 'Frederic Frederic' evaluate to true.
 * 'firstname < lastname' is a fair comparison of two columns according to the lexical order of strings.
 * 'LENGTH(firstname) < 5' compares the result of a function call to the constant value '5'. The function LENGTH operates on strings and returns a number.

Boolean Logic
Often we want to specify more than a single search criterion, e.g., are there people born in San Francisco with lastname Baker? To do this, we specify every necessary comparison independent from the next one and join them together with the boolean operators AND respectively OR.

The result of a comparison is a boolean. It may be toggled between 'true' and 'false' by the unary operator NOT.

The precedence of comparisons and boolean logic is as follows:
 * all comparisons
 * NOT operator
 * AND operator
 * OR operator

Two abbreviations

Sometimes we shorten the syntax by using the BETWEEN keyword. It defines a lower and upper limit and is primarily used for numeric and date values, but also applicable to strings.

For the comparison of a column or function with several values, we can use the short IN expression.

FETCH: Pick and Choose certain Rows
Sometimes we are not interested in all resulting rows, e.g.: we may want to see only the first 3 or 10 rows. This can be achieved with the OFFSET and FETCH clauses. OFFSET specifies the number of rows to be skipped (counting from the beginning of the result set), and FETCH specifies the number of rows, after which the delivery of rows shall stop.

Please notice that the OFFSET and FETCH clauses are separate parts of the SELECT command. Some implementations handle this functionality as part of the WHERE clause or with different keywords (ROWNUM, START, SKIP, LIMIT).

The functionality of OFFSET and FETCH can be achieved likewise by window functions with their more general syntax.

Grouping
We will offer the GROUP BY clause in combination with the HAVING clause in a later chapter.

Sorting
The DBMS is free to deliver the resulting rows in an arbitrary order. Rows may be returned in the order of the Primary Key, in the chronological order they are stored into the database, in the order of a B-tree organized internal key, or even in random order. Concerning the sequence of delivered rows, the DBMS may do what it wants to do. Don't expect anything.

If we expect a particular order of rows, we must express our wishes explicitly. We can do this in the ORDER BY clause. There we specify a list of column names in combination with an option for ascending or descending sorting.

In the above result, there are two rows with identical values in the column weight. As this situation leads to random results, we have the possibility to specify more columns. These following columns are processed only for those rows with identical values in all previous columns.

In the ORDER BY clause, we can specify any column of the processed table. We are not limited to the ones which are returned by the projection.

Combine the Language Elements
Only the first two elements of the SELECT command are mandatory: the part up to the first table (or view) name. All others are optional. If we also specify the optional ones, their predetermined sequence must be kept in mind. But they are combinable according to our needs.

Further Information
There is more information about the additional options for the SELECT command.
 * Join Operation
 * Grouping
 * IS NULL Predicate
 * Predefined Functions
 * Set Operations
 * Case Expression
 * Like Predicate
 * Subquery

Exercises
Show hobbyname and remark from the hobby table.

Show hobbyname and remark from the hobby table. Order the result by hobbyname.

Show hobbyname and remark from the hobby table. Choose 'Hobby' as first columnname and 'Short_Description_of_Hobby' as second columnname.

Show firstname and lastname of persons born in San Francisco.

Show all information items of persons with lastname 'de Winter'.

How many rows are stored in the contact table?

How many E-Mails are stored in the contact table?

What is the mean weight of persons born in San Francisco?

Find persons born after 1979-12-31, which weigh more than / less than 50 kg.

Find persons born in Birmingham, Mumbai, Shanghai or Athens in the order of their firstname.

Find persons born in Birmingham, Mumbai, Shanghai or Athens within the 21. century.

Find persons born between Dallas and Richland ('between' not in the sense of a geographic area but of the lexical order of citynames)

Which kind of contacts are stored in the contact table? (Only one row per value.)

How many different kind of contacts are stored in the contact table? (Hint: Count the rows of above query.)

Show contact_type, contact_value and a string of the form 'total number of contacts: ', where  is the quantity of all existing contacts.