Tuesday, 31 December 2013

SQL SERVER : Find the Size of Database file and Log file

Data and log information are never mixed on the same file, and individual files are used only by one database.

The database files (Primary / Secondary) are used for storing data. For each database file there will be a Log file associated, this is the transaction log file used to store the user transactions.

Please find the below code and Screenshot for finding the size of database and log file:

Code :

SELECT DB_NAME (database_id) AS Database_Name, Name AS Logical_Name,
Physical_Name, (size*8)/1024 SizeMB
FROM sys.master_files
WHERE DB_NAME(database_id) = <databasename>


Scrennshot : 



Thursday, 26 December 2013

SQL SERVER : Find out Nth Largest value

It is very common question for interview, to find out the 2nd or Nth largest salary of employee.

Please find the below methods to find out the answer :

Method 1 :

SELECT TOP 1 [Column_Name] FROM [Table_Name] 
WHERE [Column_Name] NOT IN (SELECT DISTINCT TOP (n-1) [Column_Name] FROM  [Table_Name] ORDER BY [Column_Name] DESC )
ORDER BY [Coumn_Name] DESC

Method 2 :

SELECT * FROM (SELECT *, DENSE_RANK() OVER(ORDER BY [Column_Name] DESC ) AS Name FROM [Table_Name]) DQ
WHERE DQ.Name = n

*n = for nth largest

SQL SERVER : Difference Between UNIQUE KEY and PRIMARY KEY

PRIMARY Key and UNIQUE Key enforce the Uniqueness of the values on the column[columns] on which it is defined.


  •  By Default, UNIQUE Key creates a NON CLUSTERED INDEX while PRIMARY Key creates a   CLUSTERED  INDEX 
  • You can create multiple UNIQUE Keys on a table but you can have ONLY One PRIMARY Key on a table.
  • PRIMARY Key can be used in Foreign key relationship where as UNIQUE Key can not be used.
  • PRIMARY Keys can not have nulls but UNIQUE Key allows null value (But only one null value). 


Sunday, 3 November 2013

SQL SERVER : SP_WHO and SP_WHO2

There is very useful system stored procedure called sp_who on Sql server that lists users and processes running on the system. It comes handy when you want to see if any process is blocked. Both sp_who and sp_who2 provides information about the current processes / sessions / users in sql server instances. sp_who2 provides some more information as compare to the sp_who.

SP_WHO : SP_WHO provides information like logged in user id, session id, host name ,session status, blocking process details , database name etc.

SP_WHO2 : SP_WHO2 provides some more information - CPU time for each session, Disk IO, Last Batch , Program name.
















As such there is no difference in both SPs but the major one is that SP_WHO2 is not a documented it is an undocumented stored procedure.

Above two SPs can be used to monitor the server connections. Also these can be used to check the connections created for specific login/specific session /active session. You can filter the data returned to show only those processes that are not idle. if you specify a particular user like sp_who  [@login_name=]'Login' then you get processes for that user , otherwise all processes for all users will be listed .





Saturday, 2 November 2013

SQL SERVER : Difference between SQL Server Temporary table and Table Variable

Temporary Table :

Temporary tables are created in TEMP DB. A temporary table is easy to create and back up data. They act like regular tables in that you can query their data via SELECT queries and modify their data via UPDATE,INSERT and DELETE statements.If temporary table created inside a store procedure they are destroyed upon completion of the stored procedure.Temporary tables are real tables so you can do things like CREATE Indexes etc. The scope of any temporary table is the session in which it is created.You can create a temporary table using SELECT INTO, which can be quicker to write and may allow you to deal with changing datatypes over time, since you don't need to define your temporary table structure upfront.

There are two different temporary table types : Local and Global 
Local temporary tables are prefixed with a single # sign.Local temporary table tables are available for use by the current user connection that created them.Multiple connections can create the same named temporary table for local temporary tables without encountering conflicts.The internal representation of the local table is given a unique name,so as not to conflict with other temporary tables with the same name created by the other connections in the TEMP database. Local temporary tables are dropped by using the DROP statement or are automatically removed from memory when the user connection is closed.
Global temporary tables are prefixed with a double ## sign. Global temporary table have different scope from local temporary tables.Once connection creates a global temporary table, any user with proper permission to the current database he is in, can access the table.Unlike local temporary tables, you can not create simultaneous versions of a global temporary tables, as this will produce a naming conflict.Global temporary tables are removed from sql server if explicitly dropped by DROP Table. They are also automatically removed after the connection that created it disconnects and the global temporary is no longer referenced by the other connections. 

The Syntax to creating a temporary table is similar to creating a physical table in SQL Server with the exception of the a aforementioned pound sign(#):
CREATE TABLE #TmpTable
(
ID INT NOT NULL,
Name VARCHAR(20)
)

Table Variables:

A table variable is a data type that can be used within a Transact-SQL batch, stored procedure, or function.Table variables are good replacements of temporary tables when the data set is small. Statistics are not maintained for table variables like they are for regular or temporary tables, so using too large a table variable may cause query optimization issues.Unlike regular tables or temporary tables , table variables can't have indexes or FOREIGN KEY constraints added to them. Table variables do allow some constraints to be used in the definition (PRIMARY KEY , UNIQUE,CHECK ). Table variable performance suffers when the result set becomes too large or when column data cardinality is critical to the query optimization process.

The syntax to creating a table variables is similar to creating a table, only the DECLARE keyword is used and the table name is prefixed with an @ symbol :
DECLARE @TableName TABLE
ID INT NOT NULL,
Name VARCHAR(20)
)


The main difference between temporary table and table variable is that transaction logs are not recorded for the table variables. Hence they are out of scope of the transaction mechanism. Both table variables and temporary tables are stored in TEMP database. This means you should be aware of issues such as COLLATION problems if your database collation is different to your server collation.Temporary tables and table variable will by default inherit the collation of the server, causing problems if you want to compare data in them with data in your database. Depending on the situation as well as the version and service pack of SQL server that is installed, the performance metrics of table variable versus temporary tables can change. Unless the performance metrics change significantly using one or the other, your best option is to pick the one that makes the most sense in the current situation and stick with it. 

Thursday, 17 October 2013

SQL SERVER : Get an accurate count of the number of records in a table

The main basic method to find the record count of table are :

1. Select * from <table_name>

2. Select Count(*) from <table_name>

3. Select  rows, rowcnt from sysindexes where id = OBJECT_ID(<table_name>) AND indid < 2

Here are some other method to get the record count of SQL Server table :



Friday, 11 October 2013

SQL SERVER : RESET Identity Column in SQL SERVER Table

The Following Statement RESET the Identity Column in Required table :

DBCC CHECKIDENT (<table_name>, RESEED, <reseed_value>)

With the help of TRUNCATE statement you can reset the value of identity column but TRUNCATE will the reset value to Identity value which is defined at the time of table creation.

NOTE : IDENTITY Column does not  Stand for uniqueness unless you don't define identity column as part of Primary key.

Here is the Sample Code :






Sunday, 30 June 2013

How to Display/Remove Lines number In SQL Server -2005 Query Window of SSMS (Sql Server Management Studio)

By Default line numbers are NOT shown in Query pane in SSMS (2005) query window.

You need to follow below steps to Capture the line numbers in in Query plane. You can add / remove as per your requirement.

1. Select "Tool" from Menu bar, Now select "Options".

2. Then expand the "Text editor"  option from appearing window.

3. Expand the  "All language " option.

4. Finally Select the "General "  option and place a check in the box  "Line Number" in lower display screen.

Now when you open a new query window line numbers will appear. Reverse the steps for removing the line numbers.

Monday, 15 April 2013

SQL SERVER : Remove / Drop a column from an existing Sql server table

Remove a column from a Sql server table use the following code :

Syntax :

ALTER TABLE [table_name] 
DROP COLUMN [column_name] 

E.g. :

ALTER TABLE tbl_main
DROP COLUMN App_Id

Wednesday, 6 February 2013

SQL SERVER : Alter The Column Size In SQl Server table

Changing the Size of Column :

You can change the Length, Precision or Scale of a column by specifying a new size for the column datatype in the ALTER COLUMN Clause.

If Data Exist in the column , the new size can not be smaller than the maximum size of the data. Also the column can not be defined in an Index, Unless the column is a varchar, nvarchar or varbinary data type and  the Index is not the result of a  PRIMARY Key constraint.

Syntax :

ALTER table <table> alter column <coumn> nvarchar(biggernumber) [NOT] NULL

Example :

Use Val_Invoice_Data
GO
ALTER table [tblvaluation] alter column valuationtype varchar(MAX)


Using Polybase to load data into Azure Synapse Analytics (SQL DW) from Blob Storage

Azure Synapse Analytics supports many data loading methods. The fastest and most scalable way to load is through Polybase technology. Polyba...