Add a column if not exists in table [duplicate] - mysql

This question already has answers here:
add column to mysql table if it does not exist
(16 answers)
Closed 9 years ago.
I want to add a column which will be added in table only if column with same name is not exists.
Alter Table tablename
add col varchar(250)

I think you cant just execute your SQL and retrieve the error if the column already exists.
On the other hand, if you don't want to reach a possible error situation at the MySQL side you could try something like (dynamic SQL):
SET #query = (SELECT
IF((SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=database() AND
TABLE_NAME = 'YOUR_TABLE' AND COLUMN_NAME = 'COL')=0,
CONCAT('ALTER TABLE YOUR_TABLE ADD COLUMN COL varchar(255)'),
'SELECT ''ALREADY EXISTS'''
));
PREPARE st FROM #query;
EXECUTE st;
First, you will generate a SQL containing the column addition SQL or a dummy SQL depending on whether you already have the target column at the INFORMATION_SCHEMA.
PREPARE
and
EXECUTE
statements are used to execute that query.

use INFORMATION_SCHEMA database
SELECT
count(*)
FROM
information_schema.COLUMNS
WHERE
information_schema.TABLE_SCHEMA=DB name
AND information_schema.TABLE_NAME=table name
AND information_schema.COLUMN_NAME=col name
if count is more than 0 create the column else don't

Related

Check if a column exists in mysql [duplicate]

This question already has answers here:
Check if a column exists in a table with MySQL
(11 answers)
Closed 2 years ago.
How do I check if a column exists in a table and add one if it doesn't exist?(I am using mysql)
IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'columnName' AND OBJECT_ID = OBJECT_ID(N'tableName'))
BEGIN
PRINT 'Your Column Exists'
END
This is a sample one.The results I got one from web are the older versions of mysql. I need the answer in the latest version (mysql server 2019 and above) .How do I solve it?
You can access this kind of information from the information_schema database. It contains a columns table.
The information_schema database is part of ISO SQL, and implemented on all SQL servers :
MySQL (COLUMNS table)
SQL Server (COLUMNS table)
PostgreSQL (COLUMNS table)
Here is a portable query :
SELECT count(*) FROM information_schema.columns
WHERE table_schema = 'thedatabase'
AND table_name = 'thetable'
AND column_name = 'thecolumn';
You can use below query
SHOW COLUMNS FROM table_name LIKE '%column_name%'

Please explain these SQL statements

Please explain me the below example
SELECT GROUP_CONCAT(COLUMN_NAME)
FROM information_schema.`COLUMNS` C
WHERE table_name = 'table_name'
AND COLUMN_NAME =('columns_name') INTO #COLUMNS;
SET #table = 'table_name';
SET #s = CONCAT('SELECT ',#columns,' FROM ', #table);
PREPARE stmt FROM #s;
This pattern is all about creating dynamic (prepared in MySQL parlance) queries based on the names of columns in a particular table. INFORMATION_SCHEMA is a built-in database with read-only tables describing all the tables in all databases on the MySQL server.
The first query in your sequence retrieves a text string in the local variable #COLUMNS with a value like
id,name,value,description
for a table named table_name with those four columns.
The third one retrieves a string in the local variable #s with a value containing a query like
SELECT id,name,value,description FROM table_name
The fourth one, PREPARE, gets ready to do EXECUTE stmt, which runs the query. You can read about PREPARE and EXECUTE here.
The whole sequence of queries in your question does almost exactly the same thing as SELECT * FROM table_name.
There's a defect in your first query. You should add AND TABLE_SCHEMA = DATABASE() to its WHERE clause. Otherwise, you may pick up columns from tables named table_name in multiple databases.

Search in all tables for a field with given value or name [duplicate]

This question already has answers here:
Search text in fields in every table of a MySQL database
(27 answers)
Closed 4 years ago.
Is there a pure sql solution to search in all tables for a specific field with a given value or name. In pseudocode the query im looking for would be
SELECT * FROM * WHERE field = "value"
or
SELECT tablename, field FROM *
I already know how I could use the mysql information schema to search for all tables with the column, but I'm unsure if (and how) I could combine this inside a query (or stored procedure).
You can write a script wich will generate all queries:
SELECT concat('SELECT * FROM ',TABLE_NAME,' WHERE ',COLUMN_NAME,' =\'value\'')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'columnname'
;
Then, you can execute each rows of the result to get the needed data.

getting table name from a table and using the table name to access data

I want to create a database where there is a list of table names stored in a table. Now with the help of this list I can access the other tables.
Ex :-
Table name :- table_list (2 column i.e. table_name,table_id)
table_list attributes
authentication 1
basic_info 2
contact 3
I can directly access these tables using select statement but I want to access them using the table_list table preferably using select statement.
I tried
select * from (select table_name as x from table_list where id=2) as y
But could not get the proper output.
It is called Prepared Statements and their only use is when you want to implement your mentioned need in one request. Otherwise you can easily retrieve table names in a programming language and create your next statement using the data in hand. Here's how Prepared Statements work:
SELECT table_name INTO #tbl FROM my_tables WHERE id = 1 LIMIT 1;
SET #sql := CONCAT('SELECT * FROM ', #tbl);
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
TRY THIS
select * from (SELECT TABLE_NAME FROM TABLE_LIST WHERE ID=2)as y
The table name (an "identifier") must be a static part of the SQL text issed to the database; the identifier can't be supplied "on the fly", either as a parameter or as a result from another SQL query.
To do what you want to do, you will need a two step approach. You can use one (or more) SQL statements to obtain the identifiers you need (table name, column names, etc.), and then use that to dynamically create a second SQL statement, as a string.
The identifiers (table names, column anmes) can not be provided as parameters or "bind variables", they must be a static part of the SQL text.
For example, to generate the statement:
SELECT CONCAT('SELECT * FROM `',table_name,'` ORDER BY 1') AS stmt
FROM table_list
WHERE id = 2
(The coding details are dependent on what language you are using.)
Since you are sure that the table name you want to access is x, just check whether such a table exists using a query and use x for future purpose.

Set all the columns of a mysql table to a particular value

hIs there any way to update all the columns of a mysql table for a particular record in one go to a particular value.
For e.g. I have a table that has around 70 columns , and they are by default set to 0 at the time of creating the table,when I add a new record via PHPmyadmin by just filling in one or two values and submitting it all the other fields are set to 0 , but I want to set all the fields to 1
many times ,so I need to set all the columns to 1 individually via PHPmyadmin
To speed-en up the process and
I tried
UPDATE tablename SET * = '1' WHERE id = '2' , but it does not work.
If anyone can provide a solution on similar lines , it would be great.
EDIT:
Is there a way without specifying all the 70 columns in the SQL statement? that what I am looking for. I do know how to update normally specifying columns in the SQL statement. Thank you.
If you are looking for a way to update all 70 columns to a single value with a short, simple statement, then I recommend that you write a stored procedure to do the update. That way you only need to write out the full update syntax once, and can re-use it over and over by calling the stored procedure.
CREATE PROCEDURE update_all_columns (p_new_value SMALLINT, p_id INT) ...
CALL update_all_columns(1,2);
Another trick is to use the information_schema.columns table to generate the update statement, making it less tedious to code the stored procedure.
Something like this:
SELECT concat('UPDATE ',
table_name,
' SET ',
group_concat(column_name separator ' = p_new_value, '),
' = p_new_value',
' WHERE id = p_id;') as sql_stmt
FROM information_schema.columns
WHERE table_schema = 'your_schema'
AND table_name = 'tablename'
AND column_name != 'id'
You have to name each column in an update statement.