Here let's learn 50 most important SQL queries in SQL Server. SQL SQL Server is one of the most popular RDBMs used by enterprizes and used by millions of applications. To become a good software and data developer, understanding SQL is very important. In SQL Server, all data is accessed and updated using SQL queries. In this article, I will discuss top 50 general purpose SQL queries. I think each developer should have knowledge of these queries. These queries are not related to any specific topic of SQL. But knowledge of such queries can solve some complex tasks and may be used in many scenarios.
Query 1: How to Retrieve List of All Databases in SQL Server
The following SQL query retrieves a list of all databases on a SQL Server.
EXEC sp_helpdb

Query 2: How to Display Text of a Stored Procedure, Trigger, or View in SQL Server
The following SQL query gets the display text of a stored procedure, trigger, or view on SQL Server.
exec sp_helptext @objname = 'Object_Name'

Query 3: How to List All Stored Procedures in SQL Server
The following SQL query gets a list of all stored procedures in a SQL Server database.
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE o.xtype='P'

To retrieve the View use “V” instead of “P” and for functions use “FN.
Query 4: How to Get All Stored Procedures Related To a Table in SQL Server
The following SQL query gets all stored procedures related to a database table in SQL Server.
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%Table_Name%' AND o.xtype='P'

To retrieve the View use “V” instead of “P” and for functions use “FN.
Query 5: How to Rebuild All Indexes of a SQL Server Database
The following SQL query rebuilds all indexes of a SQL Server database.
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)"
GO
EXEC sp_updatestats
GO

Query 6: How to Retrieve All dependencies of Stored Procedures in SQL Server
This query returns all object names that are being using in stored procedurs like tables, user define functions, another stored procedures and so on.
;WITH stored_procedures AS (
SELECT
oo.name AS table_name,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d
INNER JOIN sysobjects o ON o.id=d.id
INNER JOIN sysobjects oo ON oo.id=d.depid
WHERE o.xtype = 'P' AND o.name LIKE '%SP_NAme%' )
SELECT Table_name FROM stored_procedures
WHERE row = 1

Query 7: How to Find Size of a Database Table in SQL Server
The following SQL query gets the size of a database table of a SQL Server database.
SELECT sob.name AS Table_Name,
SUM(sys.length) AS [Size_Table(Bytes)]
FROM sysobjects sob, syscolumns sys
WHERE sob.xtype='u' AND sys.id=sob.id
GROUP BY sob.name

Query 8: How to get all tables that don’t have identity columns in SQL Server
The following SQL query gets all tables of a SQL Server database that don't have identity columns.
SELECT
TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
where
Table_NAME NOT IN
(
SELECT DISTINCT c.TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS c
INNER
JOIN sys.identity_columns ic
on
(c.COLUMN_NAME=ic.NAME))
AND
TABLE_TYPE ='BASE TABLE'

Query 9: How to List Primary Keys and Foreign Keys in a SQL Server Database
The following SQL query gets a list of all primary keys and foreign keys on a SQL Server database.
SELECT
DISTINCT
Constraint_Name AS [Constraint],
Table_Schema AS [Schema],
Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
GO

Query 10: List of Primary Key and Foreign Key for a particular table
SELECT
DISTINCT
Constraint_Name AS [Constraint],
Table_Schema AS [Schema],
Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_NAME='Table_Name'
GO

Query 11: RESEED Identity of all tables
EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
DBCC CHECKIDENT (''?'', RESEED, 0)

Query 12: List of tables with number of records
CREATE TABLE #Tab
(
Table_Name [varchar](max),
Total_Records int
);
EXEC sp_MSForEachTable @command1=' Insert Into #Tab(Table_Name, Total_Records) SELECT ''?'', COUNT(*) FROM ?'
SELECT * FROM #Tab t ORDER BY t.Total_Records DESC;
DROP TABLE #Tab;

Query 13: Get the version name of SQL Server
SELECT @@VERSION AS Version_Name

Query 14: Get Current Language of SQL Server
SELECT @@LANGUAGE AS Current_Language;

Query 15: Disable all constraints of a table
ALTER TABLE Table_Name NOCHECK CONSTRAINT ALL

Query 16: Disable all constraints of all tables
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

Query 17: Get Current Language Id
SELECT @@LANGID AS 'Language ID'

Query 18: Get precision level used by decimal and numeric as current set in Server
SELECT @@MAX_PRECISION AS 'MAX_PRECISION'

Query 19: Return Server Name of SQL Server
SELECT @@SERVERNAME AS 'Server_Name'

Query 20: Get name of register key under which SQL Server is running
SELECT @@SERVICENAME AS 'Service_Name'

Query 21: Get Session Id of current user process
SELECT @@SPID AS 'Session_Id'

Query 22: Get Current Value of TEXTSIZE option
SELECT @@TEXTSIZE AS 'Text_Size'

Query 23: Retrieve Free Space of Hard Disk
EXEC master..xp_fixeddrives

Query 24: Disable a Particular Trigger
Syntax
ALTER TABLE Table_Name DISABLE TRIGGER Trigger_Name
Example
ALTER TABLE Employee DISABLE TRIGGER TR_Insert_Salary
Query 25: Enable a Particular Trigger
Syntax
ALTER TABLE Table_Name ENABLE TRIGGER Trigger_Name
Example
ALTER TABLE Employee ENABLE TRIGGER TR_Insert_Salary
Query 26: Disable All Trigger of a table
We can disable and enable all triggers of a table using previous query, but replacing the "ALL" instead of trigger name.
Syntax
ALTER TABLE Table_Name DISABLE TRIGGER ALL
Example
ALTER TABLE Demo DISABLE TRIGGER ALL
Query 27: Enable All Trigger of a table
ALTER TABLE Table_Name ENABLE TRIGGER ALL
Example
ALTER TABLE Demo ENABLE TRIGGER ALL
Query 28: Disable All Trigger for database
Using sp_msforeachtable system stored procedure we enable and disable all triggers for a database.
Syntax
Use Database_Name
Exec sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER all"
Example

Query 29: Enable All Trigger for database
Use Demo
Exec sp_msforeachtable "ALTER TABLE ? ENABLE TRIGGER all"

Query 30: List of Stored procedure modified in last N days
SELECT name,modify_date
FROM sys.objects
WHERE type='P'
AND DATEDIFF(D,modify_date,GETDATE())< N

Query 31: List of Stored procedure created in last N days
SELECT name,sys.objects.create_date
FROM sys.objects
WHERE type='P'
AND DATEDIFF(D,sys.objects.create_date,GETDATE())< N

Query 32: Recompile a stored procedure
EXEC sp_recompile'Procedure_Name';
GO

Query 33: Recompile all stored procedure on a table
EXEC sp_recompile N'Table_Name';
GO

Query 34: Get all columns of a specific data type
SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'Data_Type'

Query 35: Get all Nullable columns of a table
SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE c.is_nullable=0 AND OBJECT_NAME(c.OBJECT_ID)='Table_Name'

Query 36: Get All table that don’t have primary key
SELECT name AS Table_Name
FROM sys.tables
WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0
ORDER BY Table_Name;

Query 37: Get All table that don’t have foreign key
SELECT name AS Table_Name
FROM sys.tables
WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasForeignKey') = 0
ORDER BY Table_Name;

Query 38: Get All table that don’t have identity column
SELECT name AS Table_Name
FROM sys.tables
WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasIdentity') = 0
ORDER BY Table_Name;

Query 39: Get First Date of Current Month
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE()))+1,GETDATE()),105) First_Date_Current_Month;

Query 40: Get last date of previous month
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())),GETDATE()),105) Last_Date_Previous_Month;

Query 41: Get last date of current month
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())),105) Last_Date_Current_Month;

Query 42: Get first date of next month
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())+1),105) First_Date_Next_Month;

Query 43: Swap the values of two columns
UPDATE Table_Name SET Column1=Column2, Column2=Column1

Query 44: Remove all stored procedure from database
Declare @Drop_SP Nvarchar(MAX)
Declare My_Cursor Cursor For Select [name] From sys.objects where type = 'p'
Open My_Cursor
Fetch Next From My_Cursor Into @Drop_SP
While @@FETCH_STATUS= 0
Begin
Exec('DROP PROCEDURE ' + @Drop_SP)
Fetch Next From My_Cursor Into @Drop_SP
End
Close My_Cursor
Deallocate My_Cursor

Query 45: Remove all views from database
Declare @Drop_View Nvarchar(MAX)
Declare My_Cursor Cursor For Select [name] From sys.objects where type = 'v'
Open My_Cursor
Fetch Next From My_Cursor Into @Drop_View
While @@FETCH_STATUS = 0
Begin
Exec('DROP VIEW ' + @Drop_View)
Fetch Next From My_Cursor Into @Drop_View
End
Close My_Cursor
Deallocate My_Cursor

Query 46: Drop all tables
EXEC sys.sp_MSforeachtable @command1 = 'Drop Table ?'

Query 47: Get information of tables’ columns
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE INFORMATION_SCHEMA.COLUMNS.TABLE_NAME=’Table_Name’

Query 48: Get all columns contain any constraints
SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE

Query 49: Get all tables that contain a view
SELECT * FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE

Query 50: Get all columns of table that using in views
SELECT * FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE

Read more articles on SQL Queries:

boopathi sPosted Dec 30, 2020, 1:42 PM
Please change Query 37 c.isnullable = 1
Nilofers ShaikhPosted Oct 27, 2017, 3:16 AM
Nice information.Thanx for sharing.
Ravindar KumarPosted Sep 11, 2017, 2:00 AM
Awesome article very helpful
Ankur VermaPosted Jan 7, 2017, 1:23 PM
Thank you sir ji for sharing
jitendra mishraPosted Dec 2, 2016, 8:58 AM
Nice article.query 3 should be above to query 2.
Bhanu KorremulaPosted Nov 30, 2016, 10:43 AM
Awesome article it covers so many different scenarios
Manish KumarPosted Nov 3, 2016, 8:33 AM
Sp_spaceused tablename returns no. of rows in a table and size of table
Srikanth AgollaPosted Sep 29, 2016, 9:21 AM
Thanks for sharing with us
Pankaj Kumar ChoudharyPosted Sep 26, 2016, 7:04 AM
Thanks to all of you....
Pawan TiwariPosted Sep 26, 2016, 1:27 AM
Very helpful
Vishal JadavPosted Sep 12, 2016, 10:30 AM
Really useful queries.. Thank you.
Jisny AvPosted Sep 9, 2016, 6:48 AM
Very useful
Delpin Susai RajPosted Aug 29, 2016, 9:14 AM
Nice
Pankaj Kumar ChoudharyPosted Jul 26, 2016, 8:57 AM
This is my pleausre that you find something new in this article....
veera muthuPosted Jul 9, 2016, 1:09 PM
Wow great.... I learned new quries..Thank you..
Pankaj Kumar ChoudharyPosted Jul 5, 2016, 4:01 AM
Thanks to all of you....
SubashPosted Jul 4, 2016, 12:39 AM
.
SubashPosted Jul 4, 2016, 12:39 AM
Useful tips
kalu singh raoPosted Jul 2, 2016, 3:20 PM
Nice...
Gagan SharmaPosted Jun 30, 2016, 8:11 AM
Good one..
Raveendra Reddy ChitapanaPosted Jun 21, 2016, 4:05 AM
Very Useful Thanks.
Hari SuddapalliPosted May 23, 2016, 7:58 AM
Excellent
Munesh SharmaPosted May 23, 2016, 2:07 AM
good one
Sabyasachi MishraPosted May 20, 2016, 12:18 AM
Nice collection
Manju lata YadavPosted May 18, 2016, 2:24 AM
To get All Stored Procedure, Views etc. Relate To Table we can also use SELECT * FROM sys.objects WHERE OBJECT_DEFINITION(object_id) LIKE '%xtPWN%'
Pradeep SahooPosted May 16, 2016, 11:31 PM
Excellent ... it is a great article for SQL server developers.
Pankaj Kumar ChoudharyPosted May 16, 2016, 6:58 AM
Thanks to all of you............
Satish Kumar VadlavalliPosted May 16, 2016, 3:48 AM
Excellent, keep the good work up.
KaustubhPosted May 15, 2016, 7:36 AM
excellent stuff
Pankaj SharmaPosted May 14, 2016, 12:48 PM
great Article Pankaj. keep it up.......
Ranjan SenapatiPosted May 12, 2016, 7:34 AM
Good one...
Pankaj Kumar ChoudharyPosted May 12, 2016, 2:15 AM
Thanks Prerana Tiwari Mam.....
Pankaj Kumar ChoudharyPosted May 12, 2016, 2:15 AM
Thanks Yashwant Vishwakarma Sir.....
Pankaj Kumar ChoudharyPosted May 12, 2016, 2:15 AM
Thanks Michael Griffiths........
Prerana TiwariPosted May 11, 2016, 12:31 AM
very informative.....
Yashwant VishwakarmaPosted May 10, 2016, 8:33 AM
Superb Article !!!
Michael GriffithsPosted May 8, 2016, 7:05 AM
Very popular article
Pankaj Kumar ChoudharyPosted May 8, 2016, 4:05 AM
Thanks Rahul Pushpendu Bhaskar..........
Rahul Pushpendu BhaskarPosted May 7, 2016, 2:29 PM
very good article... Thank you
Mahesh ChandPosted May 6, 2016, 10:08 AM
Wow this article is one of the most popular article in recent weeks.
Atul KumarPosted May 5, 2016, 3:24 AM
Great article! Can you please let me know if I can mark this favorite from somewhere?
Pankaj Kumar ChoudharyPosted May 4, 2016, 11:06 AM
Thanks kalu singh rao.........
Pankaj Kumar ChoudharyPosted May 4, 2016, 11:06 AM
Thanks Navratna Pawale...........
kalu singh raoPosted May 4, 2016, 11:01 AM
Nice...
Navratna PawalePosted May 4, 2016, 8:03 AM
Nice share..
Pankaj Kumar ChoudharyPosted May 3, 2016, 12:24 PM
Thanks Sonu Choudhary Mam......................
Sonu ChaudharyPosted May 2, 2016, 7:01 AM
Thanks for sharing
Pankaj Kumar ChoudharyPosted Apr 29, 2016, 10:27 AM
Thanks Upendra Pratap Shahi .............
Pankaj Kumar ChoudharyPosted Apr 29, 2016, 10:26 AM
Thanks Thiruppathi R......
Upendra Pratap ShahiPosted Apr 29, 2016, 9:00 AM
nice one Pankaj Kumar Choudhary
Sourabh PanchalPosted Apr 29, 2016, 3:43 AM
Thanks Pankaj for this..
Thiruppathi RPosted Apr 29, 2016, 1:41 AM
much usefull job..
Pankaj Kumar ChoudharyPosted Apr 28, 2016, 9:45 AM
Thanks Venu Algam............
Pankaj Kumar ChoudharyPosted Apr 28, 2016, 9:45 AM
Thanks Anoop Kumar Sharma...........
Pankaj Kumar ChoudharyPosted Apr 28, 2016, 9:45 AM
Thanks Amatya Gupta............
Venu AlgamPosted Apr 28, 2016, 9:15 AM
Thanks Pankaj
Anoop Kumar SharmaPosted Apr 27, 2016, 1:50 PM
Bookmarked this Article. Thanks, Pankaj Kumar Choudhary for sharing..!! :)
Amatya AgyeyPosted Apr 27, 2016, 7:22 AM
Nice 1 bro.. Keep sharing this kind of important and Useful queries
Pankaj Kumar ChoudharyPosted Apr 27, 2016, 12:14 AM
Thanks Aqib Shehzad ... Thanks for your suggestion i will try to write a book on these queries...........
Pankaj Kumar ChoudharyPosted Apr 27, 2016, 12:13 AM
Thanks Faizal Hussain........
Muhammad Aqib ShehzadPosted Apr 26, 2016, 12:55 PM
Kindly create a book for these useful queries and available in download section.
Faizal HussainPosted Apr 26, 2016, 12:33 PM
Good One...Thanks for sharing...
Pankaj Kumar ChoudharyPosted Apr 26, 2016, 9:36 AM
Thanks Gowtham Rajamanickam.............
Gowtham RajamanickamPosted Apr 26, 2016, 3:03 AM
easy to search everything here
Gowtham RajamanickamPosted Apr 26, 2016, 3:02 AM
very good
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 7:46 PM
Thanks Debendra Dash Sir..........
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 7:46 PM
Thanks sreenivasa k...........
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 7:46 PM
Thanks Ramchand Repalle Sir.......
Debendra DashPosted Apr 25, 2016, 2:18 PM
nice one pankaj..........
sreenivasa kPosted Apr 25, 2016, 2:05 PM
really excellent work
Ramchand RepallePosted Apr 25, 2016, 8:45 AM
Good one, Thanks for sharing..
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 6:00 AM
Thanks Anu Vivin sir.......
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 6:00 AM
Thanks Hari Shanker Sir...........
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 5:59 AM
Thanks Nitin Tyagi............
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 5:59 AM
Thanks Kumaresh Rajalingam............
Anu VPosted Apr 25, 2016, 3:40 AM
Nice
NitinPosted Apr 25, 2016, 1:57 AM
good one
Hari ShankerPosted Apr 25, 2016, 12:37 AM
Thanks Pankaj
Kumaresh RajalingamPosted Apr 24, 2016, 9:36 PM
Nice share
Pankaj Kumar ChoudharyPosted Apr 24, 2016, 11:48 AM
Thanks Vignesh Mani sir......
Pankaj Kumar ChoudharyPosted Apr 24, 2016, 11:48 AM
Thanks Dinesh Sir.............
Vignesh ManiPosted Apr 24, 2016, 10:21 AM
Nice
Dinesh BeniwalPosted Apr 24, 2016, 1:20 AM
22+K Views in less than one day, Congrats Pankaj.
Pankaj Kumar ChoudharyPosted Apr 24, 2016, 12:44 AM
Thanks Rakesh sir.......
Pankaj Kumar ChoudharyPosted Apr 24, 2016, 12:44 AM
Thanks Pradeep Sahoo sir..........
Pankaj Kumar ChoudharyPosted Apr 24, 2016, 12:43 AM
Thanks Dominique Ceja Sir .....
RakeshPosted Apr 24, 2016, 12:23 AM
Good share
Pradeep SahooPosted Apr 24, 2016, 12:15 AM
Helpful queries .Thanks for sharing
Dominique CejaPosted Apr 23, 2016, 11:33 PM
Great article. Thanks
Pankaj Kumar ChoudharyPosted Apr 23, 2016, 8:03 PM
Thanks to all of you,,,,,,,,,,,,
Michael GriffithsPosted Apr 23, 2016, 4:40 PM
Nice
Manas MohapatraPosted Apr 23, 2016, 3:22 PM
Good effort. It is very much helpful database developer..
Humayun Kabir MamunPosted Apr 23, 2016, 2:45 PM
Very helpful...
Kuppurasu NagarajPosted Apr 23, 2016, 1:33 PM
Nice Sharing..
Ano MepaniPosted Apr 23, 2016, 8:49 AM
Very nice article for understand basic of sql server.Thanks for sharing
Raja TPosted Apr 23, 2016, 7:49 AM
Nice, Thanks for sharing...
vipin dhingraPosted Apr 23, 2016, 7:40 AM
Nice
Vivek KumarPosted Apr 23, 2016, 6:58 AM
Nice one Pankaj Kumar Choudhary. keep it up.
Shaili DashoraPosted Apr 23, 2016, 6:57 AM
Nice article...
Debasis SahaPosted Apr 23, 2016, 6:25 AM
Nice One..
Muhammad Aqib ShehzadPosted Apr 23, 2016, 5:13 AM
Excellent piece of required compiled list of Queries. thanks for sharing