Get boolean result whether table exists or not - mysql

I don't want to commit a SQL request. I just want to known whether a specific table exists in data base or not, similar to the following pseudo statement:
IF EXISTS TABLE mytablename RETURN TRUE ELSE FALSE
How can I do this? I found several examples on how to modify a table if it doesn't exist.

This depends highly on the database, but this will work in many:
if exists (select 1 from information_schema.tables where table_name = 'mytablename')
(You might want to add additional conditions for the database/schema name.)
Although information_schema is supported in several databases, other databases might use all_tabs (Oracle) or some other table/view.
And, if you want a query that returns this value, use:
select max(case when table_name = 'mytablename' then 1 else 0 end) as TableExists
from information_schema.tables;

Try this Proc
CREATE PROCEDURE dbo.DoesTableExist (#TableName NVARCHAR(100))
AS
BEGIN
IF EXISTS (SELECT * FROM sys.tables WHERE Name = #TableName)
SELECT 1
ELSE
SELECT 0
END

Related

Using MYSQL, How do I query a table only if it exists already?

Im writing a migration and Im trying to query a table only if it exists in the db. In some envs it will exist and in others it wont which is why i want to check if it exists. The table of interest is called OLD_PASSWORD. I do the following.
SELECT ID, PASSWORD
FROM OLD_PASSWORD;
WHERE EXISTS
(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OLD_PASSWORD);
This fails '.dbcSQLSyntaxErrorException: Table "USER_OLD_PASSWORDS" not found;' which makes sense because it wont exist in some envs.
I also tried something like
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'OLD_PASSWORD'))
BEGIN
SELECT ID,
PASSWORD
FROM OLD_PASSWORD
END
but it's not compatible with mysql.
Best approach was to query INFORMATION_SCHEMA.TABLES from Java, and then do the query from OLD_PASSWORD if it returns something.
You forgot the ' sign at the end of query before the ).
Nonetheless, this is cartesian select. Use in instead. i.e
password in (select password ...) etc.

mysql insert into table if exists

In my project I have two code paths that interact with MySQL during first time setup. The first step is the database structure creation, in here, a user has the ability to pick and choose the features they want - and some tables may not end up being created in the database depending on what the user selects.
In the second part, I need to preload the tables that did get created with some basic data - how could I go about inserting rows into these tables, only if the table exists?
I know of IF NOT EXISTS but as far as I know, that only works with creating tables, I am trying to do something like this
INSERT INTO table_a ( `key`, `value` ) VALUES ( "", "" ) IF EXISTS table_a;
This is loaded through a file that contains a lot of entries, so letting it throw an error when the table does not exist is not an option.
IF (SELECT count(*)FROM information_schema.tables WHERE table_schema ='databasename'AND table_name ='tablename') > 0
THEN
INSERT statement
END IF
Use information schema to check existence if table
If you know that a particular table does exist with at least 1 record (or you can create a dummy table with just a single record) then you can do a conditional insert this way without a stored procedure.
INSERT INTO table_a (`key`, `value`)
SELECT "", "" FROM known_table
WHERE EXISTS (SELECT *
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'table_a')) LIMIT 1;

How to delete all tables that have 1-2 rows

Im having a database which is over 60k tables and i want to delete all the tables that have 1 or 2 rows.
You can use the below code in SQL Server 2012. It will delete all the tables which is having row_count less than 3.
USE [YourDB]
GO
DECLARE #Max int, #Count int,#Table_Name Varchar(20)
SET #Max =0
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
table_name sysname ,
row_count INT,
reserved_size VARCHAR(50),
data_size VARCHAR(50),
index_size VARCHAR(50),
unused_size VARCHAR(50)
)
IF OBJECT_ID('tempdb..#temp1') IS NOT NULL
DROP TABLE #temp1
CREATE TABLE #temp1
(
ID int IDENTITY(1,1),
table_name sysname ,
row_count INT
)
SET NOCOUNT ON
INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''
INSERT INTO #temp1
SELECT a.table_name,
a.row_count
FROM #temp a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count
HAVING a.row_count <3
SET #Count =(SELECT COUNT(*) FROM #temp1)
WHILE #Count > #Max
BEGIN
SET #Max = #Max +1
SET #Table_Name = (SELECT table_name FROM #temp1 WHERE ID = #Max)
EXEC('DROP TABLE ' +#Table_Name)
END
Use a MySQL-GUI, order by number of rows and drop all tables with 1-2 rows. it is as easy as deleting files in a windows folder. this
would take ~10 seconds + sort and drop time
or
Select table names of tables with 1-2 rows from information_schemas, load into an excel file and build your drop statements. takes around 2-5 minutes + drop time
or
Build a stored procedure that uses a Cursor to parse all the relevant table names into variables of your drop statement (like Hansa mentioned). this makes sense if you want to repeat your process from time to time. takes around 1-12 hours for beginners (depending on knowledge level) + drop time
Since logging in on SO probably took more time than solution 1 would,
i would recommend that solution.
In case you want to spend more time , the following query will show all table names for tables with 1-2 rows:
SELECT table_schema, table_name From information_schema.tables
WHERE table_schema='your_schema' # use your table_schema here
AND table_rows BETWEEN 1 and 2 ;
I would do it within some application side logic, using a programming language of your choice (which offers a mysql API).
Get all table names, described here, grouping them by table names
e.g. this could look something like:
SELECT COUNT(table_rows), table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{your_db}'
GROUP BY table_name;
(this is not tested, but to give you a basic idea...)
Execute a delete statement for the tables with rowcount 2 or lower. Should be an easy task as soon as you got the results in your programming language (btw SQL statement to delete them is "DROP TABLE")
Note: I think it should be also possible using a SQL cursor, but as I said I would prefer the above solution.
You can try this.
First take all the table names from the database.
After getting all the table names put them in a array and execute a foreach loop that checks the num of rows for each table, something like this
$tables = array();
foreach ($tables as $table_name){
$query = "select * from '$table_name'";
$result = mysqli_query($dbCon, $query);
$num_rows = mysql_num_rows($result);
if($num_rows < 3){
$delete = "drop table $table_name";
$res_del = mysqli_query($dbCon, $delete);
echo $table_name." Deleted";
}
}
You probably cant do this with 1 SQL Statement unless you are using stored procedures (see below).
You will need to select all tables in MySQL with a programming language (e.g. Java with JDBC) using the following statement:
select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_ROWS <= 2 AND TABLE_ROWS >= 1
Then you can use the results in the programming languge to issue drop Statements for each result record in a loop:
drop table <tablename>
For doing this with a stored procedure (i.e. without a programming language)
see the third comment on this page: MySQL Reference Drop Table.
Of course you will need to adapt this to your needs because this example does not select tables by their row numbers but by their names.

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

validate if table exists while selecting and inserting SQL Server

Hello I have a dynamic query like
SET #template = 'SELECT x AS X,... INTO temporalTable FROM' + #table_name
Then I execute it
EXEC (#template)
How do I validate if temporalTable
already exists, if so, drop it?
Just use OBJECT_ID
IF OBJECT_ID('temporalTable') IS NOT NULL
DROP TABLE temporalTable
No need to query any tables or do any aggregations.
Use information schema or sp_help function.
I would prefer information schema since it's SQL ANSI and you can port the code to other databases:
select count(1)
from information_schema.tables
where table_name = 'temporalTable';
sys.tables is a SQLServer specific option similar to inforamtion schema that you can also explore.
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='tablename')
SELECT 'tablename exists.'
ELSE
SELECT 'tablename does not exist.'