Do you loop?

I was pulled into a meeting to help out with a query that needed to find some data to update a field. Basically the situation is:
1. a file is received from an external entity that has 2 pieces of information needed for the lookup, a GROUP and a UCC*
2. this file is loaded into a table and then an ETL (Extract, Transform, Load) process is called
3. the ETL needs to know a PriceType that is stored in a table that contains GROUP and VendorID
4. VendorID can be found in a query using the UCC

Ultimately what I need is the PriceType to include in my ETL process.
If I know the GROUP and UCC, I can find the VendorID that is needed to determine the correct PriceType.

So, the current process takes FOREVER – days!! It is using cursors and fetch next into the cursor and a whole lot of things that I don’t get! That is why we were having the meeting…to try and find a way to make the load run in a reasonable amount of time.

So I am listening to the conversation and my co-worker keeps talking about looping through the database to find the VendorID. And I am thinking, maybe I am not getting it, but it just seems like we can take the data we know, GROUP and UPC, and using JOINs get the VendorID. Why would we need to loop? So I asked and everyone agreed that what I was saying sounded reasonable, but weren’t really positive that what I was saying would work.

So, I rewrote this UPDATE_CURSOR statement with a query. I got it 90% there. The query was then put in a table and called as part of the ETL and I was missing a key field to join on in order to perform the update, but once that piece was included the process completed in an hour!

From 27 hours with no completion to complete in an hour! That is the power of joins and thinking in a set. If you are looping through your data set to find data in your tables it try to approach it and see if you can find a way for it to be done in a single query!!

The idea of iterating is a very programmatic approach and has it’s place, but not when you are trying to extract data from a database. You should try to think of everything you want to get and what connections have to be made in order to get that data.

Start with a small query. What is the main table that you need the most data from or has the key field that will be needed to find data in other tables? Write the query that just gets those fields from that main table. Where is the next piece of data that you need? Are there any criteria that need to be applied before JOINing into that data? Can you JOIN into the table or do you need to write a SUB-QUERY to extract just some of the data from that table? Once you get the details of the secondary information worked out, JOIN your main query to that and add the fields you need. It maybe that some of the fields you included you don’t need as output, but you do need as something to JOIN on in a later part of the query.

As you can see, building a query to get your full result set takes some time and knowledge of your database structure but it really how queries are supposed to work.

Now, once your application gets the result set returned, feel free to iterate through it as many times as you like to get data from it, but the idea of running one query to get a piece of information and looping through that data to run another query should now be contrary to all you believe as a Platypus Hunter.

*The UCC is part of the UPC that is on products. It is assigned to a manufacturer and is the first 6 digits in a UPC. Every product a company makes has a UPC that starts with their assigned UCC (more information can be found here http://www.insightu.org/hobby/guide_wd/ch3.htm)

Dealing with a Bad Design – #1

I am sure that there will be many posts about dealing with bad design. So, I am going to number them as we go so I can see just how many different bad designs need a solution!

Duplicate Fields

Like many shops, the Court never had a DBA.  If you look at the Court’s PDB (Platypus Database) it is obvious that developers with no idea on how to create a relational database had “designed” it.  For over 20 years, developers had just added tables as they needed for their specific task.  To make matters worse, the platform is an IBM iSeries (formerly known as the AS400) where, depending on how a program is written, a change to a table design requires the recompilation of all programs that use the table.  And since there was no source control process it was impossible to tell WHICH programs would need to be recompiled.

The solution of course was to copy an existing table that had most of what the new process needed, rename it, and just add a few new fields…viola!!
That was the database design process.

This causes havoc when trying to write applications that need to interface with the database. The first issue, how do you keep all the data synchronized? If you update data in one table, how does it get updated in the other? The second issue, which fields need to be included in a query? The ones from the first table or the second, almost identical, table? Unfortunately in cases like this the only way to know is to ask someone and learn the structure. Eventually you will figure out when to use which table.

Fake Dates

Another example, back in the day when storage was a main consideration and before there were specific date fields, the Court decided to use a six digit INTEGER data type as the ‘Date’ field, YYMMDD. So looking at the date 111 – what date would you figure that to be? Did you guess January 11, 2000? No? huh, I’m surprised that you didn’t see that 😉

Then there was the Y2K issue. A perfect time to fix that bad decision because by then the AS400 DID have a Date datatype. Nope…let’s just add an EIGHT long INTEGER data type to every table that duplicates the six digit date and store the dates as YYYYMMDD.

And again we have to rely on someone making sure that all the dates are updated correctly. But of course there are exceptions. There’s at least one table that the eight digit date did not get added. It has to be joined into another table using the six digit date…but sometimes that data isn’t updated so the query returns no data.

Committing Spreadsheet

But I think one of the more prevalent bad design decisions is not creating the proper many to many structure – committing spreadsheet. Remember in the last post we talked about normalization and the many-to-many relationship of Jurors to Trials. The WRONG way to store this information is to do something like:

TrialID DefendantName Juror1 Juror2 Juror3 Juror4 Juror5 Juror6 ....Juror 25

Here’s why this is wrong. It is rigid – what if someone wants 26 jurors? Now you have to change the table design (and maybe the application) just to add one more person to a Jury Panel. What if they only want 20 Jurors? now there are NULLs in the data for Juror21 – Juror25. (While NULL has its place in databases this is not one of them – NULL means ‘unknown’ – these Jurors are not unknown – they don’t exist, that is a different state.)

Other Platypus Designs

I would love to hear how your PDB is designed! Send me an email or comment on your design issues and I will see if I have a solution to post for you!

Developer Golden Egg

When you have to work with a database where a non-PDB Hunter has committed spreadsheet, you can use SQL to create what SHOULD have been done. Using a UNION we can create the many-to-many table like so:

SELECT 1 as ID, TrialID, Juror1 As JurorID FROM BadTable Where Juror1 is not null
UNION
SELECT 2, TrialID, Juror2 FROM BadTable Where Juror2 is not null
...
SELECT 25, TrialID, Juror25 FROM BadTable Where Juror25 is not null

Now you have a result set that is normalized and can be used as part of another query, to join into, display results from, the same things you could do with it if it HAD been designed correctly.

First Weapon – Understanding the Relational Model

For years I have been and will continue to recommend that anyone working with databases and queries read the following articles

The Fundamentals of Relational Database Design by Paul Litwin

and

Understanding SQL Joins @ devshed.com

These two articles helped solidify my formal education in databases and for years I thought I understood the Relational Model and some of the more advanced SQL Joins…which I did, to a point.  However, to be Platypus Hunters, we must delve deeper and understand how databases are represented by the relational model.

Over the past few weeks I have been reading Exam 70-461: Querying MS SQL Server 2012 Training Kit preparing to become a Microsoft Certified Solutions Associate: SQL Server 2012.  After reading Chapter 1 – Foundations of Querying I feel I have an even better understanding of the relational model and what makes something relational.  So, my Hunters-to-be, let’s discover Cobb and his relations.

There were several “aha” moments reading this first chapter.  The first came from reading this:

A relation in the relational model is what SQL calls a table.  The two are not synonymous.  You could say that a table is an attempt by SQL to represent a relation….

That made me re-think some of my preconceived notions about what I knew about databases, tables and the relational model.

So going forward with an open mind, I read:

Some of the most important principals to understand about T-SQL stem from the relational model’s core foundations-set theory and predicate logic.

Remember that the heading of a relation is a set of attributes, and the body a set of tuples.  So what is a set?  According to the creator of mathematical set theory, Georg Cantor, a set is described as follows:

“By a ‘set’ we mean any collection of M into a whole of definite, distinct objects m (which are called the ‘elements’ of M) of our perception or of our thought.”

Set Theory

Reading this chapter exposed me to concepts that I had knowledge of but no understanding.  I had heard “real” database people refer to tuples but had never really “gotten it”.  I had to go look up “tuple” on the All-Knowing Wikipedia.  As it relates to math it

is an ordered list of elements.   Tuples are usually written by listing the elements within parentheses ‘()’ and separated by commas; for example, (2,7,4,1,7) denotes a 5-tuple.

That was another “aha” for me.  I could see that this was a set of data, like what is returned from a query.  That made sense to me.

Looking into set theory I found that a relation has a heading and a body.  The heading is a set of attributes.  These attributes are referred to by name and type .  The body is a set of tuples.  These concepts become transformed by SQL into something recognizable.  The relation is a table showing the heading as column names and tuples as rows in the table.

(So, remember in the last episode when we said that thinking of a database like a spreadsheet was ok for non-Hunters, this concept is the real deal.)

Do you remember back in elementary school when you learned about VENN diagrams?  You had to draw all those circles that represented MAMMALS and EGG LAYING CREATURES and come up with the INTERSECTION showing Mammals that are Egg Laying Creatures?

Venn Diagram

Venn Diagram

That’s Set Theory – see you know this – you just learned it so long ago, you’ve forgotten!

Back to Cantor’s definition of a set.  It should be considered as a single, whole thing….a SET of something, in this case tuples.  It should be a set with no duplicates (there are exceptions to this in the real world, but theoretically…) and while not explicitly stated, no order to the set – as one of the tek-tip gurus would say, think of a result set as a bag of marbles, all the records jumbled up together – (when, in a query, you add sorting you have created a sequence, not a relation – a topic for another day!)

Predicate Logic

A predicate is defined as an expression that when applied to an object makes a proposition evaluate to either true or false. For instance, ‘hire date greater than 1/1/2012’ is an example of a predicate. For each employee you can evaluate this predicate and create a proposition that returns true if that employee was hired after that date.  Any expression that you can write to evaluate criteria to true or false is a predicate.  Is it greater than another number, does a name match, any other criteria.

Predicate Logic is a core element of the relational model.  Using predicates you can enforce data integrity, filter data, and even define the data model.

While I didn’t study these concepts formally, I did have an intuitive understanding of them. Understanding these concepts will be the first weapon in your arsenal to fight the Platypus Database.

Developer’s Golden Egg

I have decided that when I have some tidbit that might be helpful to a certain group of my readership, the Platypus will give you a Golden Egg – the first one goes to the Developers!  In fact, for a while, most of them will probably be for developers…that is what I did for a long time!

One thing that I tried to do as an application developer was iterate through the results of my queries in my application and not on the database.  Remember, think of the results of your query as a set.  So, if you need to get all the rows that meet some criteria try to figure out a way using a query to just return to your program the information in which you are interested.   Conversely, try not to return ALL the rows and have your application determine which ones meet your criteria, let the database do what databases are good at doing.

Also. try to use aggregate functions when possible.  Don’t bring back a whole record set to your application and count the number of rows, if you just need to know the total number of rows use the COUNT function and just return what you need.

What is a database?

Recently I have been reading ‘Microsoft SQL Server 2012 – A Beginner’s Guide 5th Edition’.  I like the way it describes and gives an overview of database terminology.  There are database components which make up a database system.  The components are database application programs, client components, database servers and the databases.

A database application program is software that is written to access a database.  Most people who use a special program at work that retrieves customer data or vendor data or product information are using a database application program.

A client component is a special program written to interact with a database.  These are usually written by the companies that create databases.

A database server is used to manage the data stored in the database and to interact with the requests sent by database application programs or client components.

A database is a collection of data arranged in a logical manner that can be accessed via a user interface which allows the user to create databases, add, retrieve and modify data and manage the data.

I thought that broke down the components nicely and in a very understandable way.

Unfortunately in the real world the database is rarely “arranged in a logical manner”.  You can only hope that the programmer that was hired to develop some custom application or add onto an Off-the-Shelf application had some clue about the rules of database design and you get to work with data that is normalized.  However, if that was the case you probably wouldn’t be at The Platypus Database web site looking for help.  Most likely the database you are accessing is not normalized, has bad data or some other tragedy of a design flaw.

Hopefully you are here to learn about databases BEFORE you design one and you will be able to pass along a database that follows the rules and will be a joy for someone to work with in the future.

So, let’s start with a few basics.  You can build a database in a variety of database programs:  Microsoft Access, Microsoft SQL Server, IBM DB2, MySQL, Oracle, Paradox, and a few others.  These are just the ones that I can come up with off the top of my head.  Some of these are database servers:  MySQL, Oracle, MS SQL Server and the DB2.  MS Access is usually just a local database but can be set up to act like a database server.  Some are free and some cost money and some offer both a free and paid version.

Most of these programs come with a client component that allow you to access the server or write queries or create stored procedures.  MS SQL Server has SQL Server Management Studio.  MS Access is the client component to access MS Access databases.  Oracle Enterprise Manager Database Control or SQL Developer can be used to connect and manage Oracle databases.

All of these applications that connect to databases depend on SQL – Structured Query Language.  This is how the users tell the database what they want it to do: Create a table, return some data, insert or delete some data.  (If you are a programmer creating or modifying a database application program, you will need to consult the specific programming language documentation to determine how to connect to your database and the requirements for sending queries and processing results – specific programming languages are beyond the scope of The Platypus Database.)  Second only to understanding normalization, the ability to write and understand how queries work is key to efficiently extracting data from the database.

Back to our main question, what is a database?  When most people talk about a database they are usually talking about the collection of tables that hold data.  If you are familiar with spreadsheets you can easily transfer that understanding to database tables.  A column in a spreadsheet correlates to a FIELD in a database.  A row in a spreadsheet equals a RECORD in a database.  Now imagine that all the worksheets in a workbook are TABLES in a database.  So for most people, a good basic conceptual understanding of what databases are, can be summed up as: a collection of DATA, held in RECORDS, which are collected in TABLES and accessed using QUERIES.

But you are not most people, you are Platypus Hunters in training.  So next time we will cover some basics of Cobb’s Relational Model.

Until then, Happy Hunting!

Welcome all Platypus Hunters

Welcome to the Platypus Database – a blog dedicated to the databases all over the world that were not designed, but seemingly put together with very little thought – like the Platypus

220px-Platypus-sketch

Not to malign the poor Platypus, but it does look like no one really thought about how it would look with all those different parts stuck together like that – and it lays eggs, which for a mammal is kind of weird.

About ten years ago I posted this discussion at www.tek-tips.com asking if anyone else had to deal the same issues in their databases that I was finding – no normalization, shortcuts to avoid having to do things the right way, dates, validation (mostly the lack of),  and other situations.  (The thread quickly deteriorated into a treatise on Chimera Database – which almost became the name of this blog but I couldn’t get it to work as well.)

So why am I writing this blog?

I developed many applications against the Platypus Database over the past ten years and learned many things that are useful in certain situations when dealing with bad data and bad design.  You need to learn monster SQL skills and really understand the power of OUTER JOINS to overcome some of the issues you will find.  I would like to share those tips with other developers to help them learn how to use the power of the query to only get the data you really need into your application and minimize database calls.

As a way to continually improve and learn myself, I am working towards my MS SQL Server 2012 certification.  I want to blog about things I find as I learn about MS SQL Server and the studying and testing that I find exciting and want to share.

At this same time, my friend Jenny is trying to find a way to get into the IT world and I have been looking and looking for some web pages that can explain some basics about databases.  Every page that I found was either someone asking for help to design their database or did not mention normalization at all or if it did mention it, didn’t apply it correctly.  If you are going to work with databases in any way, you should understand the basic concepts and how to create a real database that follows the rules.

So, I am finally spurred into action to write about these topics so my friend can benefit and learn things the right way and we can all move towards certification as Platypus Hunters.

Thanks for dropping by, I hope to see you again soon!

Leslie Andrews, Platypus Hunter Extraordinaire