INFORMIX
Informix Guide to SQL: Tutorial
Chapter 2: Composing Simple SELECT Statements
Home Contents Index Master Index New Book

Single-Table SELECT Statements

You can query a single table in a database in many ways. You can tailor a SELECT statement to perform the following actions:

  • Retrieve all or specific columns
  • Retrieve all or specific rows
  • Perform computations or other functions on the retrieved data
  • Order the data in various ways

Selecting All Columns and Rows

The most basic SELECT statement contains only the two required clauses, SELECT and FROM.

Using the Asterisk Symbol (*)

Query 2-5a specifies all the columns in the manufact table in a select list. A select list is a list of the column names or expressions that you want to project from a table.

Query 2-5a

Query 2-5b uses the wildcard asterisk symbol (*), which is shorthand for the select list. The * represents the names of all the columns in the table. You can use the asterisk symbol (*) when you want all the columns, in their defined order.

Query 2-5b

Query 2-5a and Query 2-5b are equivalent and display the same results; that is, a list of every column and row in the manufact table. Query Result 2-5 shows the results as they would appear on a DB-Access or SQL Editor screen.

Query Result 2-5

Reordering the Columns

Query 2-6 shows how you can change the order in which the columns are listed by changing their order in your select list.

Query 2-6

Query Result 2-6 includes the same columns as the previous query result, but because the columns are specified in a different order, the display is also different.

Query Result 2-6

Sorting the Rows

You can add an ORDER BY clause to your SELECT statement to direct the system to sort the data in a specific order.You must include the columns that you want to use in the ORDER BY clause in the select list either explicitly or implicitly.

An explicit select list, shown in Query 2-7a, includes all the column names that you want to retrieve.

Query 2-7a

An implicit select list uses the asterisk symbol (*), as Query 2-7b shows.

Query 2-7b

Query 2-7a and Query 2-7b produce the same display. Query Result 2-7 shows a list of every column and row in the manufact table, in order of
lead_time.

Query Result 2-7

Ascending Order
The retrieved data is sorted and displayed, by default, in ascending order. Ascending order is uppercase A to lowercase z for CHARACTER data types, and lowest to highest value for numeric data types. DATE and DATETIME data is sorted from earliest to latest, and INTERVAL data is ordered from shortest to longest span of time.

Descending Order
Descending order is the opposite of ascending order, from lowercase z to uppercase A for character types and highest to lowest for numeric data types. DATE and DATETIME data is sorted from latest to earliest, and INTERVAL data is ordered from longest to shortest span of time. Query 2-8 shows an example of descending order.

Query 2-8

The keyword DESC following a column name causes the retrieved data to be sorted in descending order, as Query Result 2-8 shows.

Query Result 2-8

You can specify any column (except CLOB, BLOB, TEXT, or BYTE) in the ORDER BY clause, and the database server sorts the data based on the values in that column.

Sorting on Multiple Columns
You can also ORDER BY two or more columns, creating a nested sort. The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence.

Query 2-9 and Query 2-10 and corresponding query results show nested sorts. To modify the order in which selected data is displayed, change the order of the two columns that are named in the ORDER BY clause.

Query 2-9

In Query Result 2-9, the manu_code column data appears in alphabetical order and, within each set of rows with the same manu_code (for example, ANZ, HRO), the unit_price is listed in ascending order.

Query Result 2-9

Query 2-10 shows the reversed order of the columns in the ORDER BY clause.

Query 2-10

In Query Result 2-10, the data appears in ascending order of unit_price and, where two or more rows have the same unit_price (for example, $20.00, $48.00, $312.00), the manu_code is in alphabetical order.

Query Result 2-10

The order of the columns in the ORDER BY clause is important, and so is the position of the DESC keyword. Although the statements in Query 2-11 contain the same components in the ORDER BY clause, each produces a different result (not shown).

Query 2-11

Selecting Specific Columns

The previous section showed how to select and order all data from a table. However, often all you want to see is the data in one or more specific columns. Again, the formula is to use the SELECT and FROM clauses, specify the columns and table, and perhaps order the data in ascending or descending order with an ORDER BY clause.

If you want to find all the customer numbers in the orders table, use a statement such as the one in Query 2-12.

Query 2-12

Query Result 2-12 shows how the statement simply selects all data in the customer_num column in the orders table and lists the customer numbers on all the orders, including duplicates.

Query Result 2-12

The output includes several duplicates because some customers have placed more than one order. Sometimes you want to see duplicate rows in a projection. At other times, you want to see only the distinct values, not how often each value appears.

To suppress duplicate rows, include the keyword DISTINCT or its synonym UNIQUE at the start of the select list, as Query 2-13 shows.

Query 2-13

To produce a more readable list, Query 2-13 limits the display to show each customer number in the orders table only once, as Query Result 2-13 shows.

Query Result 2-13

Suppose you are handling a customer call, and you want to locate purchase order number DM354331. To list all the purchase order numbers in the orders table, use a statement such as the one that Query 2-14 shows.

Query 2-14

Query Result 2-14 shows how the statement retrieves data in the po_num column in the orders table.

Query Result 2-14

However, the list is not in a very useful order. You can add an ORDER BY clause to sort the column data in ascending order and make it easier to find that particular po_num, as Query Result 2-15 shows.

Query 2-15

Query Result 2-15

To select multiple columns from a table, list them in the select list in the SELECT clause. Query 2-16 shows that the order in which the columns are selected is the order in which they are produced, from left to right.

Query 2-16

As shown in "Sorting on Multiple Columns", you can use the ORDER BY clause to sort the data in ascending or descending order and perform nested sorts. Query Result 2-16 shows ascending order.

Query Result 2-16

When you use SELECT and ORDER BY on several columns in a table, you might find it helpful to use integers to refer to the position of the columns in the ORDER BY clause.The statements in Query 2-17 retrieve and display the same data, as Query Result 2-17 shows.

Query 2-17

Query Result 2-17

You can include the DESC keyword in the ORDER BY clause when you assign integers to column names, as Query 2-18 shows.

Query 2-18

In this case, data is first sorted in descending order by order_date and in ascending order by customer_num.

GLS

ORDER BY and Non-English Data

By default, Informix database servers use the U.S. English language environment, called a locale, for database data. The U.S. English locale specifies data sorted in code-set order. This default locale uses the ISO 8859-1 code set.

If your database contains non-English data, the ORDER BY clause should return data in the order appropriate to that language. Query 2-19 uses a SELECT statement with an ORDER BY clause to search the table, abonnés, and to order the selected information by the data in the nom column.

Query 2-19

The collation order for the results of this query can vary, depending on the following system variations:

  • Whether the nom column is CHAR or NCHAR data type.
    The database server sorts data in CHAR columns by the order the characters appear in the code set. The database server sorts data in NCHAR columns by the order the characters are listed in the collation portion of the locale. Store non-English data in NCHAR (or NVARCHAR) columns to obtain results sorted by the language.

  • Whether the database server is using the correct non-English locale when accessing the database.
    To use a non-English locale, you must set the CLIENT_LOCALE and DB_LOCALE environment variables to the appropriate locale name.

For Query 2-19 to return expected results, the nom column should be NCHAR data type in a database that uses a French locale. Other operations, such as less than, greater than, or equal to, are also affected by the user-specified locale. Refer to the Guide to GLS Functionality for more information on non-English data and locales.

Query Result 2-19a and Query Result 2-19b show two sample sets of output.

Query Result 2-19a

Query Result 2-19a follows the ISO 8859-1 code-set order, which ranks uppercase letters before lowercase letters and moves the names that start with an accented character (Ålesund, Étaix, Ötker, and Øverst) to the end of the list.

Query Result 2-19b

Query Result 2-19b shows that when the appropriate locale file is referenced by the data server, names starting with non-English characters (Ålesund, Étaix, Ötker, and Øverst) are collated differently than they are in the ISO 8859-1 code set. They are sorted correctly for the locale. It does not distinguish between uppercase and lowercase letters.

Selecting Substrings

To select part of the value of a CHARACTER column, include a substring in the select list. Suppose your marketing department is planning a mailing to your customers and wants a rough idea of their geographical distribution based on zip codes. You could write a query similar to the one in Query 2-20.

Query 2-20

Query 2-20 uses a substring to select the first three characters of the zipcode column (which identify the state) and the full customer_num, and lists them in ascending order by zip code, as Query Result 2-20 shows.

Query Result 2-20

Using the WHERE Clause

Add a WHERE clause to a SELECT statement if you want to see only those orders that a particular customer placed or the calls that a particular customer service representative entered.

You can use the WHERE clause to set up a comparison condition or a join condition. This section demonstrates only the first use. Join conditions are described in a later section and in the next chapter.

The set of rows returned by a SELECT statement is its active set. A singleton SELECT statement returns a single row. Use a cursor to retrieve multiple rows in an SQL API. See Chapter 5, "Programming with SQL," and Chapter 6, "Modifying Data Through SQL Programs."

Creating a Comparison Condition

The WHERE clause of a SELECT statement specifies the rows that you want to see. A comparison condition employs specific keywords and operators to define the search criteria.

For example, you might use one of the keywords BETWEEN, IN, LIKE, or MATCHES to test for equality, or the keywords IS NULL to test for null values. You can combine the keyword NOT with any of these keywords to specify the opposite condition.

The following table lists the relational operators that you can use in a WHERE clause in place of a keyword to test for equality.

Operator Operation

=

equals

!= or <>

does not equal

>

greater than

>=

greater than or equal to

<

less than

<=

less than or equal to

For CHAR expressions, greater than means after in ASCII collating order, where lowercase letters are after uppercase letters, and both are after numerals. See the ASCII Character Set chart in Chapter 1 of the Informix Guide to SQL: Syntax. For DATE and DATETIME expressions, greater than means later in time, and for INTERVAL expressions, it means of longer duration. You cannot use CLOB, BLOB, TEXT, or BYTE columns in string expressions, except when you test for null values.

You can use the preceding keywords and operators in a WHERE clause to create comparison-condition queries that perform the following actions:

  • Include values
  • Exclude values
  • Find a range of values
  • Find a subset of values
  • Identify null values
To perform variable text searches using the criteria listed below, use the preceding keywords and operators in a WHERE clause to create comparison-condition queries:

  • Exact-text comparison
  • Single-character wildcards
  • Restricted single-character wildcards
  • Variable-length wildcards
  • Subscripting
The following section contains examples that illustrate these types of queries.

Including Rows
Use the relational operator = to include rows in a WHERE clause, as Query 2-21 shows.

Query 2-21

Query 2-21 returns the set of rows that Query Result 2-21 shows.

Query Result 2-21

Excluding Rows
Use the relational operators != or <> to exclude rows in a WHERE clause.

Query 2-22 assumes that you are selecting from an ANSI-compliant database; the statements specify the owner or login name of the creator of the customer table. This qualifier is not required when the creator of the table is the current user, or when the database is not ANSI compliant. However, you can include the qualifier in either case. For a complete discussion of owner naming, see Chapter 1 in the Informix Guide to SQL: Syntax.

Query 2-22

Both statements in Query 2-22 exclude values by specifying that, in the customer table that the user odin owns, the value in the state column should not be equal to CA, as Query Result 2-22

Query Result 2-22

shows.

Specifying Rows
Query 2-23 shows two ways to specify rows in a WHERE clause.

Query 2-23

Each statement in Query 2-23 specifies a range for catalog_num from 10005 through 10008, inclusive. The first statement uses keywords, and the second uses relational operators to retrieve the rows as Query Result 2-23

Query Result 2-23

shows.

Although the catalog table includes a column with the BYTE data type, that column is not included in this SELECT statement because the output would show only the words <BYTE value> by the column name. You can display TEXT and BYTE values when you write an SQL API application to do so.

Excluding a Range of Rows
Query 2-24 uses the keywords NOT BETWEEN to exclude rows that have the character range 94000 through 94999 in the zipcode column, as Query Result 2-24 shows.

Query 2-24

Using a WHERE Clause to Find a Subset of Values
As shown in "Excluding Rows", Query 2-25 also assumes the use of an ANSI-compliant database. The owner qualifier is in quotation marks to preserve the case sensitivity of the literal string.

Query 2-25

Each statement in Query 2-25 retrieves rows that include the subset of AZ or NJ in the state column of the Aleta.customer table, as Query Result 2-25 shows.

Query Result 2-25

You cannot test a CLOB, BLOB, TEXT or BYTE column with the IN keyword.

In Query 2-26, an example of a query on an ANSI-compliant database, no quotation marks exist around the table owner name. Whereas the two statements in Query 2-25 searched the Aleta.customer table, Query 2-26 searches the table ALETA.customer, which is a different table, because of the way ANSI-compliant databases look at owner names.

Query 2-26

Query 2-26 adds the keyword NOT IN, so the subset changes to exclude the subsets AZ and NJ in the state column. Query Result 2-26 shows the results in order of the state column.

Query Result 2-26

Identifying Null Values
Use the IS NULL or IS NOT NULL option to check for null values. A null value represents either the absence of data or an unknown value. A null value is not the same as a zero or a blank.

Query 2-27 returns all rows that have a null paid_date, as Query Result 2-27 shows.

Query 2-27

Query Result 2-27

Forming Compound Conditions
To connect two or more comparison conditions, or Boolean expressions, by use the logical operators AND, OR, and NOT. A Boolean expression evaluates as true or false or, if null values are involved, as unknown. You can use CLOB, BLOB, TEXT, or BYTE objects in a Boolean expression only when you test for a null value.

In Query 2-28, the operator AND combines two comparison expressions in the WHERE clause.

Query 2-28

The query returns all rows that have a null paid_date and the ones that do not also have a null ship_date, as Query Result 2-28 shows.

Query Result 2-28

Using Variable-Text Searches

You can use the keywords LIKE and MATCHES for variable-text queries that are based on substring searches of CHARACTER fields. Include the keyword NOT to indicate the opposite condition. The keyword LIKE is the ANSI standard, whereas MATCHES is an Informix extension.

Variable-text search strings can include the wildcards listed with LIKE or MATCHES in the following table.
Symbol Meaning

LIKE

%

Evaluates to zero or more characters

_

Evaluates to a single character

\

Escapes special significance of next character

MATCHES

*

Evaluates to zero or more characters

?

Evaluates to a single character (except null)

[ ]

Evaluates to a single character or range of values

\

Escapes special significance of next character

You cannot test a CLOB, BLOB, TEXT, or BYTE column with LIKE or MATCHES.

Using Exact Text Comparisons

The following examples include a WHERE clause that searches for exact text comparisons by using the keyword LIKE or MATCHES or the equal sign (=) relational operator. Unlike earlier examples, these examples illustrate how to query on an external table in an ANSI-compliant database.

An external table is a table that is not in the current database. You can access only external tables that are part of an ANSI-compliant database.

Whereas the database used previously in this chapter was the demonstration database called stores7, the FROM clause in the following examples specifies the manatee table, created by the owner bubba, which resides in an ANSI-compliant database named syzygy. For more information on defining external tables, see Chapter 1 in the Informix Guide to SQL: Syntax.

Each statement in Query 2-29 retrieves all the rows that have the single word helmet in the description column as Query Result 2-29 shows.

Query 2-29

Query Result 2-29

Using a Single-Character Wildcard

The statements in Query 2-30 illustrate the use of a single-character wildcard in a WHERE clause. Further, they demonstrate a query on an external table. The stock table is in the external database sloth. Besides being outside the current stores7 database, sloth is on a separate database server called meerkat.

For details on external tables and external databases, see Chapter 1 in the Informix Guide to SQL: Syntax.

Query 2-30

Each statement in Query 2-30 retrieves only those rows for which the middle letter of the manu_code is R, as Query Result 2-30 shows.

Query Result 2-30

The comparison '_R_' (for LIKE) or '?R?' (for MATCHES) specifies, from left to right, the following items:

  • Any single character
  • The letter R
  • Any single character
WHERE Clause with Restricted Single-Character Wildcard
Query 2-31 selects only those rows where the manu_code begins with A through H and returns the rows that Query Result 2-31 shows. The class test '[A-H]' specifies any single letter from A through H, inclusive. No equivalent wildcard symbol exists for the LIKE keyword.

Query 2-31

Query Result 2-31

WHERE Clause with Variable-Length Wildcard
The statements in Query 2-32 use a wildcard at the end of a string to retrieve all the rows where the description begins with the characters bicycle.

Query 2-32

Either statement returns the rows that Query Result 2-32 shows.

Query Result 2-32

The comparison 'bicycle%' or 'bicycle*' specifies the characters bicycle followed by any sequence of zero or more characters. It matches bicycle stem with stem matched by the wildcard. It matches to the characters bicycle alone, if a row exists with that description.

Query 2-33 narrows the search by adding another comparison condition that excludes a manu_code of PRC.

Query 2-33

The statement retrieves only the rows that Query Result 2-33 shows.

Query Result 2-33

When you select from a large table and use an initial wildcard in the comparison string (such as '%cycle'), the query often takes longer to execute. Because indexes cannot be used, every row is searched.

GLS

MATCHES and Non-English Data

By default, Informix database servers use the U.S. English language environment, called a locale, for database data. This default locale uses the ISO 8859-1 code set. The U.S. English locale specifies that MATCHES will use code-set order.

If your database contains non-English data, the MATCHES clause should use the correct non-English code set for that language. Query 2-34 uses a SELECT statement with a MATCHES clause in the WHERE clause to search the table, abonnés, and to compare the selected information with the data in the nom column.

Query 2-34

The result of the comparison in this query is the same whether nom is a CHAR or NCHAR column. The database server uses the sort order that the locale specifies to determine what characters are in the range E through P. This behavior is an exception to the rule that the database server collates CHAR and VARCHAR columns in code-set order and NCHAR and NVARCHAR columns in the sort order that the locale specifies.

In Query Result 2-34b, the rows for Étaix, Ötker, and Øverst are not selected and listed because, with ISO 8859-1 code-set order, the accented first letter of each name is not in the E through P MATCHES range for the nom column. The database server uses code-set order when the nom column is CHAR data type. It also uses localized ordering when the column is NCHAR data type, and you specify a nondefault locale.

Query Result 2-34a

In Query Result 2-34b, the rows for Étaix, Ötker, and Øverst are included in the list because the database server uses a locale-specific comparison.

Query Result 2-34b

For more information on non-English data and locales, refer to the Guide to GLS Functionality.

Comparing for Special Characters

Query 2-35 uses the keyword ESCAPE with LIKE or MATCHES so you can protect a special character from misinterpretation as a wildcard symbol.

Query 2-35

The ESCAPE keyword designates an escape character (it is! in this example) that protects the next character so that it is interpreted as data and not as a wildcard. In the example, the escape character causes the middle percent sign (%) to be treated as data. By using the ESCAPE keyword, you can search for occurrences of a percent sign (%) in the res_descr column by using the LIKE wildcard percent sign (%). The query retrieves the row that Query Result 2-35 shows.

Query Result 2-35

Using Subscripting in a WHERE Clause
You can use subscripting in the WHERE clause of a SELECT statement to specify a range of characters or numbers in a column, as Query 2-36 shows.

Query 2-36

The subscript [1,4] causes Query 2-36 to retrieve all rows in which the first four letters of the cat_advert column are High, as Query Result 2-36 shows.

Query Result 2-36

Expressions and Derived Values

You are not limited to selecting columns by name. You can use the SELECT clause of a SELECT statement to perform computations on column data and to display information derived from the contents of one or more columns. To do this, list an expression in the select list.

An expression consists of a column name, a constant, a quoted string, a keyword, or any combination of these items connected by operators. It can also include host variables (program data) when the SELECT statement is embedded in a program.

Arithmetic Expressions

An arithmetic expression contains at least one of the arithmetic operators listed in the following table and produces a number. You cannot use CLOB, BLOB, TEXT, or BYTE columns in arithmetic expressions.

Operator Operation
+

addition

-

subtraction

*

multiplication

/

division

Operations of this nature enable you to see the results of proposed computations without actually altering the data in the database. You can add an INTO TEMP clause to save the altered data in a temporary table for further reference, computations, or impromptu reports. Query 2-37 calculates a 7 percent sales tax on the unit_price column when the unit_price is $400 or more (but does not update it in the database).

Query 2-37

If you are using DB-Access or the SQL Editor, the result is displayed in a column labeled expression, as Query Result 2-37 shows.

Query Result 2-37

Query 2-38 calculates a surcharge of $6.50 on orders when the quantity ordered is less than 5.

Query 2-38

If you are using DB-Access or the SQL Editor, the result appears in a column labeled expression, as Query Result 2-38 shows.

Query Result 2-38

Query 2-39 calculates and displays in an expression column (if you are using DB-Access or the SQL Editor) the interval between when the customer call was received (call_dtime) and when the call was resolved (res_dtime), in days, hours, and minutes.

Query 2-39

Query Result 2-39

Using Display Labels
You can assign a display label to a computed or derived data column to replace the default column header expression. In Query 2-40, Query 2-41, and Query 2-42, the derived data is shown in a column called (expression). Query 2-40 also presents derived values, but the column that displays the derived values now has the descriptive header taxed.

Query 2-40

Query Result 2-40 shows that the label taxed is assigned to the expression in the select list that displays the results of the operation unit_price * 1.07.

Query Result 2-40

In Query 2-41, the label surcharge is defined for the column that displays the results of the operation total_price + 6.50.

Query 2-41

The surcharge column is labeled in the output, as Query Result 2-41 shows.

Query Result 2-41

Query 2-42 assigns the label span to the column that displays the results of subtracting the DATETIME column call_dtime from the DATETIME column res_dtime.

Query 2-42

The span column is labeled in the output, as Query Result 2-42

Query Result 2-42

shows.

Sorting on Derived Columns

When you want to use ORDER BY as an expression, you can use either the display label assigned to the expression or an integer, as Query 2-43 shows.

Query 2-43

Query 2-43 retrieves the same data from the cust_calls table as Query 2-42. In Query 2-43, the ORDER BY clause causes the data to be displayed in ascending order of the derived values in the span column, as Query Result 2-43 shows.

Query Result 2-43

Query 2-44 uses an integer to represent the result of the operation res_dtime - call_dtime and retrieves the same rows that appear in Query Result 2-43.

Query 2-44

Using Functions in SELECT Statements

In addition to column names and operators, an expression can also include one or more functions.

Expressions supported include aggregate, function (which include arithmetic functions), constant, and column expressions. These expressions are described in Chapter 1 of the Informix Guide to SQL: Syntax.

Aggregate Functions

The aggregate functions are COUNT, AVG, MAX, MIN, and SUM. They take on values that depend on all the rows selected and return information about rows, not the rows themselves. You cannot use these functions with CLOB, BLOB, TEXT, or BYTE columns.

Aggregates are often used to summarize information about groups of rows in a table. This use is discussed in Chapter 3, "Composing Advanced SELECT Statements." When you apply an aggregate function to an entire table, the result contains a single row that summarizes all of the selected rows.

Query 2-45 counts and displays the total number of rows in the stock table.

Query 2-45

Query Result 2-45

Query 2-46 includes a WHERE clause to count specific rows in the stock table; in this case, only those rows that have a manu_code of SHM.

Query 2-46

Query Result 2-46

By including the keyword DISTINCT (or its synonym UNIQUE) and a column name in Query 2-47, you can tally the number of different manufacturer codes in the stock table.

Query 2-47

Query Result 2-47

Query 2-48 computes the average unit_price of all rows in the stock table.

Query 2-48

Query Result 2-48

Query 2-49 computes the average unit_price of just those rows in the stock table that have a manu_code of SHM.

Query 2-49

Query Result 2-49

You can combine aggregate functions as Query 2-50 shows.

Query 2-50

Query 2-50 finds and displays both the highest and lowest ship_charge in the orders table, as Query Result 2-50 shows.

Query Result 2-50

You can apply functions to expressions, and you can supply display labels for their results, as Query 2-51 shows.

Query 2-51

Query 2-51 finds and displays the maximum, minimum, and average amount of time (in days, hours, and minutes) between the reception and resolution of a customer call and labels the derived values appropriately. These amounts of time are shown in Query Result 2-51.

Query Result 2-51

Query 2-52 calculates the total ship_weight of orders that were shipped on July 13, 1994.

Query 2-52

Query Result 2-52

Time Functions

You can use the time functions DAY, MDY, MONTH, WEEKDAY, YEAR, and DATE in either the SELECT clause or the WHERE clause of a query. These functions return a value that corresponds to the expressions or arguments that you use to call the function. You can also use the CURRENT function to return a value with the current date and time, or use the EXTEND function to adjust the precision of a DATE or DATETIME value.

Using DAY and CURRENT
Query 2-53 returns the day of the month for the call_dtime and res_dtime columns in two expression columns, as Query Result 2-53 shows.

Query 2-53

Query Result 2-53

Query 2-54 uses the DAY and CURRENT functions to compare column values to the current day of the month. It selects only those rows where the value is earlier than the current day.

Query 2-54

Query Result 2-54

Query 2-55 shows another use of the CURRENT function, selecting rows where the day is earlier than the current one.

Query 2-55

Query Result 2-55

Using MONTH
Query 2-56 uses the MONTH function to extract and show what month the customer call was received and resolved, and it uses display labels for the resulting columns. However, it does not make a distinction between years.

Query 2-56

Query Result 2-56

Query 2-57 uses the MONTH function plus DAY and CURRENT to show what month the customer call was received and resolved if DAY is earlier than the current day.

Query 2-57

Query Result 2-57

Using WEEKDAY
In Query 2-58, the WEEKDAY function is used to indicate which day of the week calls are received and resolved (0 represents Sunday, 1 is Monday, and so on), and the expression columns are labeled.

Query 2-58

Query Result 2-58

Query 2-59 uses the COUNT and WEEKDAY functions to count how many calls were received on a weekend. This kind of statement can give you an idea of customer-call patterns or indicate whether overtime pay might be required.

Query 2-59

Query Result 2-59

Query 2-60 retrieves rows where the call_dtime is earlier than the beginning of the current year.

Query 2-60

Formatting DATETIME Values
In Query 2-61, the EXTEND function restricts the two DATETIME values by displaying only the specified subfields.

Query 2-61

Query Result 2-61 returns the month-to-minute range for the columns labeled call_time and res_time and gives an indication of the workload.

Query Result 2-61

Using the DATE Function
Query 2-62 retrieves DATETIME values only when call_dtime is later than the specified DATE.

Query 2-62

Query Result 2-62 returns the following rows.

Query Result 2-62

Query 2-63 converts DATETIME values to DATE format and displays the values, with labels, only when call_dtime is greater than or equal to the specified date.

Query 2-63

Other Functions and Keywords

You also can use the LENGTH, USER, CURRENT, and TODAY functions anywhere in an SQL expression that you would use a constant. In addition, with Universal Server, you can include the DBSERVERNAME keyword in a SELECT statement to display the name of the database server where the current database resides.

You can use these functions and keywords to select an expression that consists entirely of constant values or an expression that includes column data. In the first instance, the result is the same for all rows of output.

In addition, you can use the HEX function to return the hexadecimal encoding of an expression, the ROUND function to return the rounded value of an expression, and the TRUNC function to return the truncated value of an expression.

In Query 2-64, the LENGTH function calculates the number of bytes in the combined fname and lname columns for each row where the length of company is greater than 15.

Query 2-64

Although the LENGTH function might not be useful when you work with DB-Access or the SQL Editor, it can be important to determine the string length for programs and reports. LENGTH returns the clipped length of a CHARACTER or VARCHAR string and the full number of bytes in a TEXT or BYTE string.

The USER function can be handy when you want to define a restricted view of a table that contains only your rows. For information on creating views, see Chapter 11, "Granting and Limiting Access to Your Database," in this manual and the GRANT and CREATE VIEW statements in Chapter 1 of the Informix Guide to SQL: Syntax.

Query 2-65a specifies the USER function and the cust_calls table.

Query 2-65a

Query 2-65b returns the user name (login account name) of the user who executes the query. It is repeated once for each row in the table.

Query 2-65b

If the user name of the current user is richc, Query 2-65b retrieves only those rows in the cust_calls table that are owned by that user, as Query Result 2-65 shows.

Query Result 2-65

If Query 2-66 is issued when the current system date is July 10, 1994, it returns this one row.

Query 2-66

Query Result 2-66

You can include the keyword DBSERVERNAME (or its synonym, SITENAME) in a SELECT statement in Universal Server to find the name of the database server. You can query on the DBSERVERNAME for any table that has rows, including system catalog tables.

In Query 2-67, you assign the label server to the DBSERVERNAME expression and also select the tabid column from the systables system catalog table. This table describes database tables, and tabid is the serial-interval table identifier.

Query 2-67

Without the WHERE clause to restrict the values in the tabid, the database server name would be repeated for each row of the systables table.

In Query 2-68, the HEX function returns the hexadecimal format of three specified columns in the customer table.

Query 2-68

Using SPL Routines in SELECT Statements

We have seen examples of SELECT statement expressions that consist of column names, operators, and functions. Another type of expression contains an SPL routine call.

SPL routines contain special Stored Procedure Language (SPL) statements as well as SQL statements. For more information on SPL routines, refer to Chapter 14, "Creating and Using SPL Routines."

SPL routines provide a way to extend the range of functions available; you can perform a subquery on each row you select.

For example, suppose you want a listing of the customer number, the customer's last name, and the number of orders the customer has made. Query 2-69 shows one way to retrieve this information. The customer table has customer_num and lname columns but no record of the number of orders each customer has made. The following query assumes you have written a get_orders routine, which queries the orders table for each customer_num and returns the number of corresponding orders that is labeled n_orders.

Query 2-69

Query Result 2-69 shows the output from this SPL routine

Query Result 2-69

.

Use SPL routines to encapsulate operations that you frequently perform in your queries. For example, the condition in Query 2-70 contains a routine, conv_price, that converts the unit price of a stock item to a different currency and adds any import tariffs.

Query 2-70




Informix Guide to SQL: Tutorial, version 9.1
Copyright © 1998, Informix Software, Inc. All rights reserved.