JuliaDatabases / ODBC.jl

An ODBC interface for the Julia programming language
https://odbc.juliadatabases.org/stable
Other
106 stars 63 forks source link

SQL Query returns wrong number of rows instead of Divide by Zero error encountered (8134) (SQLFetch) #352

Closed pankgeorg closed 2 years ago

pankgeorg commented 2 years ago

OBDC.jl@1.1.1, MSSQLServer Compatibility level 150+, ODBC Driver 18 for SQL Server, Ubuntu on WSL, julia 1.7.2 A query looks like the following:

WITH t AS 
(SELECT
   ...
   sum(metric_1)/sum(metric_2) as a,
   avg(metric_1/metric_2) as b,
   ...
FROM
   table)
SELECT * FROM t

In julia with ODBC.jl@1.1.1 this returns 2.3k rows

If you turn the query to

WITH t AS 
(SELECT
   ...
   sum(metric_1)/sum(metric_2) as a,
   avg(metric_1/metric_2) as b,
   ...
FROM
   table)
SELECT count(*) FROM t

You get 15k

The same query in pandas/sqlalchemy raises ('22012', [22012] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Divide by zero error encountered. (8134) (SQL Fetch)'

Tweaking the query to do:

WITH t AS 
(SELECT
   ...
   CASE WHEN sum(metric_2) > 0 THEN sum(metric_1)/sum(metric_2)  ELSE NULL END as a,
   CASE WEHN metric_2 > 0 THEN avg(metric_1/metric_2) ELSE NULL END as b,
   ...
FROM
   table)
SELECT count(*) FROM t

makes the query work in both cases correctly.

Possibly related to https://github.com/JuliaDatabases/ODBC.jl/issues/32

pankgeorg commented 2 years ago

Minimal example

SELECT a, b, a/b FROM (VALUES (2,1),(1,0),(2,1)) AS t(a,b)

Returns 1 row, instead of an error