Rename table via sp_rename or ALTER SCHEMA - sql

I am going to perform a table-wide update on a huge table (+200Millon records) so I am going to populate the data via SELECT into a separate table, than drop the original and rename the new one.
In one of the articles someone mentioned that it is better to create the new table with the same name in a temporary schema (e.g. 'clone') and switch it to the used one (e.g. 'dbo'), than to use the original schema with a temporary name and call sp_rename after the data is in place and the old table is dropped.
I was looking into this, but I cannot think of anything why the schema switch is better than the sp_rename. Can anyone find any good reason why is better to use the first or the second approach?
Thanks!
EDIT: I want to update the values in a specific column
EDIT2: Ultimately my question is, if I decide to go down the way of creating a new table to transfer data to which alternative to use:
CREATE TABLE dbo.newTable
...
DROP TABLE dbo.originalTable
EXEC sp_rename N'dbo.newTable', N'dbo.originalTable'
OR
CREATE TABLE clone.originalTable
...
DROP TABLE dbo.originalTable
ALTER SCHEMA dbo TRANSFER clone.originalTable

By the way, I would suggest that you WON'T populate the table by using SELECT * INTO. This will lock your source table for everyone else during the insertion, which could take quite a time.
Just a suggestion, try this instead:
SELECT TOP 0 INTO [newTable]
FROM [oldTable]
INSERT INTO [newTable]
SELECT * FROM [oldTable]
By the way, you can use sp_rename to rename your table to another name. But it won't change the schema. If you try to change the schema too it will produce a buggy table name.
You can instead try to move the table to another name. Example below:
EXEC sp_rename N'oldTable', N'oldTable_Backup'
EXEC sp_rename N'newTable', N'oldTable'
Hopefully this will help you.

Based on your edited answer the quickest way to do that is:
If you have to include default value to the column
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[WITH VALUES]
and then drop the old column from the table.
ALTER TABLE {TABLENAME} DROP COLUMN {OLD COLUMN}
If you have to update table column based calculated values
Disable index on the column which you are updating
Create index on the column which are in WHERE clause
Update statistics
Use WITH(NOLOCK) table hint [if you are fine with dirty read]
Update
As per edit 2, your first statement is about changing table name and second statement is about changing schema. They both are different and does not related to moving data or updating value. In this case, changing schema would be the best bet

If locking was an issue before it still is regardless of what version SQL Server that you are using. When you drop and rename you are also losing all the rights on the table.

Related

Add column with data from another stdinfo5table into viewtable in sql query

select name into viewtable from stdinfo5
My error is:
There is already an object named 'viewtable' in the database.
Can someone explain: I want column with data (adding) into viewtable from the stdinfo5 table.
Thanks!
select ... into SomeTarget from SomeSource will create a physical table with the name SomeTarget!
You can use DROP TABLE SomeTarget to delete this table (carefull with real data!!!) or, what might be better, use select ... into #SomeTarget ....
The # before the name will create this table as temp table which is deleted automatically when it gets out of scope.
In your case it seems, that you do not want to delete the table, but you just want to add one more column. In this case you'd need something like ALTER TABLE viewtable ADD TheColumnName TheColumnType; and then use an UPDATE statement to fill this column. If possible, it was easier to delete the table and re-create it with the missing column...

Oracle SQL. How to change table field datatype CLOB-->VARCHAR2

I have database and some text fields are CLOB type, I need to change most of these into VARCHAR2.
Have tried to do that using SQL Developer tool, by clicking edit on table, but get error like this one:
The following SQL statement failed:
ALTER TABLE TBL_PEOPLE MODIFY (PERSON VARCHAR2(150) )
Want to ask, how can this change be done
You can't, directly. The code you tried will have got an `ORA-22859, presumably. (It's helpful to show the actual errors you get, of course).
You'll need to add a new varchar2 column; copy the data across - or a substring of it if it might be larger than the new column you're creating; drop the clob column. You can rename the columns so it looks fairly transparent.
As in this SQL Fiddle:
alter table tbl_people rename column person to clob_person;
alter table tbl_people add (person varchar2(150));
update tbl_people set person = clob_person;
alter table tbl_people drop column clob_person;
Obviously don't drop the old column until you're sure the data has copied without errors. Also take into account any constraints, indexes, etc. that might exist in the old column; they will need to be recreated. And anything that references the old column will have been invalidated - generally procedures will recompile themselves on next use.
So be careful, test it first, and plan some down time.
ALTER TABLE tablename ADD (FIELD_LIST_TEMP VARCHAR2);
UPDATE tablename SET FIELD_LIST_TEMP = FIELD_LIST;
ALTER TABLE tablename DROP COLUMN FIELD_LIST;
ALTER TABLE tablename RENAME COLUMN FIELD_LIST_TEMP TO FIELD_LIST;
Here FIELD_LIST existing column which is defined it as CLOB. With above query it will change from CLOB to VARCHAR2.

Fastest way to copy a table in mysql?

I want to copy a table in MySQL. What is the fastest way? Like this?
CREATE TABLE copy LIKE original;
INSERT INTO copy SELECT * FROM original;
or
CREATE TABLE copy SELECT * FROM original;
ALTER TABLE copy ADD PRIMARY KEY (id);
or is there another way?
EDIT: I'm worried about the indexes being re-created, how does mysql proceed executing these statements?
PS. can't use command-line tools like mysqldump, must be on-the-fly.
This copies the structure of the table immediately, but not the data:
CREATE TABLE copy LIKE original;
This creates all the indexes the original table had.
It works this way in mysql 5.1.39.
The fastest way using MyISAM tables while preserving indexes) and maybe other storage engines is:
CREATE TABLE copy LIKE original;
ALTER TABLE copy DISABLE KEYS;
INSERT INTO copy SELECT * FROM original;
ALTER TABLE copy ENABLE KEYS;
You want to disable your keys for your database load and then recreate the keys at the end.
Similarly, for InnoDB:
SET unique_checks=0; SET foreign_key_checks=0;
..insert sql code here..
SET unique_checks=1; SET foreign_key_checks=1;
(As pointed out in the comments.)
From the manual:
"CREATE TABLE ... SELECT does not automatically create any indexes for you. This is done intentionally to make the statement as flexible as possible. If you want to have indexes in the created table, you should specify these before the SELECT statement: "
CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;
You can specify indices and data types (to avoid datatype conversion) in with both CREATE TABLE LIKE and CREATE TABLE SELECT. Which one is faster will depend on your setup.
To copy with indexes and triggers do these 2 queries:
CREATE TABLE newtable LIKE oldtable;
INSERT newtable SELECT * FROM oldtable;
To copy just structure and data use this one:
CREATE TABLE tbl_new AS SELECT * FROM tbl_old;
Does create table mynewtable (select * from myoldtable) work in mysql? If so you can try it too.
Best way to copy structure and all entries from one table to another table (by creating new table) is this query...
CREATE TABLE new_table LIKE old_table;
INSERT INTO new_table
SELECT * FROM old_table;
Try SELECT INTO, and use a variable as a go-between.
You'll have to create the receiving table, first, to have the same structure as the source table.
Best thing is, it's internal so it's fast. You'll lose your indexes, though.
if you are using MyISAM you can also copying and renaming the induvidual files .
.MYD, .MYI, .FRM files in the backend
Maybe you could take a look at SHOW CREATE TABLE.
Steps to take:
Go to phpmyadmin
Go to SQL
Execute this query
SHOW CREATE TABLE `the_old_table`;
Click options
Check "Full texts" and press Go.
The result is a full CREATE TABLE statement. Edit the query until you are happy.
Resource:
http://dev.mysql.com/doc/refman/5.7/en/show-create-table.html
CREATE TABLE copy SELECT * FROM original;
Is a fast way but maybe not the quickest cause of indexes.

How to change column order in a table using sql query in sql server 2005?

How to change column order in a table using SQL query in SQL Server 2005?
I want to rearrange column order in a table using SQL query.
You cannot. The column order is just a "cosmetic" thing we humans care about - to SQL Server, it's almost always absolutely irrelevant.
What SQL Server Management Studio does in the background when you change column order there is recreating the table from scratch with a new CREATE TABLE command, copying over the data from the old table, and then dropping it.
There is no SQL command to define the column ordering.
You have to explicitly list the fields in the order you want them to be returned instead of using * for the 'default' order.
original query:
select * from foobar
returns
foo bar
--- ---
1 2
now write
select bar, foo from foobar
bar foo
--- ---
2 1
according to https://learn.microsoft.com/en-us/sql/relational-databases/tables/change-column-order-in-a-table
This task is not supported using Transact-SQL statements.
Well, it can be done, using create/ copy / drop/ rename, as answered by komma8.komma1
Or you can use SQL Server Management Studio
In Object Explorer, right-click the table with columns you want to reorder and click Design (Modify in ver. 2005 SP1 or earlier)
Select the box to the left of the column name that you want to reorder. (You can select multiple columns by holding the [shift] or
the [ctrl] keys on your keyboard.)
Drag the column(s) to another location within the table.
Then click save. This method actually drops and recreates the table, so some errors might occur.
If Change Tracking option is enabled for the database and the table, you shouldn't use this method.
If it is disabled, the Prevent saving changes that require the table re-creation option should be cleared in Tools menu > Options > Designers, otherwise "Saving changes is not permitted" error will occur.
Disabling the Prevent saving changes that require the table re-creation option is strongly advised against by Microsoft, as it leads to the existing change tracking information being deleted when the table is re-created, so you should never disable this option if Change Tracking is enabled!
Problems may also arise during primary and foreign key creation.
If any of the above errors occurs, saving fails which leaves you with the original column order.
In SQLServer Management Studio:
Tools -> Options -> Designers -> Table and Database Designers
Unselect 'Prevent saving changes that require table re-creation'.
Then:
right click the table you want to re-order the columns for.
click 'Design'.
Drag the columns to the order you want.
finally, click save.
SQLServer Management studio will drop the table and recreate it using the data.
This is similar to the question on ordering the records in the result of a query .. and typically no one likes the formally correct answer ;-)
So here it goes:
as per SQL standard, the columns in a table are not "ordered"
as a result, a select * does not force the columns to be returned in a particular order
typically, each RDBMS has a kind of "default" order (usually the order that the columns were added to the table, either in the create table' or in thealter table add ` statements
therefore, if you rely on the order of columns (because you are using the results of a query to poulate some other datastructure from the position of the columns), explicitly list the columns in the order you want them.
You can of course change the order of the columns in a sql statement. However if you want to abstract tables' physical column order, you can create a view. i.e
CREATE TABLE myTable(
a int NULL,
b varchar(50) NULL,
c datetime NULL
);
CREATE VIEW vw_myTable
AS
SELECT c, a, b
FROM myTable;
select * from myTable;
a b c
- - -
select * from vw_myTable
c a b
- - -
You can do it by creating a new table, copy all the data over, drop the old table, then renaming the new one to replace the old one.
You could also add new columns to the table, copy the column by column data over, drop the old columns, then rename new columns to match the old ones. A simple example below:
http://sqlfiddle.com/#!3/67af4/1
CREATE TABLE TestTable (
Column1 INT,
Column2 VARCHAR(255)
);
GO
insert into TestTable values(1, 'Test1');
insert into TestTable values(2, 'Test2');
GO
select * from TestTable;
GO
ALTER TABLE TestTable ADD Column2_NEW VARCHAR(255);
ALTER TABLE TestTable ADD Column1_NEW INT;
GO
update TestTable
set Column1_NEW = Column1,
Column2_NEW = Column2;
GO
ALTER TABLE TestTable DROP COLUMN Column1;
ALTER TABLE TestTable DROP COLUMN Column2;
GO
sp_rename 'TestTable.Column1_NEW', 'Column1', 'COLUMN';
GO
sp_rename 'TestTable.Column2_NEW', 'Column2', 'COLUMN';
GO
select * from TestTable;
GO
In SQLServer Management Studio:
Tools -> Options -> Designers -> Table and Database Designers
Unselect Prevent saving changes that require table re-creation.
Now you can reorder the table.
Sql server internally build the script. It create a temporary table with new changes and copy the data and drop current table then recreate the table insert from temp table. I find it from "Generate Change script" option ssms 2014. Script like this. From Here: How to change column order in a table using sql query
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_emps
(
id int NULL,
ename varchar(20) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_emps SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.emps)
EXEC('INSERT INTO dbo.Tmp_emps (id, ename)
SELECT id, ename FROM dbo.emps WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.emps
GO
EXECUTE sp_rename N'dbo.Tmp_emps', N'emps', 'OBJECT'
GO
COMMIT
If your table has enough columns then you can try this. First create a new table with preferred order of columns.
create table new as select column1,column2,column3,....columnN from table_name;
Now drop the table using drop command
drop table table_name;
now rename the newly created table to your old table name.
rename new to table_name;
now select the table, you have your columns rearranged as you preferred before.
select * from table_name;
Not sure if still relevant, but SSMS can generate a change scripts for this.
Re-order (drag the column) the table in Designer View
Click on 'Generate Change Script'
The generated script contains the script which does the following:
Create a temporary table
Adds the constraints, relationships and triggers from original table to temporary table
Drop original table
Rename temporary table to original table name
If you have not yet added any data into your table yet, there is one way to move the columns around.
Try this:
In SSMS, click Tools > Options > Designers > Table and Database Designers > Uncheck the box next to Prevent saving changes that require table re-creation > Click OK.
In the object tree, right-click on your table and select Design > in the thin column to the left of the Column Name column, you can click and drag the columns around to wherever you want them. When you're done, just go to close the Design tab and SSMS will ask you if you want to save your changes, click OK.
Optional:
3. Re-enable the checkbox for the option from Step 1 to re-secure your table.
Hope this helps someone!
Credit goes to Microsoft:
https://learn.microsoft.com/en-us/troubleshoot/sql/ssms/error-when-you-save-table#more-information
At the end of the day, you simply cannot do this in MS SQL. I recently created tables on the go (application startup) using a stored Procedure that reads from a lookup table. When I created a view that combined these with another table I had manually created earlier one (same schema, with data), It failed - simply because I was using ''Select * UNION Select * ' for the view. At the same time, if I use only those created through the stored procedure, I am successful.
In conclusion: If there is any application which depends on the order of column it is really not good programming and will for sure create problems in the future. Columns should 'feel' free to be anywhere and be used for any data process (INSERT, UPDATE, SELECT).
You can achieve it with these steps:
remove all foreign keys and primary key of the original table.
rename the original table.
using CTAS create the original table in the order you want.
drop the old table.
apply all constraints back to the original table
If the columns to be reordered have recently been created and are empty, then the columns can be deleted and re-added in the correct order.
This happened to me, extending a database manually to add new functionality, and I had missed a column out, and when I added it, the sequence was incorrect.
After finding no adequate solution here I simply corrected the table using the following kind of commands.
ALTER TABLE tablename DROP COLUMN columnname;
ALTER TABLE tablename ADD columnname columntype;
Note: only do this if you don't have data in the columns you are dropping.
People have said that column order does not matter. I regularly use SQL Server Management Studio "generate scripts" to create a text version of a database's schema. To effectively version control these scripts (git) and to compare them (WinMerge), it is imperative that the output from compatible databases is the same, and the differences highlighted are genuine database differences.
Column order does matter; but just to some people, not to everyone!
Use
SELECT * FROM TABLE1
which displays the default column order of the table.
If you want to change the order of the columns.
Specify the column name to display correspondingly
SELECT COLUMN1, COLUMN5, COLUMN4, COLUMN3, COULMN2 FROM TABLE1
you can use indexing.. After indexing, if select * from XXXX results should be as per the index, But only result set.. not structrue of Table
In order to have a specific column order You need to select column by column in the order You wish.
Selection order dictates how columns will be ordered in output.
Try this command:
alter table students modify age int(5) first;
This will change the position of age to the first position.
You can change this using SQL query. Here is sql query to change the sequence of column.
ALTER TABLE table name
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;
alter table name modify columnname int(5) first;
will bring the column to first
alter table name modify columnname int(5) after (tablename);
This worked for me on Oracle DB:
select column1, column2, t.* from table t
Example: Change position of field_priority after field_price in table status.
ALTER TABLE `status` CHANGE `priority` `priority` INT(11) NULL DEFAULT NULL AFTER `price`;

How do I rename a column in a database table using SQL?

If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?
This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.
Specifically for SQL Server, use sp_rename
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE statement:
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
In MySQL, the syntax is ALTER TABLE ... CHANGE:
ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...
Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.
Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.
ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
UPDATE MyTable SET MyNewColumn = MyOldColumn;
-- add all necessary triggers and constraints to the new column...
-- update all foreign key usages to point to the new column...
ALTER TABLE MyTable DROP COLUMN MyOldColumn;
For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.
However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.
I think this is the easiest way to change column name.
SP_RENAME 'TABLE_NAME.OLD_COLUMN_NAME','NEW_COLUMN_NAME'
In sql server you can use
exec sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
or
sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
In Informix, you can use:
RENAME COLUMN TableName.OldName TO NewName;
This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.
You can use the following command to rename the column of any table in SQL Server:
exec sp_rename 'TableName.OldColumnName', 'New colunmName'
ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.
The standard would be ALTER TABLE, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.
Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio, from the table Design Panel.
First Way
Slow double-click on the column. The column name will become an editable text box.
Second Way
SqlManagement Studio>>DataBases>>tables>>specificTable>>Column
Folder>>Right Click on column>>Reman
Third Way
Table>>RightClick>>Design
To rename you have to change the column
e.g
Suppose
*registration is Table Name
newRefereeName is a column name That I want to change to refereeName
SO my SQL Query will be*
ALTER TABLE 'registration' CHANGE 'newRefereeName' 'refereeName' VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;
exec sp_rename 'Tablename.OldColumnName', 'NewColumnName', 'Column';