How to change all table prefix in a single query - mysql

I am pretty amateur in mysql..can you please tell me how can I change table prefixes of my whole database in a single query... I can do it manually, but its quite time consuming to change all the tables prefixes. Please help me out. Like isc_administrator_log to cus_administrator_log means isc_ to cus_
I found these two solutions but do not understand either of them.
SELECT
GROUP_CONCAT('RENAME TABLE `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` TO `',
TABLE_SCHEMA, '`.`prefix_', TABLE_NAME, '`;' SEPARATOR ' ')
FROM `TABLES` WHERE `TABLE_SCHEMA` = "test";
and
SELECT
CONCAT('RENAME TABLE ', GROUP_CONCAT('`', TABLE_SCHEMA, '`.`', TABLE_NAME,
'` TO `', TABLE_SCHEMA, '`.`prefix_', TABLE_NAME, '`')) AS q
FROM
`information_schema`.`Tables` WHERE TABLE_SCHEMA='test';

Both statements generate strings which happen to be SQL statements that you can then copy/paste at your prompt to rename your tables.
Just replace the following two strings with the actual values your need:
prefix_ : the prefix you want to add
'test' : the name of the database containing the tables you want to rename
Both statements are almost identical, the only difference is that information_schema is not explicitely mentioned in the first statement. Therefore the first statement must be run from the information_schema database (issue USE information_schema beforehands).

phpmyadmin : select database ; tab structure => Check all => (with selected list) select add prefix to table .
(is not query but it works)

You can do Dynamic SQL Query For MySQL 5.0.13
delimiter //
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
SET #s = CONCAT('SELECT 'RENAME TABLE ',
GROUP_CONCAT('', TABLE_SCHEMA, ''.'', TABLE_NAME,
' TO ', TABLE_SCHEMA, ''='.prefix_''', TABLE_NAME, '')) AS q
FROM
information_schema.Tables WHERE TABLE_SCHEMA='test'';;'
PREPARE stmt FROM #s;
EXECUTE stmt;
END
//
delimiter ;
Got the Reference from here

Related

Convert MySQL Variable Query to PostgreSQL

I have migrated MYSQL database to PostgreSQL and I am now converting my queries to match. I have this MySQL query in the Python file:
SET #Drop_Stm = CONCAT('DROP TABLE ', (SELECT GROUP_CONCAT(TABLE_NAME) AS All_Tables
FROM information_schema.tables
WHERE TABLE_NAME LIKE 'temp_%' AND TABLE_SCHEMA = '{client_name}'))
 
I would like to make it works in Postgres, I tried the following but returns error:
WITH Drop_Stm AS (CONCAT('DROP TABLE ', (SELECT STRING_AGG(TABLE_NAME, ',') AS All_Tables
FROM information_schema.tables
WHERE TABLE_NAME LIKE 'temp_%' AND TABLE_SCHEMA = '{client_name}')))
LINE 1: WITH Drop_Stm AS (CONCAT('DROP TABLE ', (SELECT STRING_AGG(T...
^
I also tried DECLARE, SET, and DO $$ .. END $$ with no luck
The query itself should be changed to this:
select concat('drop table ', string_agg(format('%I.%I', table_schema, table_name), ','), ' cascade;')
FROM information_schema.tables
WHERE TABLE_NAME LIKE 'temp_%'
AND TABLE_SCHEMA = '{client_name}'
Note that I used the format() function to properly deal with identifiers needing quoting. I also generated a fully qualified table name (including the schema) so that you don't accidentally drop a table in the current schema, rather than {client_name}.
If you want to run the generated script, I see two options. One is to put this into a PL/pgSQL block and use execute:
do
$$
declare
l_stmt text;
begin
select concat('drop table ', string_agg(format('%I.%I', table_schema, table_name), ','), ' cascade;')
into l_stmt
FROM information_schema.tables
WHERE TABLE_NAME LIKE 'temp_%'
AND TABLE_SCHEMA = '{client_name}';
execute l_stmt;
end;
$$
;
I don't know Python, so I am not entirely sure if {client_name} gets replaced correctly with that approach.
Another option is to run the SELECT query in Python, and store the result into a Python variable then run that SQL through Python.

Replace space with underscore in all table names in database

I'm trying to replace all space (' ') with a underscore in all the table names in a database using PhpMyAdmin.
Ex:
Table 1 --> Table_1
I was wondering if this is possible. I know it's possible to do this for columns but I was wondering if someone could write me something for tables. I don't use PhpMyAdmin very often, but I installed it in this case becuase it works easily.
I'm not sure if you could do this in a stored procedure, but it is easy enough to have a query generate a script for you:
SELECT CONCAT('RENAME TABLE `'
, table_name
, '` TO `'
, REPLACE(table_name, ' ', '_')
, '`;'
) AS renameQuery
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'mySchema' AND TABLE_NAME LIKE '% %'
;
You could run a query like this to generate the SQL that will perform a rename:
SELECT CONCAT('RENAME TABLE ', table_name, ' TO ' , REPLACE(table_name, ' ', '_') , ';')
FROM information_schema.tables
WHERE table_schema = 'your_schema_name';
Remember to substitute your_schema_name for whatever your database is called.
To run the query in phpMyAdmin you can click the SQL tab at the top of the window, then paste the SQL into the box. The result of the above query will be SQL generated based off of the existing table names. Just copy this resulting SQL back into the textbox and run it again to perform the renames.
You can also rename all table with one command:
SELECT
CONCAT('RENAME TABLE '
,GROUP_CONCAT(
CONCAT('`',TABLE_NAME,'` TO ', REPLACE(TABLE_NAME,' ','_'))
SEPARATOR ', '),';') AS query
FROM information_schema.Tables
WHERE TABLE_SCHEMA = 'yourschema'
AND TABLE_NAME LIKE '% %';
sample
MariaDB [yourschema]> SELECT CONCAT('RENAME TABLE ' ,GROUP_CONCAT( CONCAT('`',TABLE_NAME,'` TO ', REPLACE(TABLE_NAME,' ','_')) SEPARATOR ', '),';') AS query FROM information_schema.Tables WHERE TABLE_SCHEMA = 'yourschema' AND TABLE_NAME LIKE '% %';
+--------------------------------------------------------------------------------------+
| query |
+--------------------------------------------------------------------------------------+
| RENAME TABLE `esercizio 1` TO esercizio_1, `my_table 1` TO my_table_1, `t 1` TO t_1; |
+--------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
MariaDB [yourschema]>

Making All Column Name Lower Case MySQL

I have inherited a large MySQL database.
Its a mess: half the column names are upper case, other mixed case, other lower case.
I wish to standardize them
Is there a query I can run to alter each one so that they are all lower case?
Try this for rename all tables and columns to lower case:-
SELECT CONCAT('ALTER TABLE ', TABLE_NAME, ' CHANGE `', COLUMN_NAME, '` `',
LOWER(COLUMN_NAME), '` ', COLUMN_TYPE, ';')
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{your schema name}'
Yes. You will be able to compose a query that will
1. Enumerate the tables in the database.
2. Enumerate the columns for each database.
3. If the column name is not equal to LCASE of its name, rename it to LCASE of its name.
When you post an example of what you've tried, I may be able to update this answer to be more helpful.
By this
SELECT CONCAT(
'ALTER TABLE ', table_name, ' CHANGE ', column_name, ' ',
LOWER(column_name), ' ', column_type, ' ', extra,
CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END, ';') AS line
FROM information_schema.columns
WHERE table_schema = '<DBNAME>'
AND data_type IN ('char', 'varchar','INT', 'TINYINT', 'datetime','text','double','decimal')
ORDER BY line;
its not quite perfect but close enough.

Alter all columns WHERE datatype

Is there a way to change all columns that have a specific datatype in a database?
I have some columns that their datatype is datetime(6) and if any is like that I would just want them to be datatime ... without the 6 fractional numbers. Is this possible to do in MySql without having to specify every column? Thanks
You must create text string with necessary statements and save it in somewhere (i don't have columns with datetime(6), but must be like that):
select
concat('ALTER TABLE ',
TABLE_SCHEMA,
'.',
table_name,
' CHANGE COLUMN ',
Column_name,
' ',
Column_name,
' DATETIME NULL DEFAULT NULL')
from
INFORMATION_SCHEMA.COLUMNS
where
table_schema = 'my_schema'
and data_type = 'datetime'
and character_maximum_length = 6 #may be numeric_precision, i don't know
after use exec statement, like this:
PREPARE stmt1 FROM 'ALTER TABLE ....';
EXECUTE stmt1

SQL query to find duplicate rows, in any table in Mysql database

I'm looking for a schema-independent query. The query should be equally capable of catching duplicate rows in either table in a database.I have number of tables without primary key. I have found a result for sql server [which i have most experience] but looking for same thing in mysql
Use dynamic SQL to generate the query using the column information in information_schema:
SET #tablename = 'yourTable';
SET #sql = (
SELECT CONCAT('SELECT *
FROM `', table_name, '`
GROUP BY ', GROUP_CONCAT(CONCAT('`', column_name, '`')), '
HAVING COUNT(*) > 1')
FROM information_schema.columns
WHERE table_name = #tablename );
PREPARE stmt FROM #sql;
EXECUTE stmt;