Placeholder for Decimal Column in SQL - sql

I am new to SQL so this question is likely simple and easy to answer.
I am creating a temp table in which I want a blank column to be filled later with decimal values.
Can I use as a placeholder in my SELECT statement to indicate that I want decimal values to fill the column?
For columns that I will fill with integer values, I am using the following code:
SELECT 0 AS ColumnName
I do not believe this will work for the column that I want filled with decimal values, as I believe the 0 indicates integer values instead. Is there something that I can use instead of the 0?
Any help would be appreciated!

SQL will perform implicit conversion of some types when it knows there is no risk of data loss. In your case, int can safely convert to decimal, because there's no way to corrupt your data. 0 is 0.0 as far as SQL is concerned.
The opposite would not be true, as casting from decimal to int would lose the decimal part. Therefore SQL would not implicitly cast the opposite.
Your query is good as is.

Using a 0 in a float field will not cause truncation on the record since it contains less precision than a float, so it is safe to do this and implies a 0.0
You could also DEFAULT the field to 0.0 in the table declaration so it will be 0.0 until updated. But not required.
Ex: CREATE TABLE table
( col1 FLOAT(size,d) DEFAULT 0.0 )

Related

CASTING to NUMERIC in SQL

I am trying to understand the ARPU calculation in SQL from the following code, however I don't understand why the author has used NUMERIC with revenue in the 2nd query? Won't revenue (meal_price * order quantity) be numeric anyway?
The issue is probably the following. NUMERIC is a specific data type. However, it is not clear that meal_price and order_quantity are specifically NUMERIC -- and not some other type such as INT.
Many databases do integer division for INT, so 1 / 2 is 0 rather than 0.5.
The conversion to NUMERIC is a simple way to avoid integer division.
Of course if a and b are numeric types , a * b will be numeric type
But there are many different numeric types, see
https://www.postgresql.org/docs/13/datatype-numeric.html
NUMERIC is a KEYWORK to specify numeric type of arbitrary précision, see previous link, it's often used to do exact calculations (accouinting) that cannoy be done in foating type.
In your case the author choosed to define the type he wants to use and not let the system/db choose for him. (try to figure out if a and b are integer what shoult be the type of the result 2 * 4 / 3 ?). It's a good practice.

Using decimal in a SQL query

I have a column Amount defined in my SQL Server database as varchar(20), null.
It has values like this:
1.56867
2.0
2.0000
2
If the user in the client app enters 2 for search, then I need to pull all records from the db except value 1.56867.
So search results should yield:
2.0
2.0000
2
I tried using this in my SQL query but it's still returning value 1.56867.
CONVERT(decimal, myTable.Amout) = CONVERT(decimal, 2)
Can you advise?
Thanks.
You should really consider fixing your data model, and store numbers as numbers rather than strings.
That said, you need to specify a scale and a precision for the decimal, otherwise i defaults to decimal(38, 0) , which results in the decimal part being truncated. Something like:
convert(decimal(20, 5), myTable.Amout) = 2
This gives you 20 digits max, including 5 decimal digits. There is no need to explictly convert the right operand here (that's a literal number already).
If your column may contain values that are not convertible to numbers, you can use try_convert() instead of convert() to avoid errors.
The problem is that when converting the string '1.56867' to decimal, SQL server assumes you want 0 decimal places (as pointed out by #GMB), and rounds the value to the nearest integer (2).
select convert(decimal,'1.56867');
-------
2
Also, since your column is defined to hold character data, you should use the try_cast() function to avoid Error converting data type varchar to numeric. errors that would otherwise occur if non-numeric data is present in the column.
select *
from (values
('1.56867')
,('2.0')
,('2.0000')
,('2')
,(null)
,('non-numeric value')
) myTable(Amount)
where try_cast(Amount as decimal(38,19)) = 2
;
Amount
-----------------
2.0
2.0000
2
(3 rows affected)

SQL query defining Column type as float with 3 decimal numbers

This is a simple example of what is not working for me:
CREATE TABLE Vertex(
PointID CHARACTER(15) PRIMARY KEY,
Height FLOAT(6,3)
);
After input like this:
INSERT INTO Vertex values("Tryout 1",555.22689562);
I expect the Height to be saved with the value: 555.227
However it is not the case for me, I keep finding the whole number being saved.
Could you point me to an alternate of how to define a column type and contain the format xxxxxx.xxx
Change float to decimal and it will work.
Height decimal(6,3)
Float is an approximate number data type. Using float may cause loss of precision, and using float data type for equality may not work all times.
Decimal data type is fixed precision data type. For using decimal data types, you will need to convert to the data type like convert(decimal(6,3), <number>).
In case of insert query, it is done implicitly though.

Value of real type incorrectly compares

I have field of REAL type in db. I use PostgreSQL. And the query
SELECT * FROM my_table WHERE my_field = 0.15
does not return rows in which the value of my_field is 0.15.
But for instance the query
SELECT * FROM my_table WHERE my_field > 0.15
works properly.
How can I solve this problem and get the rows with my_field = 0.15 ?
To solve your problem use the data type numeric instead, which is not a floating point type, but an arbitrary precision type.
If you enter the numeric literal 0.15 into a numeric (same word, different meaning) column, the exact amount is stored - unlike with a real or float8 column, where the value is coerced to next possible binary approximation. This may or may not be exact, depending on the number and implementation details. The decimal number 0.15 happens to fall between possible binary representations and is stored with a tiny error.
Note that the result of a calculation can be inexact itself, so be still wary of the = operator in such cases.
It also depends how you test. When comparing, Postgres coerces diverging numeric types to a type that can best hold the result.
Consider this demo:
CREATE TABLE t(num_r real, num_n numeric);
INSERT INTO t VALUES (0.15, 0.15);
SELECT num_r, num_n
, num_r = num_n AS test1 --> FALSE
, num_r = num_n::real AS test2 --> TRUE
, num_r - num_n AS result_nonzero --> float8
, num_r - num_n::real AS result_zero --> real
FROM t;
db<>fiddle here
Old sqlfiddle
Therefore, if you have entered 0.15 as numeric literal into your column of data type real, you can find all such rows with:
SELECT * FROM my_table WHERE my_field = real '0.15'
Use numeric columns if you need to store fractional digits exactly.
Your problem originates from IEEE 754.
0.15 is not 0.15, but 0.15000000596046448 (assuming double precision), as it can not be exactly represented as a binary floating point number.
(check this calculator)
Why is this a problem? In this case, most likely because the other side of the comparison uses the exact value 0.15 - through an exact representation, like a numeric type. (Cleared up on suggestion by Eric)
So there are two ways:
use a format that actually stores the numbers in decimal format - as Erwin suggested
(or at least use the same type across the board)
use rounding as Jack suggested - which has to be used carefully (by the way this uses a numeric type too, to exactly represent 0.15...)
Recommended reading:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
(Sorry for the terse answer...)
Well, I can't see your data, but I'm guessing that my_field doesn't exactly equal 0.15. Try:
select * from my_table where round(my_field::numeric,2) = 0.15;
Considering both PPTerka's and Jack's answer.
Approximate numeric data types do not store the exact values specified for many numbers;
Look here for MS' decription of real values.
http://technet.microsoft.com/en-us/library/ms187912(v=sql.105).aspx

Multiplication with NULL and empty column values in SQL

This was my Interview Question
there are two columns called Length and Breadth in Area table
Length Breadth Length*Breadth
20 NULL ?
30 ?
21.2 1 ?
I tried running the same question on MYSQL while inserting,To insert an empty value I tried the below query . Am I missing anything while inserting empty values in MYSQL.
insert into test.new_table values (30,);
Answers: With Null,Result is Null.
With float and int multiplication result is float
As per your question the expected results would be as below.
SELECT LENGTH,BREADTH,LENGTH*BREADTH AS CALC_AREA FROM AREA;
LENGTH BREADTH CALC_AREA
20
30 0 0
21.2 1 21.2
For any(first) record in SQL SERVER if you do computation with NULL the answer would be NULL.
For any(second) record in SQL SERVER, if you do product computation between a non-empty value and an empty value the result would be zero as empty value is treated as zero.
For any(third) record in SQL SERVER, if you do computation between two non-empty data type values the answer would be a NON-EMPTY value.
Check SQL Fiddle for reference - http://sqlfiddle.com/#!3/f250a/1
That blank Breath (second row) cannot happen unless Breath is VARCHAR. Assuming that, the answers will be:
NULL (since NULL times anything is NULL)
Throws error (since an empty string is not a number. In Sql Server, the error is "Error converting data type varchar to numeric.")
21.20 (since in Sql Server, for example, conversion to a numeric type is automatic, so SELECT 21.2 * '1' returns 21.20).
Assuming that Length and Breadth are numerical types of some kind the second record does not contain possible values — Breadth must be either 0 or NULL.
In any event, any mathematical operation in SQL involving a NULL value will return the value NULL, indicating that the expression cannot be evaluated. The answer are NULL, impossible, and 21.2.
The product of any value and NULL is NULL. This is called "NULL propagation" if you want to Google it. To score points in an interview, you might want to mention that NULL isn't a value; it's a special marker.
The fact that the column Breadth has one entry "NULL" and one entry that's blank (on the second row) is misleading. A numeric column that doesn't have a value in a particular row means that row is NULL. So the second column should also show "NULL".
The answer to the third row, 21.2 * 1, depends on the data type of the column "Length*Breadth". If it's a data type like float, double, or numberic(16,2), the answer is 21.2. If it's an integer column (integer, long, etc.), the answer is 21.
A more snarky answer might be "There's no answer. The string "Length*Breadth" isn't a legal SQL column name."
In standard SQL they would all generate errors because you are comparing values (or nulls) of different types:
CAST ( 20 AS FLOAT ) * CAST ( NULL AS INTEGER ) -- mismatched types error
CAST ( '' AS INTEGER ) -- type conversion error
CAST ( AS INTEGER ) -- type conversion error
CAST ( 21.2 AS FLOAT ) * CAST ( 2 AS INTEGER ) -- mismatched types error
On the other hand, most SQL product would implicitly cast values when comparing values (or nulls) of different types according to type precedence e.g. comparing float value to an integer value would in effect cast the integer to float and result in a float. At the product level, the most interesting question is what happens when you compare a null of type integer with a value (or even a null) of type float...
...but, frankly, not terribly interesting. In an interview you are presented with a framework (in the form of questions asked of you) on which to present your knowledge, skills and experience. The 'answer' here is to discuss nulls (e.g. point out that nulls are tricky to define and behave in unintuitive ways, which leads to frequent bugs and a desire to avoid nulls entirely, etc) and whether implicit casting is a good thing.