Tuesday 24 November 2015

Bulk Copy program (BCP) in sql server

With the help of Bulk copy program utility we can copies the data from an instance of Microsoft SQL Server to file in a user-specified format or file in a user-specified format to SQL server vice versa.
We can also export the data in flat files according to select query using queryout,
Let’s learn step by step how we use BCP.
There are two way to use BCP
Ø  Using command line
Ø  Using sql server
Syntax of BCP
BCP [Datebasename].[dbo].[TableName] OUT|IN|queryout [Destination where you want to store the flat file] [Arguments]
Example:-
BCP test.dbo.Emp OUT D:\Emp.txt -T -c

OUT- when we are exporting data from sql server to flat file
IN- when we are Importing the data from the file to sql server
Queryout: using in T-Sql query

Arguments
Description
 [-S server name]  
server name      
  [-T trusted connection] 
trusted connection        
  [-d database name]
database name
  [-P password]
Password          
  [-c character type]     
Character type  
  [-o out file]            
Out File
  [-U username]           
User Name
  [-x generate xml format file]
XML file

(A). Export data with trusted connection

BCP test.dbo.Emp OUT D:\Emp.txt -T -c
Open the command prompt
Before running the command see in D drive nothing is there.
  

Now I am executing BCP command in command prompt
  

Press enter
    

See here 12 rows are copies. Now we can see the files
   

It is created on the desired location.
We can achieve same thing using sql query.
 XP_cmdshell – It returning the sql row set.
Syntax is below.
exec Test..xp_cmdshell 'BCP test.dbo.Emp OUT D:\EmpDB.txt -T -c'
    

Now see in the D drive
   


(B) Export data in mix mode authentication with password

BCP test.dbo.Emp OUT D:\EmpMixMode.txt -c -Usa -SBagesh-PC –P******
 


   


(C) Import Data from file to sql server with trusted connection

We must have the same definition of the table in which we want to export it.
--Definition  of Emp table
CREATE TABLE [dbo].[Emp](
      [EmpID] [nchar](10) NOT NULL,
      [EmpName] [nchar](50) NULL,
      [EmpAdd] [nchar](100) NULL,
      [Salary] [int] NULL)
--Definition  of Emp table
CREATE TABLE [dbo].[Emp1](
      [EmpID] [nchar](10) NOT NULL,
      [EmpName] [nchar](50) NULL,
      [EmpAdd] [nchar](100) NULL,
      [Salary] [int] NULL )
Now we can Import data from file to sql server.
 

See the value in table
   

Using T-sql
exec test..xp_cmdshell 'BCP test.dbo.Emp1 In D:\Emp.txt -T -c'

    

    

(D) Export data from sql server to file based on select statement

Using cmd prompt
BCP "select EmpName,EmpAdd from test.dbo.Emp" queryout D:\Empselect.txt -T -c

 

Output file 
    

Using T-sql
exec test..xp_cmdshell 'BCP "select EmpName,EmpAdd from test.dbo.Emp" queryout D:\Empselect.txt -T -c'


 

Tuesday 17 November 2015

Deleting Duplicate Records from a table

It is one of the very important questions for sql server interview. How to delete the duplicate records from a table? Let’s learn how to achieve that. There is multiple ways to delete duplicate records.
Ø  Using Row Number function
Ø  Using sub query
Ø  Using self-join
Here I am using below table.
create table student
(
ID int Identity(1,1),
Fname varchar(50),
Lname varchar(50),
SSubject varchar(50),
Saddress varchar(100)
)

insert into student values('Bagesh','Kumar','Sql server','Pune')
insert into student values('Bagesh','Kumar','Sql server','Pune')
insert into student values('Rajesh','Kumar','Sql server','Chennai')
insert into student values('Rajesh','Kumar','Sql server','Chennai')
insert into student values('Mahesh','Kumar','Sql server','Pune')
insert into student values('Ganesh','Kumar','Sql server','Mumbai')
insert into student values('Anil','Kumar','Sql server','Mumbai')
insert into student values('Bagi','Kumar','Sql server','Pune')
insert into student values('Bagesh','Singh','Sql server','Pune')
insert into student values('Bagesh','Singh','Sql server','Pune')

In this table I have 10 records. Out of 10 records 3 records are duplicates.


Let’s start to learn how to delete duplicate records from table.

(A)   Using Row number function

select *,ROW_NUMBER() over
(PARTITION by Fname,Lname,ssubject,Saddress order by Fname,Lname,ssubject,Saddress)
 as RowNumber from student

 

Here I am using CTE to get the duplicate records.
with duplicate as
(
select *,ROW_NUMBER() over
(PARTITION by Fname,Lname,ssubject,Saddress
 order by Fname,Lname,ssubject,Saddress)
 as RowNumber from student
)
select * from duplicate where RowNumber>1

    
Here we get the duplicate records. Now we need to delete these records using below sql query.
with duplicate as
(
select *,ROW_NUMBER() over
(PARTITION by Fname,Lname,ssubject,Saddress
 order by Fname,Lname,ssubject,Saddress)
 as RowNumber from student
)
delete from duplicate where RowNumber>1
select * from student

  


(B)   Using sub query

Using below sql query we will get the duplicate records
select * from student where
ID NOT IN (select MAX(id) from student group by Fname,Lname,SSubject,saddress)

   


Now we need to delete these records using below sql query.
--using Sub query
DELETE from student
where ID NOT IN (select MAX(id) from student group by Fname,Lname,SSubject,saddress)



(C)   Using self-join

We can delete the duplicate records using self-join.
With the help of below sql query we will get the duplicate records.
--Using self join
select distinct a.Fname,a.Lname,a.SSubject,a.Saddress
from student a
JOIN student b
ON  a.Fname=b.Fname
AND a.Lname=b.Lname
AND a.SSubject=b.SSubject
AND a.Saddress=b.Saddress
and a.ID > b.ID


Now we need to delete these records.
--Using self join
DELETE from a
from student a
JOIN student b
ON  a.Fname=b.Fname
AND a.Lname=b.Lname
AND a.SSubject=b.SSubject
AND a.Saddress=b.Saddress
and a.ID > b.ID




Hope it will be help you. Thanks!!! 

Monday 16 November 2015

Find the nth highest or lowest salary of the employee

In most of the sql server interview the interviewers are asking how to find the nth highest or lowest salary of the employee. This is very common and important question in sql server interview. There is several ways to find the nth highest or lowest salary. Here I am trying to give the simple and easy answer with example.
Ø  Using sub query
Ø  Using CET or Temp table
o   Using Rank function
o   Using Row Number function
I am using table which name is EMP.


(A)   Find the highest and lowest salary of the employee.
Highest salary
--Highest salary
select MAX(Salary) as [Highest salary] from emp


Lowest salary
--Lowest salary
select Min(Salary) as [Lowest salary] from emp



(B)    2nd Highest and 2nd Lowest salary (using sub query)
2nd Highest salary
-- 2nd Highest salary
select max(Salary) as [Highest salary] from emp
where Salary < (select MAX(salary) from Emp)

select top 1 salary as [Highest salary]  from Emp
where Salary < (select MAX(salary) from Emp)
order by Salary desc

select max(Salary) as [Highest salary] from emp
where Salary NOT IN (select MAX(salary) from Emp)

select max(Salary) as [Highest salary] from emp
where Salary <> (select MAX(salary) from Emp)

         


                   

2nd lowest salary
select * from Emp order by Salary
     

-- 2nd Lowest salary
select MIN(Salary) as [Lowest salary] from emp
where Salary > (select MIN(salary) from Emp)

select top 1 salary as [Lowest salary]  from Emp
where Salary > (select MIN(salary) from Emp)
order by Salary

select MIN(Salary) as [Lowest salary] from emp
where Salary NOT IN (select MIN(salary) from Emp)

select MIN(Salary) as [Lowest salary] from emp
where Salary <> (select MIN(salary) from Emp)
     



(C)   Top N Highest or Lowest salary
3 top highest salary
select distinct top 3 Salary  from Emp
order by Salary desc

If you want to find the N top highest salary you can get it to replacing 3.
   


3 Lowest salaries
select distinct top 3 Salary  from Emp
order by Salary
 


(D)   3rd or 4th  Highest or Lowest salary
Highest salary
-- 3rd salary
select top 1 salary from emp where salary in
(select distinct top 3* Salary  from Emp order by Salary desc)
order by salary

-- 4rd salary
select top 1 salary from emp where salary in
(select distinct top 4* Salary  from Emp order by Salary desc)
order by salary

*you can replace the value as per your requirements.
     


 Lowest salary
-- 3rd lowest salary
select top 1 salary from emp where salary in
(select distinct top 3* Salary  from Emp order by Salary )
order by salary desc

-- 4rd lowest salary
select top 1 salary from emp where salary in
(select distinct top 4* Salary  from Emp order by Salary )
order by salary desc


*you can replace the value as per your requirements.
   


(E)    Using  Dense Rank Function
2nd highest salary
With Highest_Salary
AS
( select salary, DENSE_RANK() over (order by salary desc) as Salary_Rank from Emp
)
select Salary from Highest_Salary where Salary_Rank=2*

*you can get the n th highest salary.
   


Suppose if you want to find 3rd, 4th and 5th highest salary use below query
--3rd,4th and 5th highest salary
With Highest_Salary
AS
( select salary, DENSE_RANK() over (order by salary desc) as Salary_Rank from Emp
)
select Salary from Highest_Salary where Salary_Rank in (3,4,5)


Find the 2nd lowest salary
--2nd Lowest salary
With Lowest_Salary
AS
( select salary, DENSE_RANK() over (order by salary )
as Salary_Rank from Emp
)
select Salary from Lowest_Salary where Salary_Rank =2
     

Suppose if you want to find the 3rd, 4th and 5th lowest salary
--3rd, 4th and 5th Lowest salary
With Lowest_Salary
AS
( select salary, DENSE_RANK() over (order by salary )
as Salary_Rank from Emp
)
select Salary from Lowest_Salary where Salary_Rank in (3,4,5)

   

Suppose if you want to find the highest salary or lowest salary of the employee based on their location then we can achieve this using dense rank function with partition clause.
I am using below table
   


--Highest salary based on EmpAdd
With Highest_Salary
AS
( select EmpAdd,salary, DENSE_RANK() over (partition by EmpAdd order by salary desc )
as Salary_Rank from Emp
)
select EmpAdd,Salary from Highest_Salary where Salary_Rank = 1
group by EmpAdd,Salary ;
--2nd Highest salary based on EmpAdd
With Highest_Salary
AS
( select EmpAdd,salary, DENSE_RANK() over (partition by EmpAdd order by salary desc )
as Salary_Rank from Emp
)
select EmpAdd,Salary from Highest_Salary where Salary_Rank =2
group by EmpAdd,Salary ;

   


We can also find the lowest and 2nd lowest salary of the employee based by Employee address.
--Lowest salary based on Employee address
With Lowest_Salary
AS
( select EmpAdd,salary, DENSE_RANK() over (partition by EmpAdd order by salary )
as Salary_Rank from Emp
)
select EmpAdd,Salary from Lowest_Salary where Salary_Rank =1
group by EmpAdd,Salary ;
--2nd Lowest salary based on Employee address
With Lowest_Salary
AS
( select EmpAdd,salary, DENSE_RANK() over (partition by EmpAdd order by salary )
as Salary_Rank from Emp
)
select EmpAdd,Salary from Lowest_Salary where Salary_Rank =2
group by EmpAdd,Salary ;

 


(F)    Using Row Number function
Row_Number():- It will give the row number. With the help of we can get the highest or lowest salary. But the problem with this method is it will work on only distinct column value (means no duplicate salary value). If table has duplicate value it will be not work. If you want to perform with duplicate data then first we need to create a temp table and store distinct data in table and from distinct we can easily find out highest or lowest salary. See in the given example below.
--Find the nth Highest salary
create table #Highest_Salary(salary int)
insert into #Highest_Salary select distinct salary from Emp ;

Go
With Final_Table as
(
select salary,ROW_NUMBER() Over (Order by salary desc)as RowNumber from #Highest_Salary
)
select salary from Final_Table where RowNumber=2(*)

drop table #Highest_Salary

(*) you can put the number which you want to find the nth highest salary.
 

Nth lowest salary
--Find the nth lowest salary
create table #Lowest_Salary(salary int)
insert into #Lowest_Salary select distinct salary from Emp ;
Go
With Final_Table as
(
select salary,ROW_NUMBER() Over (Order by salary )as RowNumber from #Lowest_Salary
)
select salary from Final_Table where RowNumber=2

drop table #Lowest_Salary





Hope this article helps you. Thanks!!!

Popular Posts