Tuesday, February 10, 2009
Change data TYPE of a column in a table
alter table test_table alter column table_id TYPE bigint
Error :
column "table_id" cannot be cast to type "pg_catalog.int8"
Solution
-----------
ALTER TABLE sometable
ALTER COLUMN somecolumn TYPE new_data_type
USING some_function_call_to_cast(somecolumn);
Step 1 : you need to make a function to cast existing type to new data type
Step 2 : call alter USING the casting function
Below i have worked out one example
----------------------------------------
ALTER TABLE test_table
ALTER COLUMN table_id TYPE bigint
USING test_function_call_to_cast(table_id);
Here i have alter the column table_id from VARCHAR to BIGINT in test_table
body of the function :
-----------------------------------------------------------------
CREATE OR REPLACE FUNCTION
test_function_call_to_cast(VARCHAR) RETURNS bigint
AS
$BODY$
SELECT
CASE
WHEN trim($1) SIMILAR TO '[0-9]+'
THEN CAST(trim($1) AS bigint)
ELSE NULL
END;
$BODY$
LANGUAGE 'sql' IMMUTABLE STRICT;
--------------------------------------------------------------------------
important
Even if the above did work, you've got some stuff in there you don't really care about - letters and so forth or an empty string. So you want to control how the cast is done anyway
in the above function
which takes a string value and if it looks like a number, it converts it to a number otherwise it just returns NULL:
Monday, February 2, 2009
Checking Null Values
expression = NULL
but i did not get any results. Obviously the results are available for my query and i was wondering why always result set was zero. Here is the solution
--------------------------------------
To check whether a value is or is not null, use the constructs
expression IS NULL
expression IS NOT NULL
or the equivalent, but nonstandard, constructs
expression ISNULL
expression NOTNULL
Do not write expression = NULL because NULL is not "equal to" NULL. (The null value represents an unknown value, and it is not known whether two unknown values are equal.) This behavior conforms to the SQL standard.
Tip: Some applications may expect that expression = NULL returns true if expression evaluates to the null value. It is highly recommended that these applications be modified to comply with the SQL standard. However, if that cannot be done the transform_null_equals configuration variable is available. If it is enabled, PostgreSQL will convert x = NULL clauses to x IS NULL. This was the default behavior in PostgreSQL releases 6.5 through 7.1.
---------------------------------------------------------------------
So always remember to use IS NULL to check the null values