What is the downside of structuring SQL tables this way? [closed] - mysql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Let's say I want to create a table like this:
id | some_foreign_id | attribute | value
_________________________________________
1 1 Weight 100
2 1 Reps 5
3 2 Reps 40
4 3 Time 10
5 4 Weight 50
6 4 Reps 60
Versus the same data represented this way
id | some_foreign_id | weight | reps | time
____________________________________________
1 1 100 5 NULL
2 2 NULL 40 NULL
3 3 NULL NULL 10
4 4 50 60 NULL
And since in this case the id = foreign_id I think we can just append these columns to whatever table foreign_id is referring to.
I would assume most people would overwhelmingly say the latter approach is the accepted practice.
Is the former approach considered a bad idea, even though it doesn't result in any NULLs? What are the tradeoffs between these two approaches exactly? It seems like the former might be more versatile, at the expense of not really having a clear defined structure, but I don't know if this would actually result in other ramifications. I can imagine a situation where you have tons of columns in the latter example, most of which are NULL, and maybe only like three distinct values filled in.

EAV is the model your first example is in. It's got a few advantages, however you are in mysql and mysql doesn't handle this the best. As pointed out in this thread Crosstab View in mySQL? mysql lacks functions that other databases have. Postgres and other databases have some more fun functions PostgreSQL Crosstab Query that make this significantly easier. In the MSSQL world, this gets referred to as sparsely populated columns. I find columnar structures actually lend themselves quite well to this (vertica, or high end oracle)
Advantages:
Adding a new column to this is significantly easier than altering a table schema. If you are unsure of what future column names will be, this is the way to go
Sparsely populated columns result in tables full of nulls and redundant data. You can setup logic to create a 'default' value for a column...IE if no value is specified for this attribute, then use this value.
Downsides:
A bit harder to program with in MySQL in particular as per comments above. Not all SQL dev's are familiar with the model and you might accidentally implement a steeper learning curve for new resources.
Not the most scalable. Indexing is a challenge and you need work around (Strawberry's input in the comments is towards this, your value column is basically forced to Varchar and that does not index well, nor does it search easily...welcome to table scan hell) . Though you can get around this with a third table (say you query on dates like create date and close date alot. Create a third 'control' table that contains those frequently queried columns and index that...refer to the EAV tables from there) or creating multiple EAV tables, one for each data type.

First one is the right one.
If later you want change the number of properties, you dont have to change your DB structure.
Changing db structure can cause your app to break.
If the number of null is too big you are wasting lot of storage.

My take on this
The first I would probably use if I have a lot of different attributes and values I would like to add in a more dynamic way, like user tags or user specific information etc,
The second one I would probably use if I just have the three attributes (as in your example) weights, reps, time and have no need for anything dynamic or need to add any more attributes (if this was the case, I would just add another column)
I would say both works, it is as you yourself say, "the former might be more versatile". Both ways needs their own structure around them to extract, process and store data :)
Edit: for the first one to achieve the structure of the second one, you would have to add a join for each attribute you would want to include in the data extract.

I think the first way contributes better towards normalization. You could even create a new table with attributes:
id attribute
______________
1 reps
2 weight
3 time
And turn the second last column into a foreign id. This will save space and will save you the risk of mistyping the attribute names. Like this:
id | some_foreign_id | attribute | value
_________________________________________
1 1 2 100
2 1 1 5
3 2 1 40
4 3 3 10
5 4 2 50
6 4 1 60

As others have stated, the first way is the better way. Why? Well, it normalizes the structure. Reference: https://en.wikipedia.org/wiki/Database_normalization
As that article states, normalization reduces database size & allows for easy expansion.

Related

How to properly organize related tables in MySQL database?

There are two tables - users and orders:
id
first_name
orders_amount_total
1
Jone
5634200
2
Mike
3982830
id
user_id
order_amount
1
1
200
2
1
150
3
2
70
4
1
320
5
2
20
6
2
10
7
2
85
8
1
25
The tables are linked by user id. The task is to show for each user the sum of all his orders, there can be thousands of them (orders), maybe tens of thousands, while there can be hundreds and thousands of users simultaneously making a request. There are two options:
With each new order, in addition to writing to the orders table, increase the orders_amount_total counter, and then simply show it to the user.
Remove the orders_amount_total field, and to show the sum of all orders using tables JOIN and use the SUM operator to calculate the sum of all orders of a particular user.
Which option is better to use? Why? Why is the other option bad?
P.S. I believe that the second option is concise and correct, given that the database is relational, but there are strong doubts about the load on the server, because the sample when calculating the amount is large even for one user, and there are many of them.
Option 2. is the correct one for the vast majority of cases.
Option 1. would cause data redundancy that may lead to inconsistencies. With option 2. you're on the safe side to always get the right values.
Yes, denormalizing tables can improve performance. But that's a last resort and great care needs to be taken. "tens of thousands" of rows isn't a particular large set for an RDMBS. They are built to handle even millions and more pretty well. So you seem to be far away from the last resort and should go with option 1. and proper indexes.
I agree with #sticky_bit that Option 2. is better than 1. There's another possibility:
Create a VIEW that's a pre-defined invocation of the JOIN/SUM query. A smart DBMS should be able to infer that each time the orders table is updated, it also needs to adjust orders_amount_total for the user_id.
BTW re your schema design: don't name columns id; don't use the same column name in two different tables except if they mean the same thing.

Is there a way to add an attribute to only 1 row in SQL?

Take this table as an example :
CREATE TABLE UserServices (
ID BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Service1 TEXT,
Service2 TEXT,
.
.
.
) ENGINE = MYISAM;
Every user will have different number of services, so lets say the table starts with 10 columns for services for each user. If one user will have 11 services, must all other users have 11 columns also? Now of course it is a table and row needs to have the same number of columns, but it is just seems like an awful waste of memory. Maybe the use of another database type is better?
Thank you!!
Storing a boatload of nulls isn't really a "waste of memory" because the space is negligible - hard disks cost pence per gigabyte, programmers cost tens/hundreds of $/hr so it's certainly economical to burn the space and it's not really a great argument for avoidance.
There is a better argument though, as others have said; databases don't do variable numbers of columns for a particular ID in a table, but they DO do variable numbers of rows per ID.. This is how DBs are designed: columns are fixed, rows are variable. Everything that a database does and offers in terms of querying, storage, retrieval, internal design etc is optimised towards this pattern
There are well established operations (called pivots) that will turn your vertical arrangement of data into horizontal (with nulls) at query time, so you don't have to store the data horizontally
Here's a pivot example:
Table:
ID, ServiceIdentifier, ServiceOwner
1, SV1, John
1, SV2, Sarah
2, SV1, Phil
2, SV2, John
2, SV3, Joe
3, SV2, Mark
SELECT
ID,
MAX(CASE WHEN ServiceIdentifier = 'SV1' THEN ServiceOwner END) as SV1_Owner,
MAX(CASE WHEN ServiceIdentifier = 'SV2' THEN ServiceOwner END) as SV2_Owner,
MAX(CASE WHEN ServiceIdentifier = 'SV3' THEN ServiceOwner END) as SV3_Owner
FROM
Table
GROUP BY
ID
Result:
ID SV1_Owner SV2_Owner SV3_Owner
1 John Sarah
2 Phil John Joe
3 Mark
As noted, it's not a huge cost to just store the data horizontally and if you're sure the table will never change/ not need new columns adding on a weekly basis to cope with new services etc, then it might be a sensible developer optimisation to just have columns full of nulls. If you'll add columns regularly, or one day have thousands of services, then vertical storage is going to have to be the way it goes
To expand a little on what's already been said:
Is there a way to add an attribute to only 1 row in SQL?
No, and that's kinda fundamental to how relationship databases (SQL) work - and that's in any version of SQL, whether it's mysql, t-sql, etc. If you have a table - and you want to add an attribute to that table, it's going to be another column, and that column will be there for every row. Not just relational databases - that's just how tables work.
But, that's not how anyone would do it. What you would do is what Alan suggested - a separate table for Services, then a 3rd table (he suggested naming it 'UserServices') that links the two. And that's not a one-off suggestion - that's pretty much "the" way to do it. There's no waste.
Maybe the use of another database type is better?
Possibly, if you want something with less restrictions, then you could go with something other than SQL. Since SQL is so dominant, everything is usually categorized as NOSQL. - Mongo is the most popular NOSQL database currently, which is why RC brought it up.

Dilemma about the number of columns on a table

Scenario:
I am creating a website for a checklist, it can be done/accessed by multiple users in the same time thus it needs certain fields to be editable, saveable and retrievable.
Dilemma:
The checklist has 212 entries, this means 212 rows. I have 5 columns that needs entries thus, 212x5. This means, I have to create 1060 columns to be able for me to code the website to do what I want it to do. 1060 columns on a table seems wrong and very tiring to use.
My Sample solution:
I would divide the 5 columns into 5 tables, making the date that the checklist was created as their primary key. I would then use this 5 tables for their corresponding columns thus reducing the number of columns per table to 212.
Is there anyway that I could reduce this? Sorry for the long post, any help would be appreciated.
**Edit: For some reason, I can't comment on any answers, says error on page. Nevertheless, I do appreciate everybody's answer; Yet I have 1 info that may change your answers. I have thought of making 5 columns instead of the obnoxious 1060, but doing that, I would need/The system would need to create 1 table per 1 worksheet and of course, over time, this would cause massive problems to the database.
Although still pretty huge, ah_hau's answer seems to be the smallest and easiest to handle. By using it, the system would create 217 entries per checklist, but will use 6-8 columns only. Thank you to everyone who shed light into this dillemma, I do hope that I see you guys again on my next question. Cheers!
There are different ways to do it, I'd just store a Json string per checklist. The Json string would be a Json array of object { checklistName, checklistValue, timestamp }. So, the database table would only have two columns { id, checklist }. This is on the minimum side, you might want to break it down to smaller Json objects and/or add more details to them.
looking thrrough all your requirements, thou you've ban the common 6 column setup, I'd still suggest you to use a similar setup.
try to have a table like this
id [bigInt] (PK,auto_incrment)
rowId [int] //checklist row id
columnId [int] //checklist column id
text [varchar/text]
create_date [Date]
create_time [Time]
Index
unique key chekcklist_cell (create_date, rowId, columnId)
depending on your preference, you could also split columnId field into 5 columns with name column1~5 to reduce the DB entry count. But i'd suggest using my setup as it seems like user will update your checklist 1 cell at a time (or multiple cell all around the list), which my schema will make more sense. Also this schema is very expandable and could easily add new fields to them. Last thing I could think of is that you doesn't have to lock the whole checklist while a user is only updating 1 cell. This helps speed up that concurrent access thing.
why not directly add 1 more column in your checklist table?
your table structure should look like
userid
entryid (value from 1-212)
col1_entry
col2_entry
col3_entry
col4_entry
col5_entry

If a database table is expected to grow more columns later, then is it good design to keep those columns as rows of another table?

I have a database for a device and the columns are like this:
DeviceID | DeviceParameter1 | DeviceParameter2
At this stage I need only these parameters, but maybe a few months down the line, I may need a few more devices which have more parameters, so I'll have to add DeviceParameter3 etc as columns.
A friend suggested that I keep the parameters as rows in another table (ParamCol) like this:
Column | ColumnNumber
---------------------------------
DeviceParameter1 | 1
DeviceParameter2 | 2
DeviceParameter3 | 3
and then refer to the columns like this:
DeviceID | ColumnNumber <- this is from the ParamCol table
---------------------------------------------------
switchA | 1
switchA | 2
routerB | 1
routerB | 2
routerC | 3
He says that for 3NF, when we expect a table whose columns may increase dynamically, it's better to keep the columns as rows. I don't believe him.
In your opinion, is this really the best way to handle a situation where the columns may increase or is there a better way to design a database for such a situation?
This is a "generic data model" question - if you google the term you'll find quite a bit of material on the net.
Here is my view: if and only if the parameters are NOT qualitatively different from the application perspective, then go with the dynamic row solution (i.e. a generic data model). What does qualitatively mean - it means that within your application you don't treat Parameter3 any different to Parameter17.
You should never ever generate new columns on-the-fly, that's a very bad idea. If the columns are qualitatively different and you want to be able to cater for new ones, then you could have a different Device Parameter table for each different category of parameters. The idea is to avoid dynamic SQL as much as possible as it brings a set of its own problems.
Adding dynamic column is a bad idea, Actually it's a bad design. I would agree with your second option , Adding rows is OK,
Because if you want to add dynamically grow the columns then you have to provide them a default value, also you will not be able to use them as 'UNIQUE' vals, you will find really hard while updating the tables, So better to stick with adding 'ROWS' plan.

Should I create another table?

I have a table with this structure:
col1 would be "product_name" and col2 "product_name_abbreviated".
Ignoring the id colum I've this data:
1 1 43
1 1 5
1 1 6
1 1 7
1 1 8
2 2 9
2 2 10
2 2 34
2 2 37
2 2 38
2 2 39
2 2 50
I can do another table and put there col1 and col2 columns becouse they are repeated. Something like this:
But I'm sure that it'll not be repeated more than 15 times, so... Is it worth?
Thanks in advanced.
Yes, you should split them out into separate tables - this is an example of normalisation to Second Normal Form.
You are sure NOW, but what about when you will extend your application in one year time? Split the tables
Use only one table with the ID, two VARCHAR columns for the name and abbreviation and a NUMBER for the price.
Normalization is good for avoiding repeating data. Your model is tiny, the data is small, you should not worry and leave one entity (table).
In real projects sometimes we normalize and then realize we got a mess. It's always good to balance between repeating data and easy of understanding the model and querying. Not to mention when working with data warehouse databases...
This is a very basic question in database design and the answer is a resounding "Two Tables"!
Here are just some of the reasons:
If you have one table, then by mistake someone could enter a new row with product name "1" and abbreviated product name "2" The only way to stop this would be to add rules and constraints - far more complicated than just splitting the tables in the first place.
Looking at the database schema should tell you meaningfully about what it represents. If it's a FACT that you can't have a product with product name "1" and abbreviated product name "2" then this should be clear from looking at the table structure. A single table tells you the opposite, which is UNTRUE. A database should tell the truth - otherwise it is misleading.
If anyone other than yourself looks at or develops against this database, they may be confused and misled by this deviation from such basic rules of design. Or worse, it could lead to broken window syndrome, if they assume it was not carefully designed and therefore don't take care with their own work.
The principle is called "Normalisation" and is at the heart of what it means for something to be a relational database rather than just some data in a pile :)