Deleting a row if a column exists in MySQL - mysql

I am trying to delete rows if new_id column value is equal to 2 from multiple mysql tables, but I don't know if all those tables have column new_id.
I try the following statement, but it gives a syntax error:
DELETE FROM table_name WHERE new_id =2 IF EXISTS new_id int(11)
How to do this?

you can get column name by using below query
SHOW COLUMNS FROM `table_name` LIKE 'new_id';
Then from frontend you can take the decision to execute delete query

You can check in information schema:
IF EXISTS ( SELECT *
FROM information_schema.columns
WHERE table_name = 'table_name'
AND column_name = 'new_id'
AND table_schema = DATABASE () ) THEN
DELETE FROM table_name WHERE new_id = 2;
END IF;

Related

MySQL: If after select(count(*) for Dropping column if exists

I already read multiples post about drop a column if exists on the forum as
if exists
(select * from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )
ALTER TABLE table_name DROP COLUMN column_name
But, unfortunately, none give a results on MySQL 5.7. It's because i try this:
if (select count(*) from information_schema.columns
where table_name = 'XXXX'
and column_name = 'XXXX')=1
then
ALTER TABLE `XXXX`.`XXXX` DROP COLUMN `XXXX`;
end if;
Please can someone explain me how to solve this issues?
Thanks in advance!

How I can use the result of SELECT statement in ALTER TABLE in MySQL?

I have a table with some properties. I would like use these properties to create some columns in another table (ALTER TABLE).
The follow SELECT statement result in multiple results:
SELECT property FROM table1 GROUP BY property;
Result example:
firstName
lastName
address
phone
For each result of select statement above, perform:
ALTER TABLE table2 ADD property boolean null;
How do?
Here is an example for postgres. With little modification you can use it for mysql too.
DO $$
DECLARE row_results record;
BEGIN FOR row_results IN
SELECT column_name
FROM information_schema.columns
WHERE table_schema='public'
AND table_type='BASE TABLE'
AND table_name = 'table1'
LOOP
EXECUTE format('ALTER TABLE table2 ADD COLUMN %I boolean NULL', row_results.column_name);
END LOOP;
END$$;

SQL add new columns ignoring duplicates

We have quite a few databases, and we're trying to run upgrade scripts on all of them to bring them up to date - as such, they all have different columns and tables.
We want to add new tables and columns if they arent already present, so for instance
CREATE TABLE IF NOT EXISTS `orders` ( `id` INT (11) NOT NULL ,
`value` VARCHAR (50) , `designId` INT (11) , PRIMARY KEY ( `id`));
That works, but we're looking for the same kind of solution for columns. Our current solution throws Error Code: 1060 - Duplicate column name.
ALTER TABLE `orders` ADD COLUMN `customer` INT (1) NULL;
I've tried the following from garry passarella, but i get an error claiming incorrect sql syntax:
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'orders' AND COLUMN_NAME = 'customer')
BEGIN ALTER TABLE orders
ADD customer BIT DEFAULT NULL
END
If there is something we can use to get each line to ignore duplicates, or get the entire script to ignore error code 1060, it would be much appreciated.
The if ... begin ... end is SQL Server syntax. For MySQL, it's more like if ... then ... end if:
if not exists (select * from information_schema.columns
where column_name = 'customer' and table_name = 'orders') then
alter table orders add customer int(1) null;
end if
In reply to your comment: in MySQL, you can't type compound statements at the command line. They have to be in a function or stored procedure. For example:
drop procedure if exists sp_addcolumn;
delimiter //
create procedure sp_addcolumn()
begin
if not exists (select * from INFORMATION_SCHEMA.COLUMNS
where table_name = 'orders' and column_name = 'customer') then
alter table `orders` add column `customer` int(1) null;
end if;
end//
delimiter ;
call sp_addcolumn;
There is an open request on the MySQL bug tracker to allow if statements outside stored procedures. It's current status is Needs Triage.

Delete row if table exists SQL

I have a script that drops a load of tables using DROP TABLE IF EXISTS, this works.
There is also a delete in this script to DELETE a row from another table that I do not manage. This table may or may not exist.Is there any to check the table exists before attempting to delete a row?
this needs to work for MYSQL and SQLServer
thanks
Alex
To check in SQL SERVER,
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
To check in mysql:
You simply count:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
This one deletes the row and does not complain if it can't.
DELETE IGNORE FROM table WHERE id=1
source here.
For SQL Server: You could use:
IF OBJECT_ID('tablename','U') IS NOT NULL
I dont think you'll find a common syntax between SQL server and my SQL. I mean, you can check if the table exsits on SQL Server using something like:
if exists(select * from sys.objects where name like 'table_name')
but mySql would have its own catalog.
Unless you write a script like:
if (sql_server) then
if exists(select * from sys.objects where name like 'table_name')
else --mySQl
--execute the mysql script
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TABLE_NAME]') AND type in (N'U'))
It seems to me right the first item in the "Related" column on the right side answers your question.... Check if table exists in SQL Server
For MySQL
show tables like "test1";
For SQL Server
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'testSchema' AND TABLE_NAME = 'test1'
A question you want to ask yourself (in terms of database design): Why are you trying to delete rows from a table you are not sure exists? If it doesn't, but you expect it does, wouldn't you rather create the table than not delete it?
Anyway, Chris Gesslers answer does exactly what you are asking in SQL Server, but there is some smell here.
The construct in MySQL you can use is
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename'
and check for results
you can use bellow code:
DECLARE #TABLENAME VARCHAR(20)='TableName';
IF (OBJECT_ID(#TABLENAME) IS NOT NULL )
BEGIN
execute(N'TRUNCATE TABLE ' + #TABLENAME + '' );
END
ELSE
BEGIN
PRINT 'Table NOT Exists'
END

Check if a table exist in where

This query generates an error because table2 doesn't exist:
Select * FROM table WHERE table2.id IS NOT NULL
Is there anything like this for check the table2 before apply the check on the id?
Select * FROM table WHERE (EXIST(table2) AND table2.id IS NOT NULL) or not EXIST(table2)
You need to query this system table:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'yourdatabasename'
AND table_name = 'table2';
If a row is returned, then your table exists.
I do not believe there is any command or function in standard SQL to do this. You could query the data dictionary to check if the table exists before issuing your SQL query as follows:
SELECT table_name FROM INFORMATION_SCHEMA.tables WHERE table_name = 'xxx';
I do not think it could be done in a single SQL statement though.