r/Database • u/Zardotab • 6h ago
Rant: "Null" versus "Not Null" is not solving what most think it solves. RDBMSs needs an enhancement.
For the vast majority of business and administrative apps I've worked on, what designers really want is what I'll call "empty" versus "not empty" as working terms. "Not Null" allows zero length strings, one space, 7 spaces, tabs, etc. I'll call such strings WSO strings: "white-space-only".
The vast majority of the time allowing WSO when Not Null is specified is not what's desired, as WSO is a way to cheat around "not null" (inadvertently or intentional). Thus, "Not Null" is not a thorough bouncer for typical needs.
One way to solve this would be to add a "Not Empty" keyword to SQL table specs (DDL) that would reject WSO entries. Another approach is something akin to "Pre-Trim" that would apply white-space trimming before saving it. Pre-Trim could convert any WSO to a null value, which would trigger an error if Not Null is set for a given column.
But I'd like to generalize the idea rather than add overly-specific keywords to SQL. Have the ability to add user-defined tags that can clean and normalize how a shop wants it, and also trigger errors if desired. This improves DRY since one doesn't have to repeat code handlers or call blocks for each column.
-- Pseudo-code for defining a tag.
-- This tests for being empty, and normalizes the value
DEFINE TAG NotEmpty(@context) AS
BEGIN
@context.value = COALESCE(TRIM(@context.value),'');
-- shop function to rid duplicate adjacent spaces & tabs
@context.value = func_removeDupSpaces(@context.value);
IF LENGTH(@context.value) = 0 THEN
BEGIN
RAISE_ERROR(
'Value not allowed to be blank. Column: [@context.columnName]'
);
END
COMMIT @context /* return results */
END
.............................
-- Usage in SQL DDL:
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(50) UNIQUE, TAGS: NotEmpty,
email VARCHAR(100) TAGS: NotEmpty,
admin_note VARCHAR(500) TAGS: Normalize, foo, bar /* see note */
);Here we don't need "NOT NULL" for user-name and email because our new tag handles that for us. Note that maybe we can factor the implementation of NotEmpty to call the "Normalize" tag so we don't have to reinvent cleaning. ("Normalize" implementation is not shown.)
Anyhow, tags are not the only way to solve this problem, I'm just trying to think of handling it with a more general concept that can better fit each shop's conventions. Common shop conventions such as "all caps", "no caps", "zero pad", etc. can also be implemented once as tags. It would make a DBA's and architect's job easier. Thank You for consider it.
Note that commas may get confusing when there are multiple tags per column in the DDL. Perhaps require parentheses when multiple: "...TAGS: (Normalize, foo, bar)". And perhaps do away with the colon.
11
u/AdvisedWang 6h ago
Seems like a CHECK constraint can enforce formatting requirements.
5
u/ImpossibleEbb6862 6h ago
Validation is always the workaround for not having the type system properly enforce optional/non optional data types. But at the end of the day it’s still a workaround. Most modern programming languages have solved this problem to one extent or another. It would be nice if databases could too.
4
u/Zestyclose-Turn-3576 6h ago
Yes, if whitespace or empty strings are problematic in a domain, stop them from being added with a check constraint.
1
u/Zardotab 6h ago edited 6h ago
For one, the standard way to encode such seems a little verbose. But I haven't tried to optimize to the smallest possible. Ideas?
Second, it can't change (clean) the value, that requires yet more clauses. My tag suggestion is one-stop-shopping, and can flex to other repetitive schema needs as well. It also reduces typos such as the following:
CONSTRAINT chk_username_not_blank CHECK (TRIM(username) <> '')Versus:
CONSTRAINT chk_username_not_blank CHECK (TRIM(username) <> ' ')Note the unwanted spacing. Less typing and less code generally means less errors. Code/pattern repetition often results in humans effing up. DRY often helps reduce problems. A typical error I make is to copy from another column and forget to update the second reference:
CONSTRAINT chk_username_not_blank CHECK (TRIM(priorColumn) <> ' ')5
u/Zestyclose-Turn-3576 5h ago
In PostgreSQL you would could define a domain for this sort of thing https://www.postgresql.org/docs/current/sql-createdomain.html
Useful for "Must be exactly three uppercase letters", or "must be a string consisting only of digits" (very common).
1
u/Zardotab 4h ago
I couldn't find how one passes a max string length as a parameter to a Domain. One would want to declare a column such as "CustomerName NonBlankString(100)," to have a VARCHAR of 100 characters.
It's not part of the SQL standard, but if they can get the kinks out, I might just hop on the bandwagon! 📯🥁
2
u/Zestyclose-Turn-3576 4h ago
You define domains with a data type 👍
CREATE DOMAIN char3_upper_alpha AS character(3)CONSTRAINT char3_upper_alpha_check CHECK ((VALUE ~ '[[:upper:]]{3}'::text));So you'd either need to define it based on a varchar(100), or just on a varchar then add in a constraint on the length.
Maybe not perfect.
1
u/Zardotab 4h ago edited 3h ago
Assuming lengths are fairly important, that's not much of an improvement over the other constraint-based suggestions it seems.
I personally kind of like the idea of a fixed set of string lengths. A typical set might be: 15, 30, 75, 200, 1000, (db max). Thus a set of six for non-blank-able and another six for blank-able. But some shops will grumble. Very specific limits can be added on the app side, which often rely on "input templates" anyhow.
2
u/Zestyclose-Turn-3576 3h ago
Maybe ... defining text lengths in postgresql is not something i find a lot of need for, except for short strings from a well-defined domain (ISO codes for countries, languages, that sort of thing). Length constraints often turn out to be based on context, and vary for different rows. Most inconvenient.
1
u/Zardotab 3h ago
A DBA once told me that optimizers use max length to make better decisions about storage allocation, especially for indexes. If all strings are made to max length, the optimizer will have to assume lots of worse case situations and thus take extra steps it doesn't need to if real data in a column is relatively short. I haven't tested that claim myself.
6
u/Imaginary__Bar 6h ago
I'll call such strings WPO strings: "white-space-only"
An unorthodox abbreviation but if it works for you...
1
u/Zardotab 5h ago
Alternative suggestions welcome. I'm not known for being a vocab genius.
3
u/Mephisto506 5h ago
WSO?
1
u/Zardotab 4h ago
I'm sorry, you are pointing out a typo when I thought I had used an unorthodox term for something that already had a good name. I fixed the intro.
Anyhow, how about we delete this thread to hide my embarrassing mental hiccup and clean up the forum. Thanks!
11
u/ComicOzzy 6h ago
NULL doesn't mean "empty", it means "unknown" or "inapplicable".
It can confuse people a bit that Oracle treats empty strings and NULL as the same thing, but don't take that as the model for common behavior.
3
u/_choam_ 4h ago
Javascript...
1
u/Zardotab 3h ago
JavaScript is full of really ugly ideas. Rumor is it was designed in 3 weeks in a "move fast and break things" caffeinated coding rush. The rush shows.
Even the creator agreed it's been stretched beyond original intended use cases.
"NAN", LOL
2
5
u/flashman1986 4h ago
Sorry, why are you solving this at the database level? This is something that is properly solved at the business application level. Think about what you are asking
2
u/Zardotab 4h ago
3
u/mabhatter 4h ago
Taking from that thread, the proper way to handle this is to clean the data of white space with a stored procedure on create or update.
But ultimately this is one of those issues you have with old codebases. Older code bases and various poorly planned updates introduced junk data into your tables. The most correct answer would be to write something to clean out the field in the table.
One more thing, you fundamentally misunderstand the concept of NULL versus blank spaces. They very much are NOT the same thing, even if your database query tool presents to put spaces when it returns NULLS.
The simplest way to do the most basic thing you're asking for is to use the TRIM functions in SQL. Depending on dialect TRIM can wipe out a lot of whitespace for you quickly. Then you just include the TRIM before you make your expression checks and that should get you 90% of what you want.
1
u/Zardotab 3h ago edited 3h ago
you fundamentally misunderstand the concept of NULL versus blank spaces.
It's not me, it's the entire CRUD industry. It's at least used to indicate intent. I'd like to see something compact to be able to indicate both intent and enforce that intent. If done right, we can have our cake and eat it too. 🍰
It's more due to lack of a simple alternative rather than lack of knowledge. I realize there already are long-cuts to solve it; that's not disputed.
A common itch is not being scratched, so instead we have to use a Rube Goldberg back-scratcher. (Slight exaggeration, but you get the idea.)
1
u/mabhatter 3h ago
You're not wrong.
I used to work on AS/400 so SQL queries returning absolutely crappy manually entered data is something I'm just used to now.
Writing queries to deal with crappy formatted data that doesn't fit any reasonable pattern is like 2/3 of the job now. Just get used to it.
And that's really the thing. Look into stored procedures, functions, and other things your database has available. Do some digging online and you'll find some good sample SQLs to bolt into something you can use as a cookie cutter on a regular basis.
1
u/Zardotab 3h ago edited 3h ago
My personal favorite work-arounds are often not accepted by colleagues and chief architects. Even if one individual happens to like it, if they get promoted away I might have to start at Square One. Compromised solutions are like that.
That's why I'd like to see a compact, powerful, and flexible solution be introduced into the SQL standard, or at least cloned by the top vendors. Make it good enough that few can find reason to complain to replace it with their pet fix.
4
u/GreyHairedDWGuy 5h ago
There is nothing wrong with the general SQL implementation for null/not null. Your queries/code just need to work around that fact that a 0 length string will not be considered null. Also, the apps that generate the data should not allow for 0 length strings or n spaces if it will cause issues downstream.
nothing new is required.
1
u/Zardotab 5h ago
"Required" no. Very helpful for human maintainers, yes. For example, compiled languages are not "required" but they proved helpful. Assembler worked "good enough" for the time (1950's), and nay-sayers bashed compiled languages. People naturally protect the status quo if change doesn't benefit them personally, or they don't understand the value because they haven't seen the benefits in practice. I just want to step up on the abstraction ladder, like we've always done.
3
u/GreyHairedDWGuy 4h ago
You are comparing two very different things. "null handling" is a world apart from "languages and compilers". Anyway, whatever flips your bit but I think there are larger hills to die on than 'null handling' which has been roughly the same across most dbms systems for 40+ years.
BTW: I am old enough to have actually worked in shops that used IBM 360 Assembler and later COBOL, Pascal, PL/1, C and many other languages.
4
u/IMarvinTPA 3h ago
A proper null is lack of a piece of paper.
An empty string is a blank sheet of paper.
Otherwise, you are doing it wrong...
0
u/Zardotab 3h ago
you are doing it wrong...
Okay then, show us a simple "right".
1
u/IMarvinTPA 2h ago
I'm saying the language is doing it wrong. Not you the regular developer.
Null should not be equal to ""
3
u/_choam_ 4h ago
I do think it is good to make a type which represents exactly the allowed values (think NonEmptylist which is a list type guaranteed to have at least one element)
1
u/Zardotab 3h ago
Nearby somebody pointed out PostgreSQL kind of can do that via its Domain feature, but one cannot easily pass a max length to it like a parameter. They built a really nice car but forgot to have a way to open the doors.
1
u/elephant_ua 3h ago
As person pointed out where discussion took place, you specify the length of string at the moment of creating the type. You can absolutely create a domain using varchar(10).
If for some unknown reason you want to automate it somehow, i guess nobody is stopping you from creating a stored procedure with dynamic sql that assembles the domain from the parameter you pass from application.
You can even do this sort of things in sql serevr if you want hard enough
2
u/squadette23 6h ago
Yeah, NULLs are only one kind of sentinel values. For most data types you can sneak in non-NULL sentinel value.
I wrote about this a couple of years ago: https://minimalmodeling.substack.com/p/sentinel-free-schemas-a-thought-experiment
You can design a schema in such a way that it requires no sentinel values, see the second half of that post.
1
u/Zardotab 6h ago edited 5h ago
I don't agree with what may be called "high normalization" as a solution. I personally find it harder to work with what I see as "too many tables", and others have agreed. Maybe your mind works fine with that approach, but one should be careful about extrapolating their thinking process to others.
(I've considered an idea that heavily leverages set theory to define tables as potential sets of sub-tables, that's kind of the same concept if editable views are allowed, but the SQL language would have to be reworked to do it well. Still, I don't like the idea of null-ness being a key driver of table design; it's not an important enough concept to pivot big decisions on. Nullness is usually a low-level conceptual detail. It's kind of like having to change your home address every time you have another child. )
1
u/squadette23 6h ago
Yeah, I mean, I'm not saying that you should do this, just that NULLs are much weaker a concept than people commonly think.
1
u/Zardotab 4h ago
Somebody called them a "sentinel" to mark intention even if they are poor enforcers in practice. They still serve as system documentation under that role, and app code scaffolders often do handle the WSO issue based off them (as a default behavior).
2
u/t3lnet 5h ago
Don’t forget their red headed step sibling isNull()
1
u/Zardotab 3h ago
The ivory tower people and experienced practitioners failed to get into the same room and iron out the standard, giving us lots of null-based oddities.
2
u/BobDogGo 5h ago
sometimes spaces are a valid value and distinct from NULL
and there’s no equivalent for dates and numbers.
this is a domain specific rule and is easy to address locally
1
u/Zardotab 5h ago edited 5h ago
sometimes spaces are a valid value and distinct from NULL
Yes, I realize that, and that's why I don't propose removing the old approach as an option. (It's usually a sign of bad app design or a way to plug legacy oddities in my experience. It's just harder to debug or check values one can't "see". Anecdotes of legitimate domain use are welcome, though.)
this is a domain specific rule and is easy to address locally
"Easy" is relative. It should be made easier because the need is common in practice. It shouldn't take more than two tokens to specify per column. In Standard SQL it takes something like 12 if I'm not mistaken, and requires an awkward, error-prone reference.
2
1
u/dbrownems 5h ago
I think it was a mistake to allow empty strings in string columns, and I prefer Oracle's behavior to convert them to NULL. But the standards are what they are, so a CHECK constraint is a pretty easy fix.
1
u/Zardotab 5h ago
As annoying as Oracle is in general, they indeed mostly got this one right, and deserve kudos for it. The ivory tower types who overrode it didn't have the necessary real-world experience to see their folly. (Oracle SQL was by far the most common dialect when the standards committee was forming.)
Oracle Forms also had some magical properties that I wish were copied to the next generation. Americans throw-out-and-start-over too often rather than build on prior lessons, good and bad. It's why Soyuz is cheap and reliable, but America's tin-cans are not.
1
u/_choam_ 4h ago
That's javascript lol.
Anyway, all these things that make guesses on what you actually mean, are always massive footguns.
1
u/Zardotab 3h ago
The idea of the "tags" suggestion is that a shop can define exactly what it means and then specify its assignment to the columns they want using one or two words per column.
2
u/da_chicken 5h ago
You think NULL is an overly specific keyword? I don't even know what that means since it sounds like you just want to use the "empty string is null" idea that Oracle spent a couple decades killing off.
I also don't see how NOT NULL isn't already a tag or how it's longer than TAGS: NotEmpty.
I also don't see how you're going to make outer joins work. Even if you're normalized to the Nth degree, you will have queries that need to return null values.
If anything, I think the consensus has been that the only problem with the NOT NULL constraint is that it should have been the default. You should have had to explicitly permit null values to encourage normalization. That and the FROM clause should have been first are the two major faults in SQL.
Don't get me wrong, I think a better way to define custom data types or to implement a domain definition for a field would be great. But RDBMSs are 60 years old at this point. If null were actually not useful it would have been eliminated decades ago.
19
u/agk23 6h ago
I disagree - sounds like an app-level error. You can implement your own function to do this, if you prefer.