numbers going from int to varchar - sql

I have column in a postgresql database. They are lottery numbers. Four digits in length to be exact. Initially I had the datatype of the column as int. I inserted all the lottery numbers. After I inserted all the numbers I realize it chopped off my zeros. For instance 0925 is 925. I fixed the datatype to be varchar but now I need to figure out how to fix it from int to varchar with the same data. The data needs to be 4 digits in length. I was trying to just figure out how many problem numbers there are and I couldn't write a select statement that told me how many rows have less than 4 digits.
How should I go about this?
Thanks.

I was trying to just figure out how many problem numbers there are and I couldn't write a select statement that told me how many rows have less than 4 digits.
SELECT COUNT(*)
FROM lottery
WHERE char_length(x) < 4
See it working online: sqlfiddle
To fix them, you may find lpad useful. Note that the WHERE clause is not actually needed.
UPDATE lottery
SET x = lpad(x, 4, '0')
See it working online: sqlfiddle

Format your numbers with to_char():
SELECT to_char(123, 'FM0000');
You might even just leave them as integer and use the expression in queries.
Or, to convert your column back from integer to text in place:
ALTER TABLE tbl ALTER column col TYPE text USING to_char(col, 'FM0000');
Since you seem to have already converted the numbers to varchar, the expression needs an additional cast to integer:
SELECT to_char(col::int, 'FM0000')
FROM tbl;

Related

How to remove trailing zeroes in snowflake?

I have a column that is in INT type. I want to remove all the trailing zeroes and only have the number. The example below, should follow be: 3,10,20,20. I cannot have the 4 zeroes at the end.
Is there a way to do this?
You could try casting your numeric data to integer, e.g.
SELECT AS_INTEGER(col) AS col
FROM yourTable;
the 3dp is how floating point numbers print, thus you can cast to number SELECT column_name::number FROM table
If your data is a string/varient type, and not all values stored in your column always casts cleanly, in Snowflake you can hit error, with the TO_NUMBER or ::number forms, thus [TRY_TO_NUMBER][2] form should be used.

Converting varchar type variable number without having decimal points

I need to convert varchar2 type value 100.0 into 100 (without decimal points) in Oracle SQL. Can you please help me?I used regexp_substr...but it fails in one situation given below.
SELECT REGEXP_SUBSTR(0.1,'(\d*)') FROM DUAL;---it results in Null but i want zero(0).
Note:- in Orcale sql developer
You want to display number in format You wish it to be displayed, so You should use formating functions. No need for rounding here in my opinion - query below should give You what You want.
SELECT
TO_CHAR(TO_NUMBER('100.1'),'FM9999') as res
FROM
dual
;
More on number formats can be found here.
Try to this....
SELECT TRUNC(TO_NUMBER(100.5)) FROM DUAL;

Oracle - select * where column>5

I am trying to do a comparison based on a column. Let's say, if column>5.
select * where column>5
The column contains non digits. I thought Oracle allows one to compare strings (like Java).
Apparently this is not allowed.
ORA-01722: invalid number
01722. 00000 - "invalid number"
Is there a way to do comparisons with non numeric fields?
Thanks
Yes, you have to put the 5 in quotes :
select * from table where column > '5'
To shed a bit more light on why it doesn't work.
When using a number literal 5 instead of a character literal '5' Oracle does an implicit data type conversion and tries to convert all values in your table to a number. That's why you get that error.
You should never rely on implicit data type conversion. That is bound to give you trouble sometime.
Now if you correctly compare a character literal ('5') against a character column, no data type conversion is needed and no error occurs.
However: if you expect Oracle to actually do a numeric comparison then you are mistaken. Character string are based on ASCII values. Therefor the (character) value '10' is lower than the (character) value '2' because the first character '1' is ranked lower than '2'.
If the column is varchar2, then this:
select * from some_table where some_column > 5
... does an implicit conversion of all the column values to numbers, so you're really doing:
select * from some_table where to_number(some_column) > 5
It's the to_number() that's causing the ORA-01722, even though you can't see it, when it hits a value that is not numeric. The function being called on the column value also stops any index being used (oversimplifying a bit).
You can stop it failing, and let it use the index if there is one, by doing where some_column > '5' as other have said, or where some_column > to_char(5). But you need to be careful doing the comparison as it will still be a string comparison, not a numeric one; so '10' will not be seen as > '5'; and your NLS sorting parameters might produce results you aren't expecting. Or more importantly, someone else's NLS parameters - when you put this live for example - might product results you aren't expecting and which don't match the ones you got in your environment. See the documentation for more.
You should use number columns to hold numeric values, date columns to hold dates, etc., and varchar2 only to hold text values.
you can use to_char function
select * from table where column > to_char(5)
You are missing the table:
select * where FROM tablename column>5
But this only works if column is a number. If not, you can't use >.
To compare strings, you can use LIKE or STRCMP(), check examples of them HERE.
As stated by #Gerrat, you can also use > and < but the types of both sides must be compatible (number with number or text with text). To find more about it, check THIS.
Be aware that in text comparison it will compare each character individually so '11' will be < that '2'.

Conversion of varchar to number

I have a question that bothers me. How can i convert a varchar to number when inside the varchar value consists of alphabets.
For my varchar price column values:
14dollars10cents
15dollars20cents
By converting it to varchar to number price column, the values should be:
1410
1520
I know that if the varchar does not consists any alphabets, it can auto convert by"
SELECT CONVERT(INT, PRICE) FROM Table
Is there any way to get rid of the alphabets in the middle as I would like to do mathematical function on it.
Updated attempt of putting fixed point number in:
SELECT CAST (Replace(REPLACE(PRICE, 'dollars', '.'),'cents','') AS Number(4,2)))
FROM TEST;
Thanks
You could just use REGEXP_REPLACE to remove all non digit characters:
SELECT REGEXP_REPLACE(price, '[^[:digit:]]')
FROM table;
To then convert this to a number:
SELECT TO_NUMBER(REGEXP_REPLACE(price, '[^[:digit:]]'))
FROM table;
If you want to add the point in then you can do that with REGEXP_REPLACE too:
SELECT TO_NUMBER(REGEXP_REPLACE(val, '^([0-9]*)([^[:digit:]]*)([0-9]*)(.*)$', '\1.\3'))
FROM table;
Voila...
SELECT CAST(REPLACE(YourVarcharCol, 'dollars', '') AS INT) FROM Table
The issue with this is it will break if the varchar still contains alpha-numeric characters.
How about using translate to strip out the unwanted characters.
SELECT TO_NUMBER(TRANSLATE('14dollars10cents','1234567890dolarscents','1234567890')) FROM DUAL
No I don't think there is direct way.
you can do string parsing to get your integer value.

format decimals and comma to numbers retrieved

I have a column in my table which showing an amount. The amount is varying from one column to another and they are more than 15 digits.
What is the best way to format the number to show commas and decimal points?
My query is
select amount from ccamounts
How can I format the number
205511892078
to show as
205,511,892,078
and if there is a radix point it will also appear.
I believe you can use TO_CHAR to do this, the issue is that this is just a formatting function within SQL. It requires that your number is always going to be in the same format.
taking the example above you could do
TO_CHAR('205511892078', '999,999,999,999')
and this would format the number as you have specified, with a decimal place this can be done aswell but the decimal needs to be specified:
TO_CHAR('20551189207842', '999,999,999,999.99')
which would give you 205,511,892,078.42
I think if the field length is going to vary sql will just ignore anything that doesn't fit into the format string (It's a mask). Perhaps you want to consider formatting the number in this case on whichever front end you may be using?
I would format the number in the UI / Reporting tool / Presentation layer not Oracle
but if you MUST format it in oracle try:
SELECT
CASE WHEN INSTR( TO_CHAR(205511892078),'.')>0 THEN
TO_CHAR(205511892078 ,'999,999,999,999.99')
ELSE
TO_CHAR(205511892078 ,'999,999,999,999')
END
FROM DUAL
this will return the number as a string.
declare #d3 decimal (10, 2)
set #d3 = 12309809.5494
SELECT convert(varchar(15),cast(CAST(ROUND(#d3,2,1) AS DECIMAL (30,2)) as money),1) as Value
SELECT CAST(ROUND(convert(varchar(30), cast(#d3 as money),2),2,1) AS DECIMAL (30,2)) as Value
Output:
12,309,809.55
12309809.55