SQL: Check if table exists


1. By using the OBJECT_ID() function

If OBJECT_ID('my_table', 'U') is not null

BEGIN
    print 'my_table Table exists'
END

2. By using the INFORMATION_SCHEMA.TABLES

If exists (SELECT * FROM INFORMATION_SCHEMA.TABLES Where table_name = 'my_table')

BEGIN
    print 'my_table Table exists!'
END

3. By using sys.Objects Catalog view

If exists(Select * from sys.objects where  object_id = OBJECT_ID('my_table') and type = 'U')

BEGIN
    print 'my_table Table exists!'
END
Read: https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/system-information-schema-views-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.