News for hackers. Stuff that matters.
Re:SQL: The difference between WHERE and HAVING by barrkel on Tuesday December 14, 2021 @08:34AM (#29551285)
There's no good reason for using two different keywords for filtering and it harms composability. But of course SQL isn't very composable anyhow.

Preferably, SQL would look more like:

  FROM Foo f
  WHERE f.value < 10
  JOIN Bar b on b.id = f.bar_id
  WHERE b.other_value > 20
  SELECT f.group, f.value
  GROUP BY f.group the_group AGGREGATING SUM(f.value) the_sum
  WHERE the_sum > 100
  ORDER BY the_group
And so on. FROM introduces a source of data which flows into the next line. SELECT does a projection, GROUP BY applies aggregation operators on groups and also does a projection. WHERE could be inserted pretty much anywhere.
Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @08:38AM (#29551318)
If you want to see an incredibly successful data manipulation system that works exactly as you describe, you should check out R's dplyr package immediately. To me it's the perfect composable SQL API, but hardly anyone knows about it outside of R/RStudio/tidyverse aficionados!

It also cross-compiles to SQL and can thus be used to build queries, although the result is not necessarily the most efficient. Someday I hope someone with expertise in compilation and query optimization will take a look at dplyr and figure out how to get it to generate optimally efficient SQL.

If we did that, and also ported dplyr to some other languages, programmers might never have to hand-write SQL again. (LINQ might be a good way too, but I know much less about it)

Re:SQL: The difference between WHERE and HAVING by flakiness on Tuesday December 14, 2021 @09:20AM (#29551753)
Kind of sad Hadley Wickham isn't as prolific as a paper writer anymore. These papers [1] were, as its nature, very consumable even for someone outside R community. I liked them a lot.

[1] https://scholar.google.com/citations?user=YA43PbsAAAAJ&hl=en...

Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @09:36AM (#29551937)
Totally agree... but if I have to choose between him writing papers and spending more time perfecting APIs, there's no question. The man is one of the most brilliant interface designers ever to live.

Dplyr was already great in its first version, but Hadley and company have worked incredibly hard to make it much, much better. It's hard to think of another system that has improved so much from such an already high starting point.

Re:SQL: The difference between WHERE and HAVING by flakiness on Tuesday December 14, 2021 @01:05PM (#29554960)
That's fair point. I'm mostly on Python so I cannot complain.
Re:SQL: The difference between WHERE and HAVING by BoiledCabbage on Tuesday December 14, 2021 @09:13AM (#29551664)
If you like dplyr in R, you really should check out Linq. Dplyr as nice as it is doesn't remotely compare to how sensible and ergonomic Linq is.
Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @09:18AM (#29551719)
I've heard! I don't have much occasion to use Linq as a data scientist, but will definitely keep an eye out if I ever write C#, etc.
Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @08:42AM (#29551361)
Yup. To be blunt: SQL is a flawed old language that should've been replaced decades ago, but every time somebody tries to replace it they throw the baby out with the bathwater and throw out the relational theory too.

It was a fine language for its time. So was Pascal, and FORTRAN. We don't use those anymore generally for a variety of good reasons.

SQL ANSI nulls alone are a good-enough reason to toss it. Any language where "x = x" commonly returns an object that is treated as falsey is broken.

edit: I'm getting "You're posting too fast" so I can't continue this conversation, but no being able to express "unknown" is not worth throwing out the reflexive property of equality. That is a bad trade-off and I will die on this hill.

Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @08:53AM (#29551464)
> SQL ANSI nulls alone are a good-enough reason to toss it. Any language where "x = x" commonly returns an object that is treated as falsey is broken.

Nah. One of the most common uses of null is to communicate missing values in the sense of "this entity has this attribute but we don't know what its value is". This is a fundamental feature needed in data management.

So say you've got data on two balls A and B. You don't know what the color of either ball is. Is color(A) = color(B)? What's the best answer to this question?

Obviously it's "we don't know", and the value we use to communicate "we don't know" is null.

SQL nulls aren't broken. They're just a third option outside of True/False that needs its own handling, because reality is complicated.

PS: Contrary to popular opinion in certain coding circles, floating point arithmetic isn't broken either. It's a beautiful, delicate tool that works the way it does because it must in order to support its use cases (e.g. numerical linear algebra and representing continuous physical quantities). If it doesn't work exactly the way you want, you may need a couple guardrails or a different system like fixed point arithmetic.

Re:SQL: The difference between WHERE and HAVING by wyager on Tuesday December 14, 2021 @09:17AM (#29551703)
> One of the most common uses of null is to communicate missing values in the sense of "this entity has this attribute but we don't know what its value is"

The correct way to represent this, which has been widely used for several decades now, is sum types. If your value might be unknown, you need to explicitly represent this in the type of your value (e.g. Optional<Foo>) instead of relying on a hack that allows subverting the type system.

Re:SQL: The difference between WHERE and HAVING by ttfkam on Tuesday December 14, 2021 @09:44AM (#29552032)
You're approaching this at too low a level. SQL is a 4th generation language, quite possibly the only successful 4GL. Unlike every other major language, it doesn't deal with "how" you get the answer. You see the "how" with commands like EXPLAIN. Instead it focuses on "what" you want and letting the engine figure out how to get there.

Optional<Foo> lends itself well to functional programming and prevents things like null pointer errors, but that's still at 3GL level, the EXPLAIN level. SQL doesn't throw null pointer exceptions. Ever. The query syntax is correct or it isn't. The same concerns in a programmatic language simply do not apply, which is why Optional<Foo> is a poor fit in this context.

Null in SQL is not the null in JavaScript or C++. Same name, but not the same animal, and I think this is what trips folks up. In your mind, replace SQL's null with a new keyword, UNKNOWN, and it makes more logical sense.

SELECT ... FROM ... WHERE x = UNKNOWN;

Even if x were UNKNOWN in a row, is it the same unknown? For example, if you see two girls, but you don't know their birthdays. Their birthdays are unknown.

WHERE Keasha.birthday = Cynthia.birthday

This partial statement would always be false no matter what until you know both of their actual ages. Just because something is unknown doesn't mean it's the same unknown.

Set theory, not a programmatic series of steps as found in most languages. And that's what SQL is: a DSL for set theory.

I believe it's advantageous to avoid nullable columns in relational schema design, but that's a separate issue from the concept of NULL in SQL as distinct from programmatic languages.

Re:SQL: The difference between WHERE and HAVING by matwood on Tuesday December 14, 2021 @09:55AM (#29552173)
> I believe it's advantageous to avoid nullable columns in relational schema design, but that's a separate issue from the concept of NULL in SQL as distinct from programmatic languages.

Agreed, but they should be used where appropriate. My favorite example of a nullable column is an end date. Until an end date occurs, it's unknown - thus null. Representing the unknown end date with anything other than null is semantically incorrect, and in many cases can lead to errors.

Re:SQL: The difference between WHERE and HAVING by wyager on Tuesday December 14, 2021 @09:36PM (#29561392)
Supporting sum types is not in any way incompatible with being a query or logic language.
Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @09:20AM (#29551750)
I agree, and more sophisticated analytics data structures, like R's data frame, do have "typed nulls" (except in R they're called NAs).

I don't know, and would love to know, why databases have been so slow to adopt this.

Re:SQL: The difference between WHERE and HAVING by wongarsu on Tuesday December 14, 2021 @09:26AM (#29551818)
You could argue any SQL value not marked as NOT NULL is an Optional<Foo>, with NULL being the None value. It's not really subverting the type system, it's just an unconventional choice.
Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @02:07PM (#29555907)
Yes, but I can't think of any language where, given Optional<Foo> x and y, x.equals(y) would return null instead of either true, false, or an exception if y is null.

That's what makes SQL null-values distinct - the fact that expressions that return booleans can return NULLs.

Re:SQL: The difference between WHERE and HAVING by housecarpenter on Tuesday December 14, 2021 @10:06AM (#29552300)
In the relational model used by SQL, types are atomic. Sum types are inherently non-atomic. I'm sure you could graft them onto the language, the same way Postgres can have JSON type fields and all that, but I don't think you'd be able to really integrate them into SQL without fundamentally changing what kind of language SQL is.
Re:SQL: The difference between WHERE and HAVING by wyager on Tuesday December 14, 2021 @09:37PM (#29561397)
The query algebra is completely compatible with sum types. I don't think "atomic" is describing anything central to the QA model.
Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @09:21AM (#29551762)
If 3-value logic is such a good idea, why doesn't any modern general-purpose language use it?

And even if it were a good idea, leaving the user with no built-in operators, not even a simple COALESCE(bool) to properly manage the null complexity? That's unacceptable.

Given a SQL boolean expression `f(b)` that can return true, false, or null, how do I test if `f(b)` has returned NULL? How do I handle that NULL case?

ANSI SQL gives users a strange new paradigm for boolean algebra and then says "GLHF" and gives you zero tools to handle the situation, not even linguistic features that would let you roll your own boolean-based functions, since you can't write SVFs that take boolean parameters.

I mean this trashboat of a language doesn't even let you bind boolean to a variable! You have to deal with the PITA of converting from Booleans to bits because those are totally different things.

Re:SQL: The difference between WHERE and HAVING by matwood on Tuesday December 14, 2021 @09:51AM (#29552117)
> If 3-value logic is such a good idea, why doesn't any modern general-purpose language use it?

Many languages have a null/undefined of some sort, but they are often simply coerced to false. But, for a language whose sole purpose is to manipulate data the null value nearly always has meaning.

> Given a SQL boolean expression `f(b)` that can return true, false, or null, how do I test if `f(b)` has returned NULL? How do I handle that NULL case?

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

Section 8.6, the null predicate.

`where f(b) is null`

> ANSI SQL gives users a strange new paradigm for boolean algebra and then says "GLHF" and gives you zero tools to handle the situation.

It's also not a strange new paradigm, and is in fact built on foundational topics. Relational algebra and set theory are not new concepts.

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @12:00PM (#29554000)
The term 3-value logic pretty obviously implies the behavior of operators as they relate to NULL, not just the fact that data is nullable, of course.

AFAIK MySQL, Oracle, and SQL Server don't have the Boolean datatype as a variable/column type - only Bit, which lacks boolean semnatics, and so Booleans are not considered data values, and therefore can't be used with IS NULL or COALESCE.

Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @09:26AM (#29551814)
Because you can implement 3-valued logic using boolean logic in a general-purpose programming language if you need it, and most applications don't benefit from the extra nuance and complexity. But data management sure does, as I illustrated in my post with the color example.

Notice that databases, with their 3-valued logic, are written in a systems language like C/C++, a general-purpose programming language with boolean logic.

Some systems are best thought of using non-boolean logic. Quantum systems are another example. You can simulate just about anything with a Turing-complete language, but it doesn't mean that standard computation with boolean logic is the best way to think about every domain.

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @03:44PM (#29557377)
> Because you can implement 3-valued logic using boolean logic in a general-purpose programming language if you need it, and most applications don't benefit from the extra nuance and complexity.

Surely if it were beneficial you'd see more people doing it, but I have literally never encountered software outside of SQL that does it. I could probably implement it in C++ or C# in an afternoon using enums and operator overloading, at least for the boolean-boolean operators. A little longer to make comparison operators for the other basic types that would yield nulls when compared to null. But nobody does this. Why?

Re:SQL: The difference between WHERE and HAVING by civilized on Wednesday December 15, 2021 @11:21AM (#29568022)
> Surely if it were beneficial you'd see more people doing it, but I have literally never encountered software outside of SQL that does it.

Do you see SQL as some weird little edge case of data management? 99.9% of all serious data management happens in a database server with a SQL interface. Maybe other languages don't implement 3-valued logic because they don't need it, because they don't need to do data management, because they'd be bad at data management.

It's not even true that languages outside SQL don't have 3-valued logic. They may not have it built into the base language, but analytics packages like Python/pandas and R certainly have some version of a null or NA, and nobody would question the value of it for a second. And databases are typically implemented using C/C++, so there's another example of someone using a general-purpose programming language to implement 3-valued logic (as part of the SQL implementation that is written in C/C++).

It's not like SQL is some weird separate language on a different planet as your favorite general purpose programming languages. It's implemented with those languages. So there's your 3-valued implementation right there. When the feature is valuable, it's implemented, and not before.

Re:SQL: The difference between WHERE and HAVING by Sankozi on Tuesday December 14, 2021 @09:34AM (#29551916)
> Nah. One of the most common uses of null is to communicate missing values in the sense of "this entity has this attribute but we don't know what its value is". This is a fundamental feature needed in data management.

I rarely use nulls like that. And then only for things outside of SQL databases like lazy loading or caching. And even then I still prefer null == null to be true.

If nulls are for what you have written then why we are calling them "null" - no value? Why not calling them "unknown". Even then what is benefit in introducing non boolean logic to a relational query language? I have never seen anyone using any of three-valued logic benefits when writing SQL. Every time I get unknown logical value it means I have made a mistake in my query, which would be better handled by rising an error.

Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @09:59AM (#29552206)
> I rarely use nulls like that.

Well, what can I say? Other people need them, and I illustrated why.

> And even then I still prefer null == null to be true.

Some databases have alternate operators, like <=>, that make null == null true. And you can always coalesce null to a sentinel value if your dialect doesn't have this operator. Heck, if you're writing SQL using templates, you could have the template language replace a <=> b with coalesce(a, 99999999) = coalesce(b, 99999999) (or whatever other sentinel value you want to use).

Re:SQL: The difference between WHERE and HAVING by FedericoRazzoli on Tuesday December 14, 2021 @07:43PM (#29560401)
The problem, though, is that SQL standard treats NULL as unknown or as missing. One word for two meanings.

For example, AVG(col) and COUNT(col) treat it as a missing value (NULLs do not alter the average or the count), but 1 + NULL treats it as an unknown value (the result is unknown). The complete list of NULL-related inconsistencies would be long.

It would have been better to use different words for different semantics, or not implementing NULL at all. Also, in some cases it can lead to poor query performance.

Re:SQL: The difference between WHERE and HAVING by civilized on Wednesday December 15, 2021 @12:19PM (#29568850)
I emphatically reject the idea that having an imperfect null is worse than no null at all, but I understand frustrated programmers may have different beliefs.
Re:SQL: The difference between WHERE and HAVING by aidos on Tuesday December 14, 2021 @09:27AM (#29551832)
Yup. The semantics are great for joins. Two missing bits of data do not make a found.
Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @09:33AM (#29551895)
Then why doesn't it error out when faced with NULL?

I mean, we hear over and over again when learning SQL "NULL bool and FALSE are different things"...

But the SQL engine itself treats NULL and FALSE as equivalent all the time.

    DECLARE @x INT = NULL 
    SELECT 'foo' WHERE @x = 1
If three-value logic were truly embraced, that should be an error, because we don't know the state of @x. But SQL talks out of both sides of its mouth about Booleans. It freely just assumes that null is false, which we, as developers, are never ever ever allowed to do. There isn't even an operator included in ANSI SQL to let us convert null boolean values into false, because for some reason bits and bools are two different things and you can't just say

   COALESCE(x = y, false)
It's not just that three-value-logic is painful, it's that SQL makes working with them miserable because, at a linguistic level, it seems to politely forget that three-value-logic exists.
Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @03:21PM (#29557011)
> There isn't even an operator included in ANSI SQL to let us convert null boolean values into false, because for some reason bits and bools are two different things

“bit” is not a standard SQL type at all, it's an SQL server proprietary 1-bit numeric type. boolean is an standard SQL type, but SQL Server doesn't support it as a storage type or consistently elsewhere (it does exist, annoyingly, in some contexts, but is limited in where it or expressions producing it can appear, which—not any limitation of standard SQL—is the source of your problem.)

> and you can't just say COALESCE(x = y, false)

In something that supports standard SQL in the relevant parts, like Postgres, yes, you absolutely can.

In SQL Server, you have to do something clumsy like:

  CASE
    WHEN x=y THEN 1
    ELSE 0
  END
But that is “SQL Server is broken and barely supports booleans even as intermediate values” not “standard SQL is broken”.

There are plenty of valid criticisms of standard SQL around NULLs, but the particular brokenness of SQL Server’s handling of booleans is not one of them.

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @04:37PM (#29558237)
AFAIK MySQL and Oracle have the same flaws.
Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @05:33PM (#29559048)
MySQL and Oracle also lack standard boolean support while allowing true boolean values as results in certain positions, AFAIK, yes, although some versions of MySQL use “Boolean” as an alias for tinyint(1) and even more support TRUE and FALSE (without quotes) as aliases for 1 and 0, which confuses the issue a bit.

SQLite has a similar problem, averts the practical because it doesn't use booleans natively internally in which they apply, instead natively using 0 and 1 (with TRUE and FALSE as aliases) and then converting to boolean in the narrow set of boolean contexts. This means that can use COALESCE as described (and, generally, SQLite will behave as you would expect with real Boolean support, even though it doesn't actually have it.)

DB2, from what I can find, supports BOOLEAN from v11.1.

In any case, the problem here is not a standard SQL problem, even if it is a problem of several popular SQL implementations.

Re:SQL: The difference between WHERE and HAVING by piaste on Tuesday December 14, 2021 @09:51AM (#29552126)
I don't know why OP described SQL NULLs as 'three-valued logic' because it's anything but.

SQL boolean operators can only result true or false, there isn't a third option.

NULL is a data value for all data types, which happens to return 'true' to the boolean operation 'is null', and 'false' to any other boolean operation. NULL = NULL or NULL = 1 don't return a third-option NULL, there is no such thing, they return a plain old 'false'.

(NULL = NULL returns false because otherwise it would make outer joins terrible)

As you pointed out, SQL does not implicitly convert boolean values (bits) to or from the result value of boolean operators. Bits are values and can be NULL. Boolean results are not values and can only be true or false.

Now, is this optimal? Hell no. (Sum types would probably be the way to go if SQL were designed 50 years later.) But it's consistent.

Re:SQL: The difference between WHERE and HAVING by civilized on Tuesday December 14, 2021 @07:19PM (#29560141)
> SQL boolean operators can only result true or false, there isn't a third option.

What...? Go type this into your favorite DB and get back to me:

SELECT TRUE AND NULL

Re:SQL: The difference between WHERE and HAVING by piaste on Wednesday December 15, 2021 @03:45AM (#29563451)
In your example, "TRUE AND NULL" is a value, it's not a boolean condition.

What is the difference? Try this:

SELECT CASE WHEN (TRUE AND NULL) THEN 'A' ELSE 'B' END

Now "TRUE AND NULL" is a boolean condition, and it will return false, and the boolean conditional will evaluate to 'B'. If SQL had three-way logic, some expressions inside the parentheses would make the whole conditional return NULL, but it will always return either 'A' or 'B'.

Re:SQL: The difference between WHERE and HAVING by civilized on Wednesday December 15, 2021 @11:55AM (#29568512)
Ah, I got it now. Yeah, it's definitely weird how nulls reproduce themselves in values (when appropriate), but they get treated as zeros or false in boolean conditions. Base R has more consistent behavior, e.g. if you index into a data frame with an NA, the NA will give you a row full of NAs.
Re:SQL: The difference between WHERE and HAVING by Pxtl on Wednesday December 15, 2021 @02:50PM (#29570738)
It's almost as if the people designing SQL engines realized how furiously inconvenient null boolean semantics were and chose to ignore them wherever it suited them.

I just wish they'd ignored them in one more spot: equality checking.

Re:SQL: The difference between WHERE and HAVING by Taywee on Tuesday December 14, 2021 @09:49AM (#29552098)
Because then you couldn't do a join across non-mandatory foreign keys. Practically, making all NULL comparisons error out would make them almost entirely useless.
Re:SQL: The difference between WHERE and HAVING by mrbungie on Tuesday December 14, 2021 @08:48AM (#29551413)
It may be flawed, it may be old, but it clearly continues to be sufficiently expressive and useful.

Every time someone tries to replace it, it eventually comes back again. Just look at the recent NoSQL and Big Data craze, and then how we're today with a miriad of SQL engines.

Re:SQL: The difference between WHERE and HAVING by qsort on Tuesday December 14, 2021 @08:53AM (#29551468)
I think GP is correct when he says "every time somebody tries to replace it they throw the baby out with the bathwater and throw out the relational theory too".

However, I would add that SQL is a very strong local optimum: a "good" language that keeps the good parts would be insufficiently different from actual SQL to convince anybody to switch.

Also people forget that querying is only half of the equation, there's DDL too.

Re:SQL: The difference between WHERE and HAVING by setr on Tuesday December 14, 2021 @09:43AM (#29552028)
DDL is a bit curious, because it’s less a programming language and more of a set of configuration and operational commands. It just happens to look similar to DQL, but there’s nothing really pushing that beyond the fact that DDL can rely on DQL as a subexpression (eg create view as …). You could probably say the relationship between DQL and DDL is largely aesthetic

The only reason I can think of where you often can’t strictly treat DQL and DDL as totally different languages is the just from the total lack of interest in consistency in SQL language design generally — eg update and delete steal parts of DML syntax haphazardly and differently; the syntax for update/delete data referring to another table

   UPDATE table WHERE … JOIN … 
vs

   DELETE FROM table USING … 
The lack of complexity in DDL generally (its very wide, but not very deep; there’s not much meaningful composition to be discussed) and its lack of a real relationship to DQL is probably why no one discusses it much
Re:SQL: The difference between WHERE and HAVING by barrkel on Tuesday December 14, 2021 @09:07AM (#29551595)
I'd hang on to NULLs, but I'd propagate nullability in the type system. That could mean disallowing anything but non-nullable boolean as filter predicates, forcing the use of COALESCE for clarity and explictness.
Re:SQL: The difference between WHERE and HAVING by wyager on Tuesday December 14, 2021 @09:19AM (#29551723)
By far the best option would be to add support for sum types and pattern matching. Besides being tremendously useful in its own right, it would also eliminate the need for nulls.
Re:SQL: The difference between WHERE and HAVING by barrkel on Tuesday December 14, 2021 @10:24AM (#29552525)
I don't think that's right; absent data is really common and a desirable feature, and ergonomically handling it warrants built-in support.

Outer joins inherently require a concept of absence of data, so you'd need a built-in Optional type which would be nullability in all but name. And you'd want lifting of operators on the inner type to the optional type for ergonomic reasons; doing a pattern match for every selection of bar.* where bar is left-joined would be extremely painful. I think you'd end up where you started on the null front.

Sum types generally, for columns etc., maybe (pun not intended), but I'm skeptical about complex types in a relational language - structure ought to be represented as relations where possible so that everything else composes.

Re:SQL: The difference between WHERE and HAVING by wyager on Tuesday December 14, 2021 @09:38PM (#29561402)
It would be ergonomic - you'd just use a variant of the equals operator specialized to Option<A> that behaved in the way you wanted.
Re:SQL: The difference between WHERE and HAVING by qsort on Tuesday December 14, 2021 @08:56AM (#29551494)
> SQL ANSI nulls alone are a good-enough reason to toss it. Any language where "x = x" commonly returns an object that is treated as falsey is broken.

Seems like an attempt to throw the baby out. 3-valued logic anyone?

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @09:21AM (#29551769)
If 3-value logic is such a good idea, why doesn't any modern general-purpose language use it?
Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @02:49PM (#29556536)
> If 3-value logic is such a good idea, why doesn't any modern general-purpose language use it?

Most dynamically typed general-purpose languages use a large-number-of-values logic, they just use a different formulation than SQLs 3VL. Particularly, nulls tend to be equal to each other, and only propagate from basic boolean ops where false would, not whenever they are an input. (Though IEEE 754 NaNs, which most use and are another flavor of null-like value, are not equal to each other, and, in the case of quiet NaNs, propagate a lot like SQL nulls through arithmetic operations [though not consistently through other language features].)

Re:SQL: The difference between WHERE and HAVING by ttfkam on Tuesday December 14, 2021 @09:50AM (#29552102)
Optional<Boolean>

As found in a few general purpose languages.

Hell, JavaScript has true, false, null, and undefined. 4-value logic!

The real world upon which we model our code has a "true", "false", and "can't tell yet; not enough info". As inconvenient as it feels psychologically, you can't deny the fundamental reality of the third, "can't tell yet", state.

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @01:29PM (#29555282)
Yes, those languages have nulls, but the nulls don't display the strange operator semantics of SQL ANSI nulls.

In JavaScript, null == null yields true. "Test" == null yields false. In SQL, those expressions yield null. SQL is afaik unique in its belief that algebra involving nulls should yield nulls instead of boolean values. That's what's meant by "three value logic", and that's what I find problematic. It violates several mathematical rules, like the reflexive property of equality.

Re:SQL: The difference between WHERE and HAVING by Taywee on Tuesday December 14, 2021 @02:31PM (#29556249)
SQL doesn't have this "belief". SQL has the behavior that is most useful for querying and joining when some columns have unset values, or foreign key relations that are unset.

I understand your position, but your idealism would be strictly worse in real life. Can you imagine if an optional foreign key relation immediately made all joins fail because one was unset? Or if a join between two optional values made all NULL values join together?

The SQL NULL behavior also allows UNIQUE nullable columns to have more than one instance that is NULL, so you can have uniqueness over a column that may also be unset.

If you're a purist or an idealist, SQL NULL might be a mess, but pragmatically, it's the only behavior that is sane for SQL as-is.

Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @02:39PM (#29556378)
> SQL is afaik unique in its belief that algebra involving nulls should yield nulls instead of boolean values.

Really? The basic operations of boolean algebra or AND, OR, and NOT.

In JavaScript, what is:

1. null && true

2. false || null

3. !null

Well, one of them produces a boolean result, but... Actually, JS has basically an infinite valued logic, because of its truthiness/falsiness dichotomy and the rules around how the “boolean” operators preserve truthy or falsy inputs; only ! of the core boolean operators always returns a boolean which is why !! is equivalent to Boolean().

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @04:42PM (#29558298)
Right, but js treats all values as either truthy or falsey. Only SQL does this weird 3rd-way approach where values can be neither true nor false (except in a WHERE or ON clause where NULL is treated as false).

Like, this is a language where "X OR NOT X" is not true if X = null

JS, for all its wonky truthiness rules, still satisfies the basic premise that "X || !X" yields something truthy.

Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @05:41PM (#29559126)
SQL NULL and IEEE 754 NaN are very similar in weirdness of how they propagate, for very similar reasons (they are both hacks for encoding “not a value in the domain” in a value otherwise restricted to the domain; they aren't actual values but information about the absence of an acceptable value.)

Most other languages treat NULL as a distinct-but-normal value. IMO this isn't better or worse than SQL, or rather, the SQL approach is better for querying in SQL, whereas the approach common in general purpose programming languages is better more generally, but forces more special case handling.

Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @02:45PM (#29556472)
> Hell, JavaScript has true, false, null, and undefined. 4-value logic!

You have vastly underestimated the number of values in JS’s logic.

Re:SQL: The difference between WHERE and HAVING by Taywee on Tuesday December 14, 2021 @09:52AM (#29552133)
Most modern languages have option types.
Re:SQL: The difference between WHERE and HAVING by dragonwriter on Tuesday December 14, 2021 @02:51PM (#29556573)
> SQL ANSI nulls alone are a good-enough reason to toss it. Any language where "x = x" commonly returns an object that is treated as falsey is broken.

So, any language using IEEE 754 floats is broken?

Re:SQL: The difference between WHERE and HAVING by gpderetta on Tuesday December 14, 2021 @09:21AM (#29551767)
> Any language where "x = x" commonly returns an object that is treated as falsey is broken.

Err, that will include any language that implements IEEE floats.

Re:SQL: The difference between WHERE and HAVING by Pxtl on Tuesday December 14, 2021 @01:25PM (#29555236)
"Commonly" is the operative word here. I'd say that null values are far more common than NaN.
Re:SQL: The difference between WHERE and HAVING by goto11 on Tuesday December 14, 2021 @08:40AM (#29551343)
This is basically how Linq (in .net) does it. It is much more composable than SQL but still implement the relational algebra.
Re:SQL: The difference between WHERE and HAVING by wongarsu on Tuesday December 14, 2021 @09:17AM (#29551713)
And LINQ is converted into SQL if you do LINQ queries against a database. The queries are sometimes far from optimal, but the developer experience is quite nice.
Re:SQL: The difference between WHERE and HAVING by xi on Tuesday December 14, 2021 @10:20AM (#29552479)
This is pretty close to how my Julia library [0] for composable construction of SQL queries works:

    From(foo) |>
    Where(Get.value .< 10) |>
    Join(From(bar) |> As(:bar), on = Get.bar.id .== Get.bar_id) |>
    Where(Get.bar.other_value .> 20) |>
    Select(Get.group, Get.value) |>
    Group(Get.group) |>
    Where(Agg.sum(Get.value) .> 100) |>
    Order(Get.group)
There is no HAVING and the you can use any tabular operators in any order. Aggregates are also separated from grouping and can be used in any context after Group is applied.

[0] https://github.com/MechanicalRabbit/FunSQL.jl

Re:SQL: The difference between WHERE and HAVING by faho on Tuesday December 14, 2021 @10:19AM (#29552469)
I would go one step further and make the join just

   JOIN Bar b
if you've defined the foreign keys before.

The need to spell them out again and again is one of my personal SQL pet peeves.

Re:SQL: The difference between WHERE and HAVING by mamcx on Tuesday December 14, 2021 @11:33AM (#29553507)
Building https://tablam.org I learn a bit about the relational model and found that the whole having/group by is plain bad "hack".

GROUP BY is totally the opposite of what you expect. It NOT "group by"!,

This is group by:

    1:
       A
       B
    2:
       A
       C
If where like this (as in the RM) then you can bet other hacks like graph-ql where not necessary (and will make database more friendly to OO langs)
Re:SQL: The difference between WHERE and HAVING by barrkel on Tuesday December 14, 2021 @11:54AM (#29553895)
GROUP BY is two things, partitioning and aggregation to a single row within each partition. The relational model doesn't really have a model for partitioning on its own so they're fused, but if they were distinct concepts it might make e.g. analytic window functions more composable and less awkward.