Alter table after keyword in Oracle - oracle

ALTER TABLE testTable ADD column1 NUMBER(1) DEFAULT 0 NOT NULL AFTER column2;
Why can't I use mySql syntax in Oracle too? The above command works in MySql. Can you give me an equivalent that works?
Error report:
SQL Error: ORA-01735: invalid ALTER TABLE option
01735. 00000 - "invalid ALTER TABLE option"
I am asking if there is any way to use after clause in Oracle command that I provided?

Because SQL is a relational algebra. It doesn't care one bit about "where" columns are located within a table, only that they exist.
To get it to work in Oracle, just get rid of the after clause. The Oracle documentation for alter table is here but it boils down to:
alter table testTable
add ( column1 number(1) default 0 not null )
There is no after clause for the alter table command.

Oracle does not support adding columns in the middle of a table, only adding them to the end. Your database design and app functionality should not depend on the order of columns in the database schema. You can always specify an order in your select statement, after all.
However if for some reason you simply must have a new column in the middle of your table there is a work around.
CREATE TABLE tab1New AS SELECT 0 AS col1, col1 AS col2 FROM tab1;
DROP TABLE tab1 PURGE;
RENAME tan1New to tab1;
Where the SELECT 0 AS col1 is your new column and then you specify other columns as needed from your original table. Put the SELECT 0 AS col1 at the appropriate place in the order you want.
Afterwards you may want to run an alter table statement on the column to make sure it's the data type you desire.

Try this :
ALTER TABLE testTable ADD column1 NUMBER(1) DEFAULT 0 NOT NULL

Related

Apex Oracle How To Create Conditional Column

I am new to using Apex Oracle to create a table and insert values in it. I need to create a column that is only mandatory if the value for another column is "Y" (if it is "N", then it is not mandatory). The type of the other column is a CHAR with length 1. How could I do this? Would this be done in SQL Scripts or SQL Commands? Similarly, is there a way to delete old SQL commands that were used (that now I realize are incorrect)?
Thank you!
Welcome to Oracle APEX and Stack Overflow. You can create objects (tables/views) in both SQL commands and SQL Scripts. For ad hoc creating, SQL Commands is probably easier. To remove (called "drop" in oracle) objects that you create, that can be done in SQL Commands, or even easier in the "Object Browser" - locate the object and select "drop". Note that this cannot be undone.
About the requirement for a column to be conditionally mandatory:
This can be enforced in the database using a check constraint.
CREATE TABLE test_table (
id NUMBER GENERATED AS IDENTITY,
col1 VARCHAR2(1),
col2 VARCHAR2(10));
Table TEST_TABLE created.
ALTER TABLE test_table ADD CONSTRAINT test_table_c1
CHECK ((col1 = 'Y' AND col2 IS NOT NULL) or (col1 != 'Y'));
Table TEST_TABLE altered.
INSERT INTO test_table(col1,col2) VALUES ('N',NULL);
1 row inserted.
INSERT INTO test_table(col1,col2) VALUES ('Y',NULL);
INSERT INTO test_table(col1,col2) VALUES ('Y',NULL)
Error report -
ORA-02290: check constraint (SAMPLEAPPS.TEST_TABLE_C1) violated
INSERT INTO test_table(col1,col2) VALUES ('Y','Some Value');
1 row inserted.

How to find the root cause of ORA-54033 error when altering column data type

I am attempting to alter the data type of a column from a NUMBER to a VARCHAR2 in an existing database table. When running the following ALTER TABLE statement I receive the "ORA-54033: column to be modified is used in a virtual column expression" error:
ALTER TABLE table MODIFY (col1 varchar2(8));
I have already worked through the directions listed here. When looking at the SYS generated export statistics using the following query
select column_name, data_default, hidden_column
from user_tab_cols
where table_name = 'Table';
there is nothing referencing col1 in export statistics. There are about 15 hidden, SYS generated rows associated with the table and they all have a data default value of <Long>. There are no virtual columns in the DDL, nor is this column being used for any indexes or as a FK. I have also had the DBA run the following:
SELECT EXTENSION_NAME, EXTENSION, CREATOR, DROPPABLE
FROM DBA_STAT_EXTENSIONS
WHERE TABLE_NAME='Table'
and the output lines up with what I find in user_tab_cols. Where else can I look for this seemingly buried virtual column?

H2 ALTER TABLE DROP CONSTRAINT only if table exists

I need to drop a constraint (say, foreign key). But the table, the constraint on it, or both, may not exist.
I tried:
ALTER TABLE IF EXISTS Table1 - invalid syntax
ALTER TABLE Table1 DROP CONSTRAINT IF EXISTS Constraint - fails if Table1 is missing
funky CASE WHEN stuff like
select CASE (select count(*)
from INFORMATION_SCHEMA.CONSTRAINTS
where CONSTRAINT_SCHEMA = 'DBO'
and CONSTRAINT_NAME = upper('FK_Table1_Col1_Table2_Col2'))
WHEN 1 THEN 'select 5'
end
In MS SQL for example you have all the IF EXISTS clauses allowing you to branch script easily. Not so with H2, it would seem. There should be some way to make it work similar to my attempt with CASE WHEN, no ?
If possible, I want to avoid writing Java code in the sql file.

Oracle - Change Table Position [duplicate]

I have a specific scenario where i have to insert two new columns in an existing table in Oracle. I can not do the dropping and recreating the table. So can it be achieved by any means??
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish.
Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
In 12c you can make use of the fact that columns which are set from invisible to visible are displayed as the last column of the table:
Tips and Tricks: Invisible Columns in Oracle Database 12c
Maybe that is the 'trick' #jeffrey-kemp was talking about in his comment, but the link there does not work anymore.
Example:
ALTER TABLE my_tab ADD (col_3 NUMBER(10));
ALTER TABLE my_tab MODIFY (
col_1 invisible,
col_2 invisible
);
ALTER TABLE my_tab MODIFY (
col_1 visible,
col_2 visible
);
Now col_3 would be displayed first in a SELECT * FROM my_tab statement.
Note: This does not change the physical order of the columns on disk, but in most cases that is not what you want to do anyway. If you really want to change the physical order, you can use the DBMS_REDEFINITION package.
Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):
Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
"Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
drop existing table:
drop table TAB1;
rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;
You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.
If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-
First copy the table
CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;
Then drop columns that you want to be after the column you will insert
ALTER TABLE my_tab DROP COLUMN three;
Now add the new column (two in this example) and the ones you removed.
ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));
Lastly add back the data for the re-created columns
UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);
Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?

Automatically populate date in oracle table

I have created a table in oracle XE, and I have a field with type date. I would like if possible when I insert a row, that it automatically fills that field with the current date from the system.
I am inserting the rows from the SQL prompt.
Thanks
Here is how, you need to format your table properly:
create table test (first number
, second timestamp default systimestamp
, third varchar2(12));
And your default value is always current system time formatted as timestamp.
change the field after creating the table
ALTER TABLE table MODIFY time_collumn TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
Or you could also use a trigger:
CREATE OR REPLACE TRIGGER date_trigger
BEFORE INSERT
ON table_name
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT sysdate INTO :NEW.column_name FROM dual;
END;
The below snippet might be helpful if we forget to add the constraint while creating the table:
ALTER TABLE TABLE_NAME
ADD CONSTRAINT CONSTRAINT_NAME
COLUMN_NAME DATA_TYPE DEFAULT CURRENT_DATE;

Resources