I have learnt that VARCHAR occupies the only memory which is required unlike CHAR which always occupy same amount of memory whether needed or not.
My question: Suppose I have a field VARCHAR(50), I know that if it needs to store 30 characters, it will only occupy 30 bytes and no more than that(assuming 1 char takes one byte). So why should I even mention 50 or 30 or any upper limit, since it will only take the memory which is required.
UPDATE: Why do I have to mention the upper limit since there will be no useless memory occupied?
If you are sanitizing your inputs with something like
final_value = left(provided_value, 30)then it’s a non-issue for your database. You can set it tovarchar(255)if you like.The idea of putting the max limit is to ensure you don’t mistakenly send more chars than what you actually plan for.
Would be a pain in the future for code maintenance to recall the data size limit of every column of every table. You need to do that anyway but by looking at your table definitions as the single source for info about that.
Would a table be written to (
insert/update) from only one piece of code in your app or website? If there’s another interface to the database like, say, a REST API listener, if you don’t enter the same values again, you’ll have an issue with non-uniform data – exactly what db’s are able to prevent.If a coding error (or hack) bypasses your app/website controls for data (size limits, or worse) then at least your db will still be maintaining the data correctly.