862

The table name is Scores.

Is it correct to do the following?

IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
tmaster
  • 9,345
  • 6
  • 24
  • 27

15 Answers15

1566

Is it correct to do the following?

IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores

No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).

Instead, for a permanent table you can use

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
  DROP TABLE dbo.Scores; 

Or, for a temporary table you can use

IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
  DROP TABLE #TempTableName; 

SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • 162
    Fwiw -- The `'U'` for the second param apparently means "Only look for objects with this name that are tables". [One source](http://beyondrelational.com/modules/2/blogs/28/posts/10487/using-tsql-function-objectid.aspx). So `OBJECT_ID('TableName')` isn't *wrong*, but it's not insanely precise either, thus `'U'` in @Martin's excellent answer. – ruffin Nov 06 '13 at 18:00
  • 8
    Regarding the second param; [here is another source](http://msdn.microsoft.com/en-us/library/ms190324.aspx) , I used 'V' for a View. – Nate Anderson Aug 08 '14 at 18:44
  • 4
    HI can you explain me what this second parameter means in OBJECT_ID('tempdb.dbo.#T', 'U'), for example this 'U' ? – Zvonimir Tokic Feb 07 '16 at 09:56
  • 11
    @ZvonimirTokic it means "User defined Table". "IT" would be an internal, system defined, table. A full list is here https://msdn.microsoft.com/en-us/library/ms190324.aspx – Martin Smith Feb 07 '16 at 09:59
  • 2
    Argh, my "one source" disappeared. [Archived here](https://web.archive.org/web/20120321203046/http://beyondrelational.com/modules/2/blogs/28/posts/10487/using-tsql-function-objectid.aspx) & thanks, @TheRedPea for the second, more canonical, source. – ruffin Jul 24 '20 at 19:44
557

From SQL Server 2016 you can use

DROP TABLE IF EXISTS dbo.Scores

Reference: DROP IF EXISTS - new thing in SQL Server 2016

It will be in SQL Azure Database soon.

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
Jovan MSFT
  • 13,232
  • 4
  • 40
  • 55
  • This should be the accepted answer. Thanks for updating to current tech, @Jovan. – Rap Jun 12 '23 at 19:47
  • I rushed right out to use this when I found out it existed, but it still seems to wreak havoc on query plans, still true as of SQL Server 2019. When I switched from `IF OBJECT_ID() IS NOT NULL DROP TABLE #T_Foo` to `DROP TABLE IF EXISTS #T_Foo`, otherwise identical stored procedures changed from 10 msec to 25 seconds! So make sure you measure performance if you use this new syntax. – Sean Werkema Jun 13 '23 at 17:48
161

The ANSI SQL/cross-platform way is to use the INFORMATION_SCHEMA, which was specifically designed to query meta data about objects within SQL databases.

if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
    drop table dbo.Scores;

Most modern RDBMS servers provide, at least, basic INFORMATION_SCHEMA support, including: MySQL, Postgres, Oracle, IBM DB2, and Microsoft SQL Server 7.0 (and greater).

jveazey
  • 5,398
  • 1
  • 29
  • 44
  • 2
    Is the `if exists` ansi compliant? – Martin Smith May 25 '15 at 20:47
  • 10
    Be careful if you have more than one schema in the database. You might need to be specific about which [Scores] you are detecting and deleting. E.g. WHERE TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo' – Andrew Jens Aug 19 '15 at 05:09
  • 1
    @kiquenet Generally yes, but not when using the if exists - since this stops as soon as it returns one row. But I personally always do select 1 anyway. – Harag Oct 05 '15 at 11:00
73

Have seen so many that don't really work. when a temp table is created it must be deleted from the tempdb!

The only code that works is:

IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL     --Remove dbo here 
    DROP TABLE #tempdbname   -- Remoeve "tempdb.dbo"
Biondo86
  • 893
  • 6
  • 6
  • 3
    Thanks, changing `dbo` to `tempdb` made this work. I would also like to suggest adding the `'u'` as mentioned in the accepted answer's comments. Thus, the full IF statement would look like this: `IF OBJECT_ID('tempdb..#temp', 'U')` – whiteshooz Feb 01 '16 at 16:49
53

In SQL Server 2016 (13.x) and above

DROP TABLE IF EXISTS dbo.Scores

In earlier versions

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
DROP TABLE dbo.Scores; 

U is your table type

Tomáš Fejfar
  • 11,129
  • 8
  • 54
  • 82
Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37
30

Or:

if exists (select * from sys.objects where name = 'Scores' and type = 'u')
    drop table Scores
sventevit
  • 4,766
  • 10
  • 57
  • 89
  • 5
    You can use sys.tables since 2005 to simplify this: `if exists (select * from sys.tables where name = 'Scores') drop table Scores` – Michael Parker Sep 01 '15 at 12:47
28

I hope this helps:

begin try drop table #tempTable end try
begin catch end catch
hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
vlad
  • 301
  • 3
  • 2
22

I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:

CREATE FUNCTION [dbo].[Table_exists]
(
    @TableName VARCHAR(200)
)
    RETURNS BIT
AS
BEGIN
    If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
        RETURN 1;

    RETURN 0;
END

GO

To delete table User if it exists, call it like so:

IF [dbo].[Table_exists]('User') = 1 Drop table [User]
Palec
  • 12,743
  • 8
  • 69
  • 138
Mansfield
  • 14,445
  • 18
  • 76
  • 112
  • 1
    What about same name but different schema? The best way is here: https://stackoverflow.com/a/33497857/956364 – Protiguous May 16 '20 at 04:47
10

Simple is that:

IF OBJECT_ID(dbo.TableName, 'U') IS NOT NULL
DROP TABLE dbo.TableName

where dbo.TableName is your desired table and 'U' is type of your table.

Pang
  • 9,564
  • 146
  • 81
  • 122
Arsman Ahmad
  • 2,000
  • 1
  • 26
  • 34
7

SQL Server 2016 and above the best and simple one is DROP TABLE IF EXISTS [TABLE NAME]

Ex:

DROP TABLE IF EXISTS dbo.Scores

if suppose the above one is not working then you can use the below one

IF OBJECT_ID('dbo.Scores', 'u') IS NOT NULL 
DROP TABLE dbo.Scores;
RF1991
  • 2,037
  • 4
  • 8
  • 17
Ravi S
  • 79
  • 1
  • 1
6
IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
    DROP TABLE Scores
GO
Alfaiz Ahmed
  • 1,698
  • 1
  • 11
  • 17
4

I use:

if exists (select * 
           from sys.tables 
           where name = 'tableName' 
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end
3N1GM4
  • 3,372
  • 3
  • 19
  • 40
2

Make sure to use cascade constraint at the end to automatically drop all objects that depend on the table (such as views and projections).

drop table if exists tableName cascade;
hmofrad
  • 1,784
  • 2
  • 22
  • 28
1

If you use long codes and want to write less for temporary table create this procedure:

CREATE PROCEDURE MF_DROP (@TEMP AS VARCHAR(100)) AS
    EXEC('IF OBJECT_ID(''TEMPDB.DBO.' + @TEMP + ''', ''U'') IS NOT NULL DROP TABLE ' + @TEMP)

In execution:

EXEC MF_DROP #A
CREATE TABLE #A (I INT) ....
-3

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

Joseph Wambura
  • 2,732
  • 2
  • 21
  • 24
  • 11
    This question is related to `SQL`, not related to `Visual Studio`. Therefore, this answer is irrelevant to this question. – Adnan Sharif Jun 11 '19 at 05:26
  • 3
    Btw, the question is "How to drop a table if it exists?" with a tag "sql-server" without specifically lining it to SQL only, therefore this answer is not only technically correct but some (knowing only basics) might find this more convenient and helpful instead. – Umar T. Aug 09 '21 at 11:42