Databases and SQL
Calculating New Values
- Write queries that calculate new values for each selected record.
After carefully re-reading the expedition logs, we realize that the radiation measurements they report may need to be corrected upward by 5%. Rather than modifying the stored data, we can do this calculation on the fly as part of our query:
SELECT 1.05 * reading FROM Survey WHERE quant='rad';
|1.05 * reading|
When we run the query, the expression
1.05 * reading is evaluated for each row. Expressions can use any of the fields, all of usual arithmetic operators, and a variety of common functions. (Exactly which ones depends on which database manager is being used.) For example, we can convert temperature readings from Fahrenheit to Celsius and round to two decimal places:
SELECT taken, round(5*(reading-32)/9, 2) FROM Survey WHERE quant='temp';
We can also combine values from different fields, for example by using the string concatenation operator
SELECT personal || ' ' || family FROM Person;
Fixing Salinity Readings
After further reading, we realize that Valentina Roerich was reporting salinity as percentages. Write a query that returns all of her salinity measurements from the
Survey table with the values divided by 100.
UNION operator combines the results of two queries:
SELECT * FROM Person WHERE ident='dyer' UNION SELECT * FROM Person WHERE ident='roe';
UNION to create a consolidated list of salinity measurements in which Roerich’s, and only Roerich’s, have been corrected as described in the previous challenge. The output should be something like:
Selecting Major Site Identifiers
The site identifiers in the
Visited table have two parts separated by a ‘-’:
SELECT DISTINCT site FROM Visited;
Some major site identifiers are two letters long and some are three. The “in string” function
instr(X, Y) returns the 1-based index of the first occurrence of string Y in string X, or 0 if Y does not exist in X. The substring function
substr(X, I) returns the substring of X starting at index I. Use these two functions to produce a list of unique major site identifiers. (For this data, the list should contain only “DR” and “MSK”).