![]() |
|
Home | Contents | Index | Master Index | New Book | ![]() |
![]() |
Single-Table SELECT StatementsYou can query a single table in a database in many ways. You can tailor a SELECT statement to perform the following actions:
Selecting All Columns and RowsThe most basic SELECT statement contains only the two required clauses, SELECT and FROM.
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-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-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.
An explicit select list, shown in Query 2-7a, includes all the column names that you want to retrieve. An implicit select list uses the asterisk symbol (*), as Query 2-7b shows. 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.
The keyword DESC following a column name causes the retrieved data to be sorted in descending order, as Query Result 2-8 shows.
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.
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. 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 2-10 shows the reversed order of the columns in the ORDER BY clause. 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.
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).
Selecting Specific ColumnsThe 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 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.
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. 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.
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 Result 2-14 shows how the statement retrieves data in the po_num column in the orders table.
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.
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. 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.
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.
You can include the DESC keyword in the ORDER BY clause when you assign integers to column names, as Query 2-18 shows. In this case, data is first sorted in descending order by order_date and in ascending order by customer_num.
ORDER BY and Non-English DataBy 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. The collation order for the results of this query can vary, depending on the following system variations:
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 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 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.
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.
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."
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.
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: 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:
Query 2-21 returns the set of rows that Query Result 2-21 shows.
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. 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
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
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
FROM customer WHERE zipcode NOT BETWEEN '94000' AND '94999' ORDER BY state
Using a WHERE Clause to Find a Subset of ValuesAs 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.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.
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 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 2-27 returns all rows that have a null paid_date, as Query Result 2-27 shows.
In Query 2-28, the operator AND combines two comparison expressions in the WHERE clause. 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.
Variable-text search strings can include the wildcards listed with LIKE or MATCHES in the following table.
You cannot test a CLOB, BLOB, TEXT, or BYTE column with LIKE or MATCHES.
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
For details on external tables and external databases, see Chapter 1 in the Informix Guide to SQL: Syntax. 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.
The comparison '
WHERE Clause with Restricted Single-Character WildcardQuery 2-31 selects only those rows where the manu_code begins withA 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.
Either statement returns the rows that Query Result 2-32 shows.
The comparison '
Query 2-33 narrows the search by adding another comparison condition that excludes a manu_code of The statement retrieves only the rows that Query Result 2-33 shows.
When you select from a large table and use an initial wildcard in the comparison string (such as '
MATCHES and Non-English DataBy 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. 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.
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.
For more information on non-English data and locales, refer
to the Guide to GLS Functionality.
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.
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.
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.
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). 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 2-38 calculates a surcharge of $6.50 on orders when the quantity ordered is less than 5. 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 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 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 .
In Query 2-41, the label surcharge is defined for the column that displays the results of the operation The surcharge column is labeled in the output, as Query Result 2-41 shows.
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. The span column is labeled in the output, as Query Result 2-42
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 2-44 uses an integer to represent the result of the operation
Using Functions in SELECT StatementsIn 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.
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-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
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-48 computes the average unit_price of all rows in the stock table.
Query 2-49 computes the average unit_price of just those rows in the stock table that have a manu_code of
You can combine aggregate functions as Query 2-50 shows. Query 2-50 finds and displays both the highest and lowest ship_charge in the orders table, as Query Result 2-50 shows.
You can apply functions to expressions, and you can supply display labels for their results, as Query 2-51 shows. 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 2-52 calculates the total ship_weight of orders that were shipped on July 13, 1994.
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-55 shows another use of the CURRENT function, selecting rows where the day is earlier than the current one.
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-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-60 retrieves rows where the call_dtime is earlier than the beginning of the current year.
YEAR (call_dtime) call_year, YEAR (res_dtime) res_year FROM cust_calls WHERE YEAR (call_dtime) < YEAR (TODAY)
Formatting DATETIME ValuesIn Query 2-61, the EXTEND function restricts the two DATETIME values by displaying only the specified subfields.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-62 returns the following rows.
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.
DATE (call_dtime) called, DATE (res_dtime) resolved FROM cust_calls WHERE call_dtime >= DATE ('1/1/94')
Other Functions and KeywordsYou 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.
LENGTH (fname) + LENGTH (lname) namelength FROM customer WHERE LENGTH (company) > 15
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-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. 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.
If Query 2-66 is issued when the current system date is July 10, 1994, it returns this one row.
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.
WHERE tabid <= 4
In Query 2-68, the HEX function returns the hexadecimal format of three specified columns in the customer table.
HEX (rowid) hexrow FROM customer
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 Result 2-69 shows the output from this SPL routine
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.
|
![]() |
![]() |