Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value in a numeric field is an integer?

Tags:

sql

postgresql

I have a numeric column in Postgresql with these values:

1.0
3.5
1.5
4.0

I want to write a query which will give me all rows that aren't integer. Meaning I want to get:

3.5
1.5

How do I do that?

like image 579
avi Avatar asked Nov 09 '15 13:11

avi


People also ask

How do you check if a value is an integer?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you know if a column value is integer or non integer?

Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.

How do you test if a value is an integer in Python?

To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.

How do you check if a number is an integer in C++?

Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int. Print the resultant output.


1 Answers

You can use modulo division:

CREATE TABLE tab(col DECIMAL(10,2));

INSERT INTO tab(col)
VALUES (1.0),(3.5),(1.5),(4.0);

SELECT *
FROM tab
WHERE col % 1 <> 0;

LiveDemo

Remainder:

In mathematics, the remainder is the amount "left over" after performing some computation.

For example:

10 % 4 = 2      because (FLOOR(10/4)  = 2,  2 * 4 + 2 = 10)
13 % 4 = 1      because (FLOOR(13/4)  = 3,  3 * 4 + 1 = 13)
3.5 % 1 = 0.5   because (FLOOR(3.5/1) = 3, 3 * 1 + 0.5 = 3.5)
4.0 % 1 = 0     because (FLOOR(4.0/1) = 4, 4 * 1 + 0 = 4)

So if number has something else than zeros after decimal point you know that it is not Integer.

Alternatively you could use:

SELECT *
FROM tab
WHERE col <> FLOOR(col);

LiveDemo2

like image 166
Lukasz Szozda Avatar answered Nov 15 '22 13:11

Lukasz Szozda