ALTER TABLE SQL Oracle - 12c - sql

we are confused with below answers.so our answer is 3, 5
Which three actions can you perform by using the ALTER TABLE command?
1- Lock a set of rows in a table.
2- Drop pseudocolumns from a table.
3- Rename a table.
4- Drop all columns simultaneously from a table.
5- Enable or disable constraints on a table.
6- Restrict all DML statements on a table.
Thank you

3, 5 and 6
Lock a set of rows in a table.
Oracle locks rows it is performing DML on or when you use SELECT ... FOR UPDATE; you cannot lock rows with ALTER TABLE.
Drop pseudocolumns from a table.
The common pseudocolumns of a table are ROWID, ROWNUM and ORA_ROWSCN; you cannot drop these.
Rename a table.
CREATE TABLE table_name ( a NUMBER, b NUMBER );
ALTER TABLE table_name RENAME TO other_name;
Works.
Drop all columns simultaneously from a table.
CREATE TABLE table_name ( a NUMBER, b NUMBER );
ALTER TABLE table_name DROP ( a, b );
Outputs:
ORA-12983: cannot drop all columns in a table
Enable or disable constraints on a table.
CREATE TABLE table_name ( a NUMBER CONSTRAINT qu5__pk PRIMARY KEY, b NUMBER );
ALTER TABLE table_name MODIFY PRIMARY KEY DISABLE;
Will disable the constraint.
Restrict all DML statements on a table.
CREATE TABLE table_name ( a NUMBER, b NUMBER );
ALTER TABLE table_name READ ONLY;
Then
INSERT INTO table_name ( a, b ) VALUES ( 1, 1 );
UPDATE table_name SET b = 2;
DELETE FROM table_name;
all fail with the exception:
ORA-12081: update operation not allowed on table "SCHEMA_NAME"."TABLE_NAME"
db<>fiddle here

Related

Missing Keyword Error in Oracle SQL Database [duplicate]

I was wondering how can I add an identity column to existing oracle table? I am using oracle 11g. Suppose I have a table named DEGREE and I am going to add an identity column to that.
FYI table is not empty.
You can not do it in one step. Instead,
Alter the table and add the column (without primary key constraint)
ALTER TABLE DEGREE ADD (Ident NUMBER(10));
Fill the new column with data which will fulfill the primary key constraint (unique/not null), e.g. like
UPDATE DEGREE SET Ident=ROWNUM;
Alter the table and add the constraint to the column
ALTER TABLE DEGREE MODIFY (Ident PRIMARY KEY);
After that is done, you can set up a SEQUENCE and a BEFORE INSERT trigger to automatically set the id value for new records.
From Oracle 12c you would use an identity column.
For example, say your table is called demo and has 3 columns and 100 rows:
create table demo (col1, col2, col3)
as
select dbms_random.value(1,10), dbms_random.value(1,10), dbms_random.value(1,10)
from dual connect by rownum <= 100;
You could add an identity column using:
alter table demo add demo_id integer generated by default on null as identity;
update demo set demo_id = rownum;
Then reset the internal sequence to match the data and prevent manual inserts:
alter table demo modify demo_id generated always as identity start with limit value;
and define it as the primary key:
alter table demo add constraint demo_pk primary key (demo_id);
This leaves the new column at the end of the column list, which shouldn’t normally matter (except for tables with a large number of columns and row chaining issues), but it looks odd when you describe the table. However, we can at least tidy up the dictionary order using the invisible/visible hack:
SQL> desc demo
Name Null? Type
-------------------------------- -------- ----------------------
COL1 NUMBER
COL2 NUMBER
COL3 NUMBER
DEMO_ID NOT NULL NUMBER(38)
begin
for r in (
select column_name from user_tab_columns c
where c.table_name = 'DEMO'
and c.column_name <> 'DEMO_ID'
order by c.column_id
)
loop
execute immediate 'alter table demo modify '||r.column_name||' invisible';
execute immediate 'alter table demo modify '||r.column_name||' visible';
end loop;
end;
/
SQL> desc demo
Name Null? Type
-------------------------------- -------- ----------------------
DEMO_ID NOT NULL NUMBER(38)
COL1 NUMBER
COL2 NUMBER
COL3 NUMBER
One thing you can't do (as of Oracle 18.0) is alter an existing column to make it into an identity column, so you have to either go through a process like the one above but copying the existing values and finally dropping the old column, or else define a new table explicitly with the identity column in place and copy the data across in a separate step. Otherwise you'll get:
-- DEMO_ID column exists but is currently not an identity column:
alter table demo modify demo_id generated by default on null as identity start with limit value;
-- Fails with:
ORA-30673: column to be modified is not an identity column
add the column
alter table table_name add (id INTEGER);
create a sequence table_name_id_seq with start with clause, using number of rows in the table + 1 or another safe value(we don't want duplicate ids);
lock the table (no inserts)
alter table table_name lock exclusive mode;
fill the column
update table_name set id = rownum; --or another logic
add a trigger to automaticaly put the id on insert using the sequence(you can find examples on internet, for example this answer)
When you'll fire the create trigger the lock will be released. (it automatically commits).
Also, you may add unique constraint on the id column, it is best to do so.
For Oracle :
CREATE TABLE new_table AS (SELECT ROWNUM AS id, ta.* FROM old_table ta)
remember this id column is not auto incremented

Can I alter the constraints of one table by using the constraints of another table?

I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.
I have tried adding the constraints, triggers, and indices manually, but there are just too many.
I was wondering if I could do something like:
alter table t73
modify col_n....col_n+1
using (select constraints from t73#otherdb)
No, that won't work.
What you could do is to use some GUI (like TOAD or SQL Developer), find table t73, have a look at its Script which contains all commands (CREATE TABLE, CREATE INDEX, CREATE CONSTRAINT, ...) and copy/paste the ones you need and execute them in your current database.
That would be quick.
If you want to do it right (you know, pretending you know what you're doing, just like I do), then see DBMS_METADATA.GET_DDL and extract those commands from the database.
The final result should be the same.
this is below example how you can use dbms_metadata.get_ddl oracle package
create table EX_EMPLOYEe ( id number(5) null, name varchar2(100))
/
alter table ex_Employee add constraint PK_EX_EMPLOYEE primary key (id)
/
alter table ex_Employee add constraint FK_EX_EMPLOYEE foreign key (id)
references ex_Employee1 (id)
/
create table EX_EMPLOYEe1 ( id number(5) null, name varchar2(100))
/
alter table ex_Employee1 add constraint PK_EX_EMPLOYEE1 primary key (id)
alter table SYS_PARAM_KEY_LABEL
add constraint FK1_SYS_PARAM_KEY_LABEL foreign key (KEY_GROUP_ID)
references SYS_PARAM_KEY_GROUP (KEY_GROUP_ID);
/
CREATE INDEX IDX_EX_EMPLOYEe on ex_employee(name)
/
Create or replace PROCEDURE P_EX_EMPLOYEe as
begin
select id from ex_employee where rownum=1;
end;
/
CREATE OR REPLACE TRIGGER TRG_EX_EMPLOYEe AFTER DELETE ON EX_EMPLOYEe
FOR EACH ROW
BEGIN
DELETE FROM ex_employee1 WHERE id = :OLD.ID;
END;
/
select to_char( dbms_metadata.get_ddl('CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='P'
union
select to_char( dbms_metadata.get_ddl('REF_CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='R'
union
select to_char( dbms_metadata.get_ddl('INDEX', c.index_name)) from user_indexes c where table_name='EX_EMPLOYEE'
union
select to_char( dbms_metadata.get_ddl('PROCEDURE', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='PROCEDURE'
union
select to_char( dbms_metadata.get_ddl('TRIGGER', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='TRIGGER'

Adding a NOT NULL column to a Redshift table

I'd like to add a NOT NULL column to a Redshift table that has records, an IDENTITY field, and that other tables have foreign keys to.
In PostgreSQL, you can add the column as NULL, fill it in, then ALTER it to be NOT NULL.
In Redshift, the best I've found so far is:
ALTER TABLE my_table ADD COLUMN new_column INTEGER;
-- Fill that column
CREATE TABLE my_table2 (
id INTEGER IDENTITY NOT NULL SORTKEY,
(... all the fields ... )
new_column INTEGER NOT NULL,
PRIMARY KEY(id)
) DISTSTYLE all;
UNLOAD ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;
COPY my_table2
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;
DROP table my_table;
ALTER TABLE my_table2 RENAME TO my_table;
-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)
Is this the best way of achieving this?
You can achieve this w/o having to load to S3.
modify the existing table to create the desired column w/ a default value
update that column in some way (in my case it was copying from another column)
create a new table with the column w/o a default value
insert into the new table (you must list out the columns rather than using (*) since the order may be the same (say if you want the new column in position 2)
drop the old table
rename the table
alter table to give correct owner (if appropriate)
ex:
-- first add the column w/ a default value
alter table my_table_xyz
add visit_id bigint NOT NULL default 0; -- not null but default value
-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;
-- now create the new table with the proper constraints
create table my_table_xzy_new
(
key bigint not null,
visit_id bigint NOT NULL, -- here it is not null and no default value
adt_id bigint not null
);
-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;
-- remove the orig table
DROP table my_table_xzy_events;
-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;
-- adjust any views, foreign keys or permissions as required

Oracle SQL to change column type from number to varchar2 while it contains data

I have a table (that contains data) in Oracle 11g and I need to use Oracle SQLPlus to do the following:
Target: change the type of column TEST1 in table UDA1 from number to varchar2.
Proposed method:
backup table
set column to null
change data type
restore values
The following didn't work.
create table temp_uda1 AS (select * from UDA1);
update UDA1 set TEST1 = null;
commit;
alter table UDA1 modify TEST1 varchar2(3);
insert into UDA1(TEST1)
select cast(TEST1 as varchar2(3)) from temp_uda1;
commit;
There is something to do with indexes (to preserve the order), right?
create table temp_uda1 (test1 integer);
insert into temp_uda1 values (1);
alter table temp_uda1 add (test1_new varchar2(3));
update temp_uda1
set test1_new = to_char(test1);
alter table temp_uda1 drop column test1 cascade constraints;
alter table temp_uda1 rename column test1_new to test1;
If there was an index on the column you need to re-create it.
Note that the update will fail if you have numbers in the old column that are greater than 999. If you do, you need to adjust the maximum value for the varchar column
Add new column as varchar2, copy data to this column, delete old column, rename new column as actual column name:
ALTER TABLE UDA1
ADD (TEST1_temp VARCHAR2(16));
update UDA1 set TEST1_temp = TEST1;
ALTER TABLE UDA1 DROP COLUMN TEST1;
ALTER TABLE UDA1
RENAME COLUMN TEST1_temp TO TEST1;
Look at Oracle's package DBMS_REDEFINE. With some luck you can do it online without downtime - if needed. Otherwise you can:
Add new VARCHAR2 column
Use update to copy NUMBER into VARCHAR2
Drop NUMBER column
Rename VARCHAR2 column
Here you go, this solution did not impact the existing NOT NULL or Primary key constraints. Here i am going to change the type of Primary key from Number to VARCHAR2(3), Here are the Steps on example table employee.
Take backup of table and Index, Constraints
created table employee_bkp
create table employee_bkp as select * from employee
commit;
Truncate the table to empty it
truncate table employee
Alter the table to change the type
ALTER TABLE employee MODIFY employee_id varchar2(30);
Copy the data back from backup table
insert into employee (select * from employee_bkp)
commit;
Verify

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

I would like to write a single SQL command to drop multiple columns from a single table in one ALTER TABLE statement.
From MSDN's ALTER TABLE documentation...
DROP { [CONSTRAINT] constraint_name | COLUMN column_name }
Specifies that constraint_name or column_name is removed from the table. DROP COLUMN is not allowed if the compatibility level is 65 or earlier. Multiple columns and constraints can be listed.
It says that mutliple columns can be listed in the the statement but the syntax doesn't show an optional comma or anything that would even hint at the syntax.
How should I write my SQL to drop multiple columns in one statement (if possible)?
For SQL Server:
ALTER TABLE TableName
DROP COLUMN Column1, Column2;
The syntax is
DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ]
For MySQL:
ALTER TABLE TableName
DROP COLUMN Column1,
DROP COLUMN Column2;
or like this1:
ALTER TABLE TableName
DROP Column1,
DROP Column2;
1 The word COLUMN is optional and can be omitted, except for RENAME COLUMN (to distinguish a column-renaming operation from the RENAME table-renaming operation). More info here.
Summarizing
Oracle:
ALTER TABLE table_name DROP (column_name1, column_name2);
MS SQL Server:
ALTER TABLE table_name DROP COLUMN column_name1, column_name2
MySQL:
ALTER TABLE table_name DROP column_name1, DROP column_name2;
PostgreSQL
ALTER TABLE table_name DROP COLUMN column_name1, DROP COLUMN column_name2;
Be aware
DROP COLUMN does not physically remove the data for some DBMS. E.g. for MS SQL. For fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD.
create table test (a int, b int , c int, d int);
alter table test drop column b, d;
Be aware that DROP COLUMN does not physically remove the data, and for fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD.
This may be late, but sharing it for the new users visiting this question.
To drop multiple columns actual syntax is
alter table tablename drop column col1, drop column col2 , drop column col3 ....
So for every column you need to specify "drop column" in Mysql 5.0.45.
The Syntax as specified by Microsoft for the dropping a column part of an ALTER statement is this
DROP
{
[ CONSTRAINT ]
{
constraint_name
[ WITH
( <drop_clustered_constraint_option> [ ,...n ] )
]
} [ ,...n ]
| COLUMN
{
column_name
} [ ,...n ]
} [ ,...n ]
Notice that the [,...n] appears after both the column name and at the end of the whole drop clause. What this means is that there are two ways to delete multiple columns. You can either do this:
ALTER TABLE TableName
DROP COLUMN Column1, Column2, Column3
or this
ALTER TABLE TableName
DROP
COLUMN Column1,
COLUMN Column2,
COLUMN Column3
This second syntax is useful if you want to combine the drop of a column with dropping a constraint:
ALTER TBALE TableName
DROP
CONSTRAINT DF_TableName_Column1,
COLUMN Column1;
When dropping columns SQL Sever does not reclaim the space taken up by the columns dropped. For data types that are stored inline in the rows (int for example) it may even take up space on the new rows added after the alter statement. To get around this you need to create a clustered index on the table or rebuild the clustered index if it already has one. Rebuilding the index can be done with a REBUILD command after modifying the table. But be warned this can be slow on very big tables. For example:
ALTER TABLE Test
REBUILD;
For MySQL (ver 5.6), you cannot do multiple column drop with one single drop-statement but rather multiple drop-statements:
mysql> alter table test2 drop column (c1,c2,c3);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(c1,c2,c3)' at line 1
mysql> alter table test2 drop column c1,c2,c3;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'c2,c3' at line 1
mysql> alter table test2 drop column c1, drop column c2, drop c3;
Query OK, 0 rows affected (0.64 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql>
BTW, drop <col_name> is shorthanded for drop column <col_name> as you can see from drop c3 above.
If it is just single column to delete the below syntax works
ALTER TABLE tablename DROP COLUMN column1;
For deleting multiple columns, using the DROP COLUMN doesnot work, the below syntax works
ALTER TABLE tablename DROP (column1, column2, column3......);
Generic:
ALTER TABLE table_name
DROP COLUMN column1,column2,column3;
E.g:
ALTER TABLE Student
DROP COLUMN Name, Number, City;
alter table tablename drop (column1, column2, column3......);
for postgis is
alter table table01 drop columns col1, drop col2
this query will alter the multiple column test it.
create table test(a int,B int,C int);
alter table test drop(a,B);
ALTER table table_name Drop column column1, Drop column column2,Drop column column3;
for MySQL DB.
Or you can add some column while altering in the same line:
ALTER table table_name Drop column column1, ADD column column2 AFTER column7;