Category: nice to know

  • Skewness in teradata

    Currently, I work on a Teradata machine. I understand that Teradata is based on the idea that processes work in parallel with each other. The idea is that data are divided over so-called amps that each process their share of the data.
    If each so-called amp may process their share of data, the amount of data must be equally divided over the amps. If each amp take proportional part of data, each amp has a fair share of work. As the last amp decides on total elapse time, it is advisable to have an equal amount of data allocated to each amp.
    To see as to what extent the data are equally divided, one may run this query:

    SELECT databasename, tablename, creatorname
    ,dat_created*1 + 19000000 AS dat_created
    ,MAX(amps) AS amps
    ,MAX(R) AS Ratio
    ,MAX(AvgMB) AS AvgMB
    ,MAX(MaxMB) AS MaxMB
    FROM (
    SELECT t.tablename
    , t.databasename
    , ts.vproc
    , ts.currentperm/1000000.0  AmpMB
    , t.creatorname 
    ,CAST (t.createtimestamp AS DATE) AS dat_created
    ,AVG(ts.currentperm/1000000.0) OVER 
     (PARTITION BY ts.databasename, ts.tablename) AS AvgMB
    ,MAX(ts.currentperm/1000000.0) OVER 
     (PARTITION BY ts.databasename, ts.tablename) AS MaxMB
    ,COUNT(*) OVER (PARTITION BY ts.databasename, ts.tablename) AS AMPS
    ,CAST ( 10000* (maxmb-avgmb)/maxmb AS INTEGER )  AS R
    FROM dbc.tablesize ts JOIN  dbc.tables t 
    ON ts.databasename = t.databasename AND ts.tablename = t.tablename
    WHERE
     t.databasename  IN  ('financial') 
    ) MY_DISPLACED
    GROUP BY 1,2,3,4
    ORDER BY Ratio DESC;
    

    The higher, the ratio R, the more skewed the division of data over the amps is.
    One influences the division of data with the addition of “primary index(attribute name)” in the ddl that creates the table.
    Records that have the same value for the attribute are then allocated to the same amp. This implies that the primary index should have a many different values as possible. Different values implies different amps that get records allocated to.
    An example. Table “slecht” is divided over two amps. One amp contains 0.08 MB, the second contains 0.08 MB. This is nicely distributed and the SQL that runs on this table will run smooth. If we look at the values, we notice that slecht has a primary index refers to an attribute that has many different values with no value standing out. If we update the table “slecht”by giving the primary index attribute the same value, we see that one amp gets 0.16 MB whereas the other amp gets no records at all. In that case, the sql will take more time as only one amp must do all work.

  • Get data from Oracle

    There exist many ways to get data from Oracle. After all, this is the core functionality of Oracle: getting data in and out. A nice possibility is to retrieve data by means of a small script. Such script is straightforward:

    set echo off   
    set pagesize 0 
    set feedback off
    set linesize 50
    set termout off
    
    spool c:/onzin.txt
    
    select '"'||job_id||'";"'||job_id||'";'
    ||min_salary||';'||max_salary from jobs;
    
    spool off

    The two most important lines are: “spool ” which designates a file that will receive data and the SQL that reads like “select etc”. Such script can be executed from SQLplus by @ “filename” where “filename” is the file that holds the script. In SQLplus, this looks like
    When I go to the directory c:\, I see the file “onzin.txt”, that contains the data

    "AD_PRES";"AD_PRES";20000;40000                   
    "AD_VP";"AD_VP";15000;30000                       
    "AD_ASST";"AD_ASST";3000;6000                     
    "FI_MGR";"FI_MGR";8200;16000                      
    

    I like this approach: you only need SQLplus as client application, which is standard in most circumstances. Moreover, it is fast: it depends on the network, but it is possible to retrieve millions of records within reasonable amount of time. Finally, this approach is repeatable since the script can be stored in a file.

    Final remark

    It is possible to execute this approach in a scheduled environment. If we have a script (say a.bat) that looks like:

    connect scott/bunvgeni@INTERNET
    @C:\a.sql
    quit
    

    This script can be executed by a scheduler with subsequent command “sqlplus /nolog @a.bat”. Without human interference, SQLplus is started and within SQLplus, a script is executed that retrieves data.

  • The foreign key in Oracle XE

    Oracle has introduced a small version of its DBMS that is labelled “XE”. This small version can be downloaded and used for free upon the condition that its usage is for personal study only.
    I really like this application: it has a relative small footprint; it runs on a small machine and it allows you to learn Oracle in your own environment.
    It is possible to play with the features that Oracle has. To refresh my knowledge on foreign keys.

    Let us first start with the creation of two tables:

    DROP TABLE "SCOTT"."CHILD";
    CREATE TABLE "SCOTT"."CHILD" 
       (	"CHILD_ID" NUMBER NOT NULL ENABLE, 
    	"PARENT_ID" NUMBER, 
    	"BIJDRAGE" NUMBER, 
    	 CONSTRAINT "CHILD_PK" PRIMARY KEY ("CHILD_ID")) ;
    
    DROP TABLE "SCOTT"."PARENT";
    CREATE TABLE "SCOTT"."PARENT" 
       (	"PARENT_ID" NUMBER NOT NULL ENABLE, 
    	"PARENT_NAAM" VARCHAR2(20 BYTE), 
    	 CONSTRAINT "PARENT_PK" 
             PRIMARY KEY ("PARENT_ID")) ;
    
    INSERT INTO "SCOTT"."PARENT" 
    (PARENT_ID, PARENT_NAAM) VALUES ('1', 'tom');
    INSERT INTO "SCOTT"."PARENT" 
    (PARENT_ID, PARENT_NAAM) VALUES ('2', 'ine');
    
    INSERT INTO "SCOTT"."CHILD" 
    (CHILD_ID, PARENT_ID, BIJDRAGE) VALUES ('1', '1', '123');
    INSERT INTO "SCOTT"."CHILD" 
    (CHILD_ID, PARENT_ID, BIJDRAGE) VALUES ('2', '1', '23');
    INSERT INTO "SCOTT"."CHILD" 
    (CHILD_ID, PARENT_ID, BIJDRAGE) VALUES ('3', '2', '45');
    INSERT INTO "SCOTT"."CHILD" 
    (CHILD_ID, PARENT_ID, BIJDRAGE) VALUES ('4', '2', '65');
    INSERT INTO "SCOTT"."CHILD" 
    (CHILD_ID, PARENT_ID, BIJDRAGE) VALUES ('5', '2', '78');

    We now have two tables: a child and a parent. With a foreign key relation, I will link the two tables. This is done with:

    alter table "CHILD" 
    add foreign key("PARENT_ID") 
    references "PARENT"("PARENT_ID")
    ; 
    

    This links the parent to the child. In this case, one record in the “parent” table may be linked to zero, one or more records in the “child” table. In it also true that a record in the child must always be linked to the parent. This can also be seen in the database diagramme:


    The foreign key relation described above does not allow you to remove a parent record that has still child records. If we want to remove such a record, we should first remove the child records.
    To avoid this somewhat cumbersome procedure (first delete relevant chiuld record, then remove parent record), we might use a different way of creating the foreign key:

    alter table "CHILD" 
    add foreign key("PARENT_ID") 
    references "PARENT"("PARENT_ID")
    on delete cascade
    ; 
    

    In that case, removal of a parent record automatically deletes the child records. This could be quite convenient if we have a system where details are stored in a separate table, away from a general table. With the removal of records from the general table, the details are automatically removed as well.

     

     

  • How many non-nulls per column?

    In Oracle, it is quite well possible to display quickly how many non-nulls we have per column in a table.
    The script reads like:

    set termout off echo on feed off trimspool 
    on head off pages 0
    
    spool C:\countall.tmp
    
    SELECT  'select count('||t.column_name||') 
     from ' || t.table_name ||';'
    FROM    user_tab_columns t
    WHERE  t.table_name = 'DATE_D2'
    ;
    
    spool off
    
    set termout on
    @@c:\countall.tmp
    
    set head on feed on

    And the results look like:

  • How many records in a table?

    Recently, I encountered a very nice script that allows us to get an overview of the number of records per table in an Oracle scheme. First the script:

    set termout off echo off feed off trimspool 
    on head off pages 0
    
    spool C:\countall.tmp
    select 'SELECT count(*), '''||table_name||''' 
    from '||table_name||';'
    from   user_tables
    /
    spool off
    
    set termout on
    @@c:\countall.tmp
    
    set head on feed on

    The output then looks like:

    As you can see, I stored the script in a file c:\a.sql, where I copied the script. The resulting output showed itself in the terminal.

  • ASCII or EBCDIC: how to recognise it?

    Today, I heard someone complaining that he received a file that contained “unexpected characters”. Later it was discovered that this file was provided in EBCDIC and the receiver tried to open it on a UNIX box with an ordinary editor. Such a UNIX box assumes the ASCII lay-out and as the file was delivered in EBCDIC, the characters shown were not comprehensible.

    What is the difference between ASCII and EBCDIC?

    Roughly stated ASCII and EBCDIC both translate a byte into a character. A byte may have 256 different values. A byte then ranges from 0 to 255. In heximal format: it ranges from 00 to FF. This implies that a byte with heximal value 20 is ASCII interpreted as a blank. It also implies that a byte with heximal value 40 is EBCDIC interpreted as a blank.
    We can see the heximal values when we toggle in a text-editor between the normal representation and the heximal representation. On my laptop, I have a text editor (Notepad++) that allows such a toggle. My laptop uses the ASCII representation and toggling shows that “TOM ” is equivalent to heximal values “54 4F 4D 20”. On Windows and Unix the ASCII representation is most often used and text editors on either a Windows box or a UNIX provide you with the heximal representation.
    On the other hand, EBCDIC is used on IBM mainframes. There, we also have the possibility to show the heximal values. See:.

    All right. Assume, we get a file that contain strange characters. Do we have a EBCDIC/ASCII mix up?
    If we are working on a Windows or Unix box, we see the ASCII representation. We know that the ASCII heximal value of “@” is 40. This 40 is translated into a space under EBCDIC. Hence: if we see in an editor on a Windows/Unix box many “@”, we may suspect that an EBCDIC file is delivered whereby the blanks are translated into ASCII “@”.
    Another possibility is to look at the heximal representation. If we see many “F0”, we may suspect an EBCDIC file as the EBCDIC heximal value F0 stands for a “0”. Hence: many heximal values of F0 indicate EBCDIC as any file may contains many 0.
    Hence: enough clues to find out if an EBCDIC file is delivered in stead of an ASCII file!

  • A set of tables and content

    Yesterday, I encountered a small but convenient script that creates and loads a set of tables in an Oracle environment. It was part of an Informatica training, so I have to give the credits to those guys. Click here to get the Script
    I changed a few things in the script but not much. The major thing, I changed was to replace the insert of dates (done via a string like ‘1998-05-21’) into an insert via to_date(‘1998-05-21′,’YYYY-MM-DD’). This makes the script independent from local settings. I admit: it is a little detail but I believed it is a minor improvement.

    The nice thing about these type of scripts is that someone who wants to get acquainted with a database is given a head start by the provision of a set of tables. One could directly play with relationships, inserts of new records, deletes etc.

  • A date dimension

    Today I had to create a date dimension. This is a dimension that provides us with a list of records that contains the weekdays, the number of a month etc.
    Let me give a screenshot of these records:

    This table helps us to translate a date (like 08 – 25 – 2011) into a day in the week, like Monday, Tuesday. Such translation is by no means trivial. A table that contains the dates, along with, say, weekday names helps us in this task.

    I encountered beautiful scripts to create such a table. I want to refer to http://www.dwhworld.com/2010/11/date-dimension-sql-scripts-oracle/ to see such a script. Similarly take a look at http://kimballgroup.forumotion.net/t52-date-dimension-in-oracle-with-one-sql-statement. Or http://oracleolap.blogspot.nl/2011/01/script-for-time-dimension-table.html. Or http://code.google.com/p/oraclenerd/source/browse/trunk/misc/sql/tables/times.tab . Only one problem: only Oracle scripts.

    For some other DBMS it is also easy to find a script that creates a date dimension. For SQL Server, I noticed http://www.sqlbook.com/Data-Warehousing/Date-Dimension-SQL-script-18.aspx. This script was really helpful.
    For MySQL, I found http://www.dwhworld.com/2010/08/date-dimension-sql-scripts-mysql/. This script was somewhat cumbersome but with some determination I got a nice table of dates in MySQL.

    I also studied the scripts somewhat to see how they worked. The general idea is straightforward in the scripts.
    The first step is to create a table. Let us give the an Oracle script:

    CREATE TABLE Date_D(
    DateKey Integer ,
    DateValue Date ,
    Day Char(10 ),
    DayOfWeek Integer,
    DayOfMonth Integer,
    DayOfYear Integer,
    PreviousDay date,
    NextDay date,
    WeekOfYear Integer,
    Month Char(10 ),
    MonthOfYear Integer,
    QuarterOfYear Integer,
    Year Integer
    );
    

    In a second step, a long table is created that only contains dates. In Oracle this can be done with a statement like:

    select level
    from dual
    connect by level <= 5000;
    

    This creates 5000 records ranging from 1 to 5000.

    The 1, 2, 3 is subsequently translated into dates by:

    select  TO_DATE('31/12/2009','DD/MM/YYYY') +
     NUMTODSINTERVAL(level,'day') datevalue
    from dual
    connect by level <= 5000
    

    This provides a range of dates starting from 1 Jan 2010, 2 Jan 2010 etc .

    This is stored in the target table with:

    INSERT INTO Date_D(datevalue)
    SELECT
    datevalue
    FROM (
    select TO_DATE('31/12/2009','DD/MM/YYYY') + 
    NUMTODSINTERVAL(level,'day') datevalue
    from dual
    connect by level <= 5000);
    

    In a third step, extensive use is made of the date functions to derive the requested fields: the name of day, the weeknumber, the number of the month etc. One then updates the columns with the datevalue that is already loaded. As an example:

    update date_d
    set DateKey = to_number(to_char(datevalue, 'YYYYMMDD'));
    

    and the remainder of the columns is updated with:

    update date_d
    set 
    Day = TO_CHAR(datevalue,'Day'),
    DayOfWeek = to_number(TO_CHAR(datevalue,'D')),
    DayOfMonth = to_number(TO_CHAR(datevalue,'DD')), 
    DayOfYear = to_number(TO_CHAR(datevalue,'DDD')),
    PreviousDay=datevalue - 1,
    NextDay = datevalue + 1, 
    WeekOfYear = to_number(TO_CHAR(datevalue+1,'IW')),
    Month = TO_CHAR(datevalue,'Month'), 
    MonthofYear = to_number(TO_CHAR(datevalue,'MM')),
    QuarterOfYear = to_number(TO_CHAR(datevalue,'Q')),
    Year = to_number(TO_CHAR(datevalue,'YYYY'));
    

    However, I had to create such a table on a Teradata DBMS. Unfortunately I could not find such a script for Teradata. Ok, I then created such a script myself from the date dimensions I created so far on Oracle, SQL Server and MySQL. Hereby I present you such a script with insert statements only. Click here to get the Script. Have fun with it. It only contains statements that Teradata understands: only numerics and strings.

  • JCL or the stern face of a main frame

    I realise that working on a main frame can be very intimidating. Look at the JCL: the job language that you use to get things done. This is the way how you might copy files, how to execute a programme, to compile a programme. This implies that you will use the JCL every day when working on a main frame.

    Let us see how such JCL looks like:

    This is a programme that writes two lines “0 tom” and “1 papa” to a file (or data set as it is called on a mainframe). Oops: to get it done, one needs 9 lines of jcl.
    On the other hand, most of the lines can be reused. Take as an example, the first two lines that give a name to the job. These lines are probably only created once and later copied from job to job.
    I can also imagine that this programme that copies two lines into a file, is used as a skeleton to copy lines into files. Only a change in the lines or the filename is sufficient to perform a new task.

    On book helped me hugely to understand jcl: Murach’s OS/390 and z/OS JCL. This helped me to pass that impressive hurdle.

    But let us go back to the JCL.
    [1] The first two lines indicate the jobname. These two lines can be copied from job to job. They indicate what job is run and who is accounted for the costs of the job.
    [2] The third line indicates what is done. In this case the programme IEBGENER. This programme copies one dataset to another. The programme IEBGENER requires four datasets. These four datasets are described in subsequent lines.
    [3] SYSIN: it must be included but the reason is not really clear in a copy statement
    [4] SYSPRINT: indicates where the job warnings are written
    [5] SYSUT2: the output dataset. As a new dataset is created, the properties must be indicated
    [6] SYSUT1: the input dataset. In this case the input dataset is directly included as an instream dataset.

    One could make minor modifications. Such a modification is given below. In this case the output dataset is an existing dataset and the data are appended to the bottom of the dataset.

    This implies that only the SYSUT2 statement must be changed. The programme below copies the data to the bottom of the output dataset.

    000001 //MAAN093 JOB (12345678),MAAN093,MSGCLASS=H,
    000002 // MSGLEVEL=(1,1),CLASS=A,NOTIFY=&SYSUID
    000003 //STEP1 EXEC PGM=IEBGENER
    000004 //SYSIN DD DUMMY
    000005 //SYSPRINT DD SYSOUT=* KOMMENTAAR VAN NIKS
    000006 //SYSUT2 DD DISP=(MOD,KEEP),DSN=MAAN093.DATA.TXT16
    000007 //SYSUT1 DD *
    000008 01 TOM
    000009 03 INE1
    000010 /*

    Let us go to another programme. Just to show what is possible in JCL. The programme looks like:

    000001 //MAAN093 JOB 'MAAN093',CLASS=A,MSGCLASS=X,NOTIFY=&SYSUID
    000002 //*------------------------------------------*
    000003 //GOOI PROC
    000004 //MAKEFI EXEC PGM=IEFBR14
    000005 //DD2 DD DSN=MAAN093.FLIP.TXT,DISP=(SHR,DELETE) GOOIT OUD WEG
    000006 // PEND
    000007 //*------------------------------------------*
    000008 //STEP EXEC GOOI

    This programme creates a procedure that is called “gooi”. This procedure starts with a declaration: “gooi proc” and it ends with “pend” to state where the procedure ends. This procedure “gooi” contains two lines. One line indicates what is to be done. In this case IEFBR14 is executed: the deletion of a file. The file that is deleted is indicated by the dd2 line.
    The procedure “gooi” is executed in the last line: exec gooi will initiate the gooi procedure.

     
    To finalise, some more examples of JCL code
    Sortprocedure with JCL
     
    Combine two input datasets into one sortprocedure with JCL

     

     

  • Querying a Db2 database on a mainframe

    Recently, I was in a situation where I had to query a Db2 database on a mainframe. I was also in a situation where the knowledge and documentation on that mainframe was not very widespread. So there I found myself, sitting in the dark with only a so-called 3270 screen looking at me, waiting for a first step that I would take.

    The first question: how are the tables called. Second question: what tools to use to query the database.

    I remembered from a distant past that IBM has a so-called “File-Aid” for Db2. This tool has a browse option that allows you to browse interactively tables in a Db2 database. The nice thing about it that the browse mode accepts wild-cards like *. When multiple answers are possible a pop-up appears that gives a clear choice on the possiblities. I used this tools to get a hunch of the table-names and to get a first impression on the content of the tables.

    Once I had a list of filenames, I started with a second tool that gave me more insight. This tool is called “Spufi”. This tool basically uses two files (or datasets as they are called on a mainframe). One file is used to store the SQL statements, whereas a second dataset is used to capture the output. I realised that the two files must be allocated beforehand and that both files could best reside under your own name. I created two files: “tom.input.sql”  and “tom.output.txt”. I then used these two names in the first screen of Spufi where the exact names of input- and output files is being asked for.

    This allowed me to start investigating the database.