Ever find yourself working in an unfamiliar Database or table and in need of knowing what are the data types for the different columns? Well that recently happened to me when I had to expand some queries in a DB2 environment.

As it turns out there exists the Describe command that outputs the columns of a table and their data type. The basic command is as follows that can be used on a TABLE or VIEW:

DESCRIBE TABLE schema.table_name

The command will output the following information for each column.

  • Column Name
  • Type Schema
  • Type Name
  • Length
  • Scale(precision)
  • Nulls(is nullable)

In addition to obtaining the column information you can also use the command to get a table’s indexes.

DESCRIBE INDEXES FOR TABLE schema.table_name

Resources

, , , , , ,

Like most individuals I find the built int SUM function of SQL very helpful when performing computations. Recently however I found myself wondering how to compute the product of a result set grouped by some factor, and I found myself slightly at a lost as no Product function exists.

Fortunately for us we can use some basic Math to do our aggregate multiplication. As you may or may not remember we can Log and AntiLog to perform multiplication.

X * Y * Z = ANTILOG( LOG( X ) + LOG( Y ) + LOG( Z ) )

Looking closely at the above formula you can see that these functions all exist in most Database Servers and in T-SQL specifically you can rewrite the formula as :

SELECT EXP ( SUM ( LOG (myColumn) ) ) FROM myTable

If you wanted to get even fancier and get totals based on some criteria then you could add in GROUP BY and WHERE clauses to your queries. For example lets say you are doing some probability calculations and want to have the product of some percentages then you could do something like:

SELECT EXP(SUM(LOG(r.MEAN)))
FROM RESOURCES r
WHERE r.MODEL_ID = "TEMP"
GROUP BY r.GROUP_ID
ORDER BY r.GROUP_ID

Also it is worth wild to mention this only works for positive values. If you want to have the product of values that could potentially be negative you will have to keep track of the number of negative values and then set the result as necessary.

, , , , , ,

While continuing my exploration into the world of DB2 databases, I found myself confused as to why my basic SELECT … WHERE … statement were failing when I tried to do AND/OR clauses. After a little fumbling around I found the solution… parentheses.

Parenthesis? you ask, yes. Simply put when you want to write a compound WHERE clause using AND and/or OR statements you need to wrap each clause in parentheses. To illustrate lets start with a basic SQL select query and then we’ll show how it needs to be written for DB2

SQL Statement

SELECT first_name, last_name, id 
FROM APP_DB..APP_USERS 
WHERE active=1 
    AND  is_admin=1

DB2 SQL Statement

SELECT first_name, last_name, id
FROM APP_SCHEMA.APP_USERS
WHERE ( active = 1 ) 
    AND  ( is_admin = 1 );

As you can see for the DB2 query to function properly it needs the parentheses around the clauses while most other SQL languages don’t. Hopefully this little tidbit will save others the half hour I spent fumbling around with this little subtle syntax difference.

, , , , ,

Back from an extended vacation and I find myself in the middle of a project needing to export data from a DB2 database. Fortunately I have decent knowledge of SQL and the basic syntax matches up but then I found myself wanting to limit the results returned. Now in T-SQL and MySQL I often would use the, LIMIT, TOP or SET ROWCOUNT commands but they aren’t available in DB2. Instead you use the FETCH FIRST command.

To put things simply to limit the number of rows returned the command is:

FETCH FIRST 10 ROWS ONLY

What this means is that your basic SELECT statement would be entered as:

SELECT * FROM mySchema.myTable WHERE TRAN_TS >= '05/01/2010' FETCH FIRST 10 ROWS ONLY
, , , , ,

PHP Database Objects PDOs for short is a light-weight data abstraction layer for PHP. What this means is that it allows you to use an interface for performing data manipulations instead of using db specify functions such as mysql_query. So that if you needed to migrate to a different database you would not have to rewrite your code instead you simply change the connection driver. In addition to portability of the code you also protect against SQL-Injection as the prepare method will call the underlying quote method of the specific driver so that your input gets escaped properly.

Connecting to a database with PDO

To connect to a database you need to instantiate the PDO object. The constructor espects 3 parameters: connection string, username, and password. The connection string specifies the driver, host, and optional database or schema to connect to and has the following format: driver:host=hostname:port;dbname=database

$pdo = new PDO("mysql:host=localhost;dbname=mysql", "username", "password");

When establishing a connection if there is an error connecting an exception will be thrown. In this thrown exception the stack trace will reveal the username and password used to access the server. It is very important that you capture these exceptions and either throw an excpetion that does not share this information or define your own handlers. Below is a full example for connection to a databse with PDO and handling the Exception if the connection fails.

$driver = "mysql";
$host_name = 'localhost';
$user_name = 'root';
$password = 'root';
$db_name = 'MY_DB';
 
try {
    $db = new PDO("$driver:host=$host_name;dbname=$db_name", $user_name, $password);
    echo 'Connected to database';
}
catch(PDOException $e) {
    echo $e->getMessage();
}

Preparing and Executing a Query

There are 2 main ways to prepare queries when using PDOs. The first method is to define your sql with ? placeholders for variables.

$sql = 'SELECT name, phone_num, active
    FROM Users
    WHERE name like ?';
$statement = $pdo>prepare( $sql );

The second option is define the query with named variables by use of the : character. In the below query we defined the named variable :name.

$sql = 'SELECT name, phone_num, active
    FROM Users
    WHERE name like :name';
$statement = $pdo>prepare( $sql );

The PDOStatement object is returned from the prepare function. The next step will be to execute the statements with your variables. If you used the ? method you simply pass an array of variables.

$statement->execute(array('A%'));

While if you used the named parameter way you will pass in an assocaited array of the variables

$statement->execute( array( ":name" => "A%" ) );

Now that you have executed the query me can fetch the results in various different methods.

Fetching and Using the Result

Now that you have executed your query you want your results right? To do this you utilize either the fetch or fetchAll method. Which will return the next result row or an array of all the rows. You can even specify how you want the data returned as: FETCH_ASSOC returns an associated array by the column name and FETCH_BOTH returns it by both the index of the column and the name.

$result = $sth->fetch(PDO::FETCH_ASSOC);
$result = $sth->fetchAll(PDO::FETCH_BOTH);

Now that you have the data simply use it however you need in your application. If you returned it as an associated array you can simply get the property.

echo $result->name;

Closing your Connection

To close your connection you simply need to set all your references to the PDO object to null. If you fail to close the connection it will be closed automatically upon the completion of the script. Good practice is to close it once you are finished.

$pdo = null;

Resources