• subscribe
November 20, 2001 12:00 AM

Querying a Real-Life Denormalized Table

SQL Server Pro
InstantDoc ID #22987
Downloads
22987.zip

In real life, you often have to work with data in tables that aren't properly normalized. For example, let's say you want to list in alphabetical order all the residents of an apartment building. This task would be easy with a normalized database, which would have one table to hold just the names of individual residents, each of whom might or might not share an apartment unit with someone else. But in our real-life scenario, the database developer (unwisely) created a table for each apartment, using an array, or repeating group, to store each resident's name.

Listing 1 shows the denormalized Id_Residents table and all its columns. Ugh! The developer thought that because no more than five residents would live in any one apartment (location_id) at a time, creating a repeating group was OK. But suppose someone requests an alphabetized view of all residents in the entire building (as happened to me). How do you create this view without using temporary tables, cursors, or other resource-hungry tools?

My solution was to use the UNION statement along with a subquery that produces a derived table, as the code in Listing 2 shows. First, the subquery creates a derived table that consists of all the names in the Id_Residents table joined by the UNION statement. (Note the alias after the subquery; the alias is necessary when you're using derived tables.) The outer query then selects from this derived table and orders the data alphabetically. Note that the TOP n statement in the view definition is necessary in a view whenever you're using ORDER BY.



ARTICLE TOOLS

Comments
    There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here
  • SP1?
    I know there is a SP1 for SQL 2008 R2 available....and there is a "feature pack" as well... ...
  • SQL database mirroring
    I have SQL Server 2008 R2 Enterprise 64bit on Windows 2008 R2 Enterprise 64bit.  Each SQL Server has...
  • Dell Compellent Disk Drive
    Does anybody has experience with Dell Compellent Disk Drive? Basically, this system manages all disk...
  • Sql server performance tuning
    I need to find a tool that help me to optimize sql server,queries,improve the performance and solve ...