Featured ProjectsPress Releases |
How to Denormalize a Normalized Table Using SQLOften times, we sacrifice some usability in our data in order to follow nth-normal form in our database architecture. This tutorial will teach you a trick that allows us to retrieve name-value pairs of data as denormalized column-value pairs. Let's take the case of a user settings table. A typical denormalized user settings table may look like this: CREATE TABLE denormalized_settings ( This table will create one record for each user, with the setting values placed in appropriate columns. The data will look something like this: user_id setting1 setting2 setting3 setting4 By normalizing our table, we allow flexible control of settings through meta-data identifiers, rather than table definition. The following would be a proper 2nd normal form settings table design: CREATE TABLE normalized_settings ( We could even go a step further and define a "setting_types" table, in order to be third normal form compliant (no repeating identifiers in the "name" column). This is what our final "settings" database could look like: CREATE TABLE users ( So now, what we get is a user_settings table that has very strict data definition, and looks something like this: user_id setting_type_id value But let's say that our application needs to retrieve the normalized data in one row per user.... well then we're stuck... right? Wrong! This is where we have to get creative! The following SQL query will denormalize your data for you: SELECT And the results look something like this: user_id setting1 setting2 setting3 setting4 Look familiar? (Check the data of the first table again!) So there you have it... some clever grouping and SQL data manipulation, and you've denormalized your properly normalized table. |
Design and content copyright Transio, LLC © 2007-2009. All rights reserved. Any and all reproduction without express written consent is strictly forbidden.
Transio
•
Software Development Miami
•
Web Design Miami
•
Web Marketing & SEO Miami
•
Serving Miami-Dade, Broward, and Palm Beach.