POW – Explain That SQL #1

Someone asked me to quickly write them some code in any language that would accomplish a certain task. The following, which is in PostgreSQL, is the second solution that I came up with after doing the first one in my favorite language, JavaScript:

SELECT ARRAY_TO_STRING(ARRAY(
    SELECT CHR(num
        + CASE
            WHEN num < 26 THEN 65
            WHEN num BETWEEN 26 AND 51 THEN 71
            ELSE -4
          END
      )
    FROM (
      SELECT FLOOR(RANDOM() * 62)::INT AS num,
        generate_series(1, 12)
    ) AS t
  ), '')

The question is, what does this SELECT statement actually do? If you were asked to write that as a JavaScript, substituting the 12 for a variable passed into the function, what would your function look like?

As usual, the answer to this Problem of the Week will be made available a week from today, on Wednesday, August 22, 2012.

The answer to this Problem of the Week can now be found here.

POW – Fill In The Blanks In SQL

One of the things I always find interesting is the fact that DBAs almost always use some type of auto-increment method in order to generate unique IDs for records. Sometimes, though, you may have a table in which you don’t want to use the default method of generating the next ID in the sequence. Sometimes the goal is to re-use old IDs that are no longer in use. The goal this week will be to create a SELECT statement in any flavor of SQL you want, that will fetch the smallest non-negative positive integer that has not yet been used. The column will be called id while the table will be called stars. What is your most efficient way that you can think of the accomplish this task using just a SELECT statement (not a self-written function)?

The answer to this Problem of the Week is here.