Quantcast
Channel: Welcome To TechBrothersIT
Viewing all 1874 articles
Browse latest View live

How to generate drop Unique Constraint scripts in SQL Server Database - SQL Server / TSQL Tutorial Part 99

$
0
0

Scenario:

You are working as SQL Server developer, you need to generate scripts to drop all Unique Constraints in SQL Server Database.

Solution:

The below syntax can be used to drop Unique Constraint on table.

Alter table [SchemaName].[TableName]
Drop Constraint [ConstraintName]

The below query can be used to generate drop Unique Constraints in SQL Server database.

SELECT
Table_Schema,
Table_Name,
Constraint_Name,
'Alter table ['
+Table_Schema+'].['
+Table_Name+']'
+' Drop Constraint ['+Constraint_Name+']'
as DropUniqueConstraintQuery
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'UNIQUE'


Generate scripts to drop Unique Constraint in SQL Server Database

What are the different ways to insert data into SQL Server Table - SQL Server / TSQL Tutorial Part 100

$
0
0

Scenario:

As SQL Server Developer, you have to come with different ways to insert data into SQL Server Table.
Sometime you have to simply insert static records, sometime you have to insert data from another table to existing table. Let's check out different techniques to insert data into SQL Server table.

Solution:

Let's create the dbo.Customer Table first by using  below definition.

USE yourDatabaseName
Go
CreateTable dbo.Customer(
Id intidentity(1,1),
FName VARCHAR(50),
LName VARCHAR(50),
Age int,
DOB Date,
Salary Numeric(6,2))

1)  Use Multiple Inserts to insert data into table.


Insertinto dbo.Customer(FName,LName,Age,DOB,Salary)
Values('Aamir','Shahzad',36,'1980-01-01',5000.50)
GO
Insertinto dbo.Customer(FName,LName,Age,DOB,Salary)
Values ('Raza','M',33,'1983-03-03',4900.34)
GO
Insertinto dbo.Customer(FName,LName,Age,DOB,Salary)
Values ('John','Smith',26,'1990-04-05',5000.50)

2) Use single Insert with multiple Values

As in above example, we use multiple inserts.Each was inserting single record. In SQL Server we can use single Insert with multiple values as shown below.

Insertinto dbo.Customer(FName,LName,Age,DOB,Salary)
Values('Aamir','Shahzad',36,'1980-01-01',5000.50),
('Raza','M',33,'1983-03-03',4900.34),
('John','Smith',26,'1990-04-05',5000.50)

3)  Use Select with Insert to insert Records

We can use Insert with Select query to insert the result set returned by select query. 

Insertinto dbo.Customer(FName,LName,Age,DOB,Salary)
Select'Aamir'as FName,'Shahzad'as LName,36 as Age,'1980-01-01'as DOB,5000.50 as Salary
unionall
Select'Raza','M',33,'1983-03-03',4900.34
Unionall
Select'John','Smith',26,'1990-04-05',5000.50

4) Use Insert without provide Column Names

As you have seen in above examples, I have used column list with Insert, you don't have to use that if you know the order of columns and values you are using are also in order. I always use the column list in insert and select to make sure I am inserting correct data to table in correct columns.

--Insert without provide Column Names
Insertinto dbo.Customer
Select'Aamir'as FName,'Shahzad'as LName,36 as Age,'1980-01-01'as DOB,5000.50 as Salary
unionall
Select'Raza','M',33,'1983-03-03',4900.34
Unionall
Select'John','Smith',26,'1990-04-05',5000.50
Also we can use the insert without Column Names with Values option
Insertinto dbo.Customer
Values('Aamir','Shahzad',36,'1980-01-01',5000.50),
('Raza','M',33,'1983-03-03',4900.34),
('John','Smith',26,'1990-04-05',5000.50)

5) Insert data from Another Table to Destination table

As we have seen that the select query results can be inserted into table. In above examples we have used the static values with select, You can select the data from table,view and function etc. to insert into your table. Let's say if we want to insert data into dbo.Customer table from dbo.CustomerUS table. you can use below query.

--Insert into table from another table
Selectinto dbo.Customer(FName,LName,Age,DOB,Salary)
Select FName,LName,Age,DOB,Salary from dbo.CustomerUS


How to insert rows in SQL Server Table by Edit Table Rows GUI - SQL Server / TSQL Tutorial Part 101

$
0
0

Scenario:

You are working as SQL Server developer, you need to insert couple of records into dbo.Customer table but you don't want to use TSQL scripts. How would you insert data into table without using TSQL?

Solution:

Let's create the dbo.Customer table first by using below script.

USE yourDatabaseName
Go
CreateTable dbo.Customer(
Id intidentity(1,1),
FName VARCHAR(50),
LName VARCHAR(50),
Age int,
DOB Date,
Salary Numeric(6,2))


Once the table is created. Go to Database and then Tables tab. Right click on the dbo.Customer table as shown and choose Edit Top X rows according to your setting.

How to insert data to SQL Server Table by using Graphical user interface in SQL Server

Now start typing the values you want to insert. As Id is identity column, we don't have to insert any value.
How to insert data into SQL Server Table by using Graphical user interface in SSMS

Once done with inserting the data, just close the windows and records will be saved to table.


How to insert Excel or CSV data into Table by using Graphical User Interface in SQL Server - SQL Server / TSQL Tutorial Part 102

$
0
0

Scenario:

You are working as SQL Server developer, you got an excel file or CSV file that contains data for dbo.Customer table. How can you insert Excel or CSV data to table by using Graphical user Interface.

Solution:

Step 1: 
Let's create dbo.Customer table first by using below script.

USE yourDatabaseName
Go
CreateTable dbo.Customer(
Id intidentity(1,1),
FName VARCHAR(50),
LName VARCHAR(50),
Age int,
DOB Date,
Salary Numeric(6,2))

Step 2:
Go to database , then tables and then right click on dbo.Customer and choose Edit Top X rows as per your settings.

How to insert Excel or CSV data to Table by using Graphical User Interface

Below windows will open that will let you insert the records into table dbo.Customer. 

How to insert records into table from Excel by using Graphical interface in SSMS

Step 3: 
Open the Excel or CSV file and copy the data as shown below. Don't copy the header as we don't want to insert header values into table.
Insert Excel data into SQL Server Table by using Graphical User Interface

Step 4:
Noticed that the columns and copied data has the same order. Come to SSMS and then paste the data.
How to insert Excel or CSV data into SQL Server Table Manually by using SSMS

As Id is identity ( Auto generated) column and we are trying to insert values in that, the excel data start with FName. As Fname data can not be inserted into Id, it will be ignored and rest of the data will be shift as well. The Last Name values are inserted into FName as can be seen below.

How to insert data from Excel or CSV to Table in SSMS

To avoid this, we should only select the columns in which we want to insert the data. Also select in the order in which we have the data from Excel or CSV.

Once you run the query, you will see the selected columns only. Go ahead and past the data as Step 4.
Insert data from Excel or CVS To SQL Server Table without using Import Wizard in SQL Server

Once you hit paste, data will be written to table as shown below.
How to insert data from Excel or CSV to SQL Server Table by using Edit window in SSMS

If you have few records, you might be ok with speed. If you have millions of records, inserting records by using Edit window can take long time. you might want to use Import Wizard in cases where you have huge number of records to insert into SQL Server Table.


How to generate Insert Statements from Excel Data and Load into SQL Server Table - SQL Server / TSQL Tutorial Part 103

$
0
0

Scenario:

You are working as SQL Server Developer, you received data in an Excel file for dbo.Customer tables. You need to load this data into dbo.Customer table. How would you generate Insert Statement for given data in excel so you can load into DEV, QA,UAT and Production.

Solution:

There are multiple ways to achieve this requirement. You can use Import/Export Wizard first to load the data into Development environment and then generate insert script from table in SSMS.

If you don't want to load the data into table , you can use Excel formula's to generate Insert statement from data.

How to generate Insert Statements from Excel for SQL Server Table

First of all we need to know in which table we want to load the data. In our case it is dbo.Customer. Also the names of columns provided in Excel are exactly the same like our dbo.Customer table columns.
Go to any column and type this formula as shown below in first row. I typed in column G.

="insert into dbo.Customer ("&A1&","&B1&","&C1&","&D1&","&E1&") Values"

In Excel we start formula with = (equal to sign). For concatenation we use &. To add string we have to put double quotes around as we did for comma ",".

How to generate Insert Statements for SQL Server Table from Excel Data

Now first part of our Insert statement is ready. we have to generate the values part for our insert statement. Go to 2nd Row and use below formula.

="('"&A2&"','"&B2&"',"&C2&",'"&TEXT(D2,"dd/mm/yyyy")&"',"&E2&"),"

Drag it down to all the way till last record. All Insert values will be generate. Copy all the values from column G and paste into SSMS. There will be extra comma(,) at the end with last record. Remove that and run your insert statement to test if working as expected.

How to generate Insert Statements from Excel file for SQL Server table


Here are the generated Insert Statements, copied from G Column and pasted in SSMS.




How to backup or create new table from Existing SQL Server Table in SQL Server - SQL Server / TSQL Tutorial Part 105

$
0
0

Scenario:

You are working as SQL Server developer, you need to provide some update or delete scripts to update or delete data from a table.You want to take the backup of those records or if the table is small you might want to backup entire table before you run update or delete statements.

How would you backup entire table or only the records on which you need to run update or delete statements?

Solution:

SQL Server does not provide Table level backup. When we say that we want to take the backup of the table, we are talking about making a copy of existing table with records.

Let's say if we have dbo.Customer Table with few records and we want to create backup table dbo.Customber_Bkp_TodayDate, we can use below script

First create dbo.Customer table with sample records

USE yourDatabaseName
Go
CreateTable dbo.Customer(
Id intidentity(1,1),
FName VARCHAR(50),
LName VARCHAR(50),
Age int,
DOB Date,
Salary Numeric(6,2))

--Use the Insert Into with Values single Statement
Insertinto dbo.Customer
Values('Aamir','Shahzad',36,'1980-01-01',5000.50),
('Raza','M',33,'1983-03-03',4900.34),
('John','Smith',26,'1990-04-05',5000.50)

Now let's create dbo.Customber_Bkp_TodayDate backup table with all the records which are present in dbo.Customer.

Select * into dbo.Customber_Bkp_20160507from dbo.Customer


To create new table with records, you have to use Into NewTable from OldTable as shown above.

If we are only interested to copy records where FName='Aamir' our query will be like below.

Select * into dbo.Customber_Bkp_20160507_OnlyAamirfrom dbo.Customer where FName='Aamir'


Run above scripts and check the tables if created with required records.
How to backup records into new table from existing SQL Server Table in SQL Server



How to generate Insert Statements from Text Files for SQL Server Table in SQL Server - SQL Server / TSQL Tutorial Part 106

$
0
0

Scenario:

You are working as SQL Server developer, you get text files such as comma separate values, Tab delimited or pipe delimited files. It is one time task and you need to generate insert statements from these files so you can load the data into dbo.Customer table in DEV,QA,UAT and Production environments by using those scripts.

Solution:

I wrote a post , how to generate Insert statements from Excel file. Click here.  It means if we can open the text files with excel then we can use excel formulas to build insert statements.

If we have comma separate values file, you can directly open with excel and then use the steps shown in this post.

If you have tab delimited or pipe delimited file, first of all we need to open with excel and then use the formulas.

Step 1: 
Let's say that I have Tab delimited  Customer.txt file as shown below and want to open in excel.
How to generate Insert Statements from Tab delimited file for SQL Server Table

Step 2: 
Open Excel and then go to File and hit Open, Browse to customer.txt file
Generate Insert Statements from Text files for SQL Server Table 


Test Import Wizard will open, Choose Delimited and Click My Data has Headers if it does and  then Click Next
How to open Tab Delimited File in Excel to generate Insert statements for SQL Server Table

Choose the Delimiters, in our case it is Tab and hit Next.
How to Convert Tab Delimited File to Excel file and Generate Insert Statements for SQL Server Table

How to load Tab delimited file into Excel and Create Insert Statements for SQL Server Table


Once you will hit Finish, below excel sheet will be populated with flat file data.
How to generate Insert Statements from Excel File for SQL Server Table 

Now the data is in Excel file. we can use the excel formulas to generate insert statements as shown in this post.

How to generate Select query with all the columns from a table quickly in SQL Server - SQL Server / TSQL Tutorial Part 107

$
0
0

Scenario:

You are new to SQL Server and you want to select all the columns from SQL Server Table to see the data in SSMS.

Solution:

There are multiple ways to quickly select all the columns from a table and run the query to display data for them.

1) Use * 

You can use Select *From SchemaName.TableName

See the green highlighted *, once you use in your Select query , it is going to return all the column from table.

2) Use Select Top X Rows in SSMS
Go to Database in which your table exists, Right Click on the table and then choose Select top X row (x= depends upon your setting for SSMS) and it will generate select query with all the column from a table for you.

How to generate Select query with all the column for SQL Server Table
The below query will be generate with all the column from the table you have selected.
Select all columns quickly from a table for Select query in SQL Server

 3) Drag the Columns to Query Window
If you are not interested to use above two methods, you can open new query window , type Select and then drag the columns tab from the table you would like to use the columns. it will bring all the columns.
How to select all the columns from a table for Select query in SQL Server

Generate Select query with all the columns from a table quickly in SQL Server

Now you can write the rest of the part such as from SchemaName.TableName.

By knowing above methods, it really helps to prepare your queries quickly as sometime we have to select all columns and exclude couple of them. We can generate the query with all the  columns and then delete the columns which are not required from query.




How to restore Databases from backups files automatically in SQL Server - SQL Server DBA

$
0
0

Scenario:

Let's say that you are working as SQL Server DBA and you tons of backups files sitting in one of the folder, you need to restore all those backups files to newly created DEV , QA or UAT server. If you will start restoring one after one manually, it will take you forever. You are looking for some scripts those can restore these full backups files to newly created server.

You will be able to use this type of script to refresh databases on regular basis such as monthly or on demand from Production to lower environments.

I have tested this script on SQL Server 2016. You might get some error in case you are using old versions or latest versions as sometime microsoft change the number of columns returned by RESTORE FILELISTONLY.


Check the columns list and update the definition of temp tables according to your version, rest of the script will be same.

I did write same type of script before but I was considering the databases will have only mdf and ldf, Check here. The below script can handle database with NDF as well and overwrite existing DB if exists.




--Provide the folder path where backups are present
DECLARE @BackupFolder VARCHAR(128)
SET @BackupFolder='E:\Backup\'

--Provide the data and log files paths
--where you would like to restore databases

Declare @DataFilesPath VARCHAR(128)
Declare @LogFilesPath VARCHAR(128)

SET @DataFilesPath='D:\Data\'
SET @LogFilesPath='D:\Logs\'

--Get Backup files informaiton in temp table
IF OBJECT_ID('tempdb..#BackupFileList') ISNOTNULL
DROPTABLE #BackupFileList

--Drop temp table if exits
IF OBJECT_ID('tempdb..#RESTOREFILELISTONLY') ISNOTNULL
DROPTABLE #RESTOREFILELISTONLY

IF OBJECT_ID('tempdb..#RestoreHeaderOnly') ISNOTNULL
DROPTABLE #RestoreHeaderOnly

CREATETABLE #BackupFileList (
Id intidentity(1,1),
BackupFile nvarchar(255),
Depthsmallint,
FileFlag bit)


--Select * From #BackupFileList
--Store Backup information
CreateTable #RestoreHeaderOnly(
BackupName nvarchar(128) ,
BackupDescription nvarchar(255) ,
BackupType smallint ,
ExpirationDate datetime ,
Compressed bit ,
Positionsmallint ,
DeviceType tinyint ,
UserName nvarchar(128) ,
ServerName nvarchar(128) ,
DatabaseName nvarchar(128) ,
DatabaseVersion int ,
DatabaseCreationDate datetime ,
BackupSize numeric(20,0) ,
FirstLSN numeric(25,0) ,
LastLSN numeric(25,0) ,
CheckpointLSN numeric(25,0) ,
DatabaseBackupLSN numeric(25,0) ,
BackupStartDate datetime ,
BackupFinishDate datetime ,
SortOrder smallint ,
CodePage smallint ,
UnicodeLocaleId int ,
UnicodeComparisonStyle int ,
CompatibilityLevel tinyint ,
SoftwareVendorId int ,
SoftwareVersionMajor int ,
SoftwareVersionMinor int ,
SoftwareVersionBuild int ,
MachineName nvarchar(128) ,
Flags int ,
BindingID uniqueidentifier ,
RecoveryForkID uniqueidentifier ,
Collation nvarchar(128) ,
FamilyGUID uniqueidentifier ,
HasBulkLoggedData bit ,
IsSnapshot bit ,
IsReadOnly bit ,
IsSingleUser bit ,
HasBackupChecksums bit ,
IsDamaged bit ,
BeginsLogChain bit ,
HasIncompleteMetaData bit ,
IsForceOffline bit ,
IsCopyOnly bit ,
FirstRecoveryForkID uniqueidentifier ,
ForkPointLSN numeric(25,0) NULL ,
RecoveryModel nvarchar(60) ,
DifferentialBaseLSN numeric(25,0) NULL ,
DifferentialBaseGUID uniqueidentifier ,
BackupTypeDescription nvarchar(60) ,
BackupSetGUID uniqueidentifier NULL ,
CompressedBackupSize bigint ,--2008 has till here

containment tinyint notNULL )--2012 has till here

--KeyAlgorithm nvarchar(32),--Add below if using sql 2014,2016

--EncryptorThumbprint varbinary(20) ,

--EncryptorType nvarchar(32))

--Select * From #RESTOREFILELISTONLY

--Create Temp Table for DB files

--Select * From #RESTOREFILELISTONLY
--Create Temp Table for DB files
Createtable #RESTOREFILELISTONLY(
LogicalName NVARCHAR(128),
PhysicalName NVARCHAR(260),
Type CHAR(1),
FileGroupName NVARCHAR(128),
Sizenumeric(20,0),
MaxSize numeric(20,0),
Field bigint,
CreateLSN numeric(25,0),
DropLSN numeric(25,0),
UniqueId uniqueidentifier,
ReadonlyLSN numeric(25,0),
ReadWriteLSN numeric(25,0),
BackupSizeInBytes BigInt,
SourceBlockSize Int,
FileGroupId int,
LogGroupGUID uniqueidentifier,
DifferentialBaseLSN numeric(25,0),
DifferentialBaseGUID uniqueidentifier,
IsReadOnly bit,
IsPresent bit,
TDEThumprint varbinary(32)) --2012 is till here
--SnapshotURL nvarchar(360))

--Save backup files into temp table
INSERTINTO #BackupFileList (BackupFile,Depth,FileFlag)
EXEC xp_dirtree @BackupFolder, 10, 1

--Select * FROM #BackupFileList

--Use Cursor to loop throught backups files and restore
Declare @BackupFile VARCHAR(500)

DECLARE Cur CURSORFOR
SELECT BackupFile from #BackupFileList
where fileflag=1

OPEN Cur
FETCHNextFROM Cur INTO @BackupFile
WHILE@@FETCH_STATUS = 0
BEGIN

Truncatetable #RESTOREFILELISTONLY

--Insert data from RESTORE FILELISTONLY
insertinto #RESTOREFILELISTONLY
EXEC('RESTORE FILELISTONLY FROM DISK = '''+@BackupFolder+@BackupFile+'''')

insertinto #RestoreHeaderOnly
EXEC('RESTORE HEADERONLY FROM DISK = '''+@BackupFolder+@BackupFile+'''')
--Select * From #RESTOREFILELISTONLY
--Select * From #RestoreHeaderOnly

Declare @FilesNumber varchar(10)=Null
Declare @LogFileName NVARCHAR(128)=NULL
Declare @DataFileName NVARCHAr(128)=NULL
Declare @DBName NVARCHAR(128)=NULL
--We are considering we have a log and single data file
SET @LogFileName=(Select logicalName from #RESTOREFILELISTONLY where type='L')
SET @DataFileName=(Select logicalName from #RESTOREFILELISTONLY where type='D'and FileGroupName='PRIMARY')
SET @DBName=(Selecttop 1 DatabaseName from #RestoreHeaderOnly)
SET @FilesNumber=(Selectcount(*) From #RestoreHeaderOnly)


--Prepare Restore Statement
Declare @SQLRestore NVARCHAR(MAX)
SET @SQLRestore='RESTORE DATABASE "' +@DBName+'"
FROM DISK='
''+@BackupFolder+@BackupFile+'''
WITH File='
+@FilesNumber+',REPLACE,
MOVE '
''+@DataFileName+''' TO '''+@DataFilesPath+@DataFileName+'.mdf'',
MOVE '
''+@LogFileName+''' TO '''+@LogFilesPath+@LogFileName+'.ldf'''

--Execute SQL to Restore DBs
Print @SQLRestore
EXEC(@SQLRestore)

Truncatetable #RestoreHeaderOnly
FETCHNextFROM Cur INTO @BackupFile
END
CLOSE Cur
DEALLOCATE Cur

How to quickly write Select Query in SQL Server - SQL Server / TSQL Tutorial Part 108

$
0
0
You just started working with SQL Server and interested to learn how to select data from a table. Here are some tips for you

1) Select all the columns from a table/ View by using *
You can always use Select * from SchemaName.TableName to display data for all the columns from a table or view. When you use * in Select query, it return you all the columns from table or view.

Let's say that if I want to select all the columns from dbo.TotalSale table , I can use below query
How to select data for all the columns from SQL Server Table by using *


2) Drag the Columns Tab to new query
If you would like to get all the column names for your select query, you will open new query window. Then type Select and Drag the Columns Tab under the table to query window. All the columns will be displayed. If you would like to remove few, you can remove.

Select all the Columns quickly for a table for Select Query in SQL Server


After dragging the Columns Tab, you will see the column names are added to select.
How to generate Select Query with required Columns quickly in SSMS - SQL Server Tutorial


3)  Select Top X Row
Third and easy way to write your select query is, Right click on Table name and then choose Select Top X Rows ( X can be different as per your SSMS option settings). Once you choose it will generate the select query with all the column. You can remove the top x part from select and modify as required.
How to use Select Top X rows to generate select query with all the column names in SQL Server



How to use Sorting ( Order By) in Select Statement in SQL Server - SQL Server / TSQL Tutorial Part 109

$
0
0

Scenario:

You are working as SQL Server developer, you need to output sorted data. Which Key words you would like to use in T-SQL To output sorted data?

Solution:

The Order by Keyword can be used to sort the result set. We can sort the results by single or multiple columns.

Let's create dbo.Customer table with couple of test records and then use Order by keyword to sort them.

  Create table dbo.Customer(
id int, FName VARCHAR(100))
insert into dbo.Customer values(
1,'Aamir'),(2,'Raza')


1) When we only use Order by ColumnName
Let's say if you would like to sort the data by using Id column and in ascending order, you can use below query.

Select * From dbo.Customer
orderby Id


Select * From dbo.Customer
orderby Id ASC

Notice that in first query, I did not write ASC to order the data in ascending order. In second query I did use ASC key word. If you don't use any keyword after column names, SQL Server will order the data in ascending order.


How to use Order by to sort result set in SQL Server


2) How to sorting data in desending order
To order results in desending order, you have to add DESC keyword after column names. Let's say if we would like to order the data by using FName in desending oder, we will use below query.

Select * From dbo.Customer
orderby FName DESC
How to sort the output returned by select query by using Order by keyword


3)  Using Column Numbers instead of Column Names in Order by 
You can always use the Column numbers instead of column names in Order by. Let's say if we would like to order by FName,ID we can write our query by using names or column numbers as shown below.

Select * From dbo.Customer
orderby FName DESC,id DESC

Select * from dbo.Customer
Orderby 2 DESC,1 DESC

How to use Column numbers instead of using Column Names in Order By to sort results in SQL Server


How to use Where clause in Select Statement in SQL Server - SQL Server / TSQL Tutorial Part 109

$
0
0
In this post we will get familiar with Where Clause in TSQL.
Where clause is used in DML statements such as select, update, delete to filter the records according to criteria we used in where clause.

Let's create the table by using this script to create TotalSale Table so we can use for different queries.

We know that to see all the data from a table we can use

Select * from dbo.TotalSale

Select all records from a table by using Select * in SQL Server - SQL Server / TSQL Tutorial

With Where clause we can use different types of operations to filter the records such =, < >, >, >=, <, <=, IN, BETWEEN, LIKE, IS NULL or IS NOT NULL.

Let's try few of above operators with Select query for dbo.TotalSale table.

1) Get all the records from dbo.TotalSale table for Region equal to Asia.

Select * From dbo.TotalSale
where Region='Asia'


How to filter records in SQL Server Select query by using Where clause

2) Get all the records from dbo.TotalSale where ItemsSold is greater than 3.
Select * From dbo.TotalSale
where ItemsSold >3

How to get only records where value is greater than some value in SQL Server Select Query

3) Get all the records where State Name starts with N letter

Select * From dbo.TotalSale
whereStatelike'N%'

How to use like operator with Where clause to filter the records in SQL Server - SQL Server Tutorial

AND and OR keywords can be used to check multiple criteria.

4) If we want to get only the records where ItemsSold is greater than 2 and State name starts with N letter.

Select * From dbo.TotalSale
where itemssold>2
Andstatelike'N%'

How to use AND keyword in Where clause in Select Query in SQL Server - SQL Server / TSQL Tutorial

When you use AND, all the conditions should be true to return record.

4) Get all the records where ItemsSold is greater than 2 or state name start with N.

Select * From dbo.TotalSale
where itemssold>2
ORstatelike'N%'

How to use OR keyword in Select query - SQL Server / TSQL Tutorial

As you can see that when we used OR keyword, either of the condition has to be true to return the results.

How to filter Rows with Null Values in Select Statement in SQL Server - SQL Server / TSQL Tutorial Part 110

$
0
0

Scenario:

Let's say that you are working as SQL Server developer. You need to write two queries
  1) Return all the records from dbo.Customer table where Address column has Null values
  2) Return only the records from dbo.Customer table where Address column has the values other than Null.

Solution : 

We can use Where clause in our Select statement to return null records or not null records. Let's create dbo.Customer table first and insert couple of records.

--Create dbo.Customer table
Createtable dbo.Customer(
Id int,
Name VARCHAR(100),
Address VARCHAR(100))

--Insert records in dbo.Customer table
Insertinto dbo.Customer
Values(1,'Aamir','XyZ Address')
,(2,'Raza',Null)

--Return all records from dbo.Custoemr Table
Select * From dbo.Customer

Return all records from a table by using Select statement in SQL Server Database - SQL Server / TSQL Tutorial

1) Now if we want to get all the records where Address column has Null values. our query will be like below.

Select * From dbo.Customer
where Address is Null
How to get records with Null values in Select query in SQL Server Database - SQL Server / TSQL Tutorial

2) If we want to get the records where Address column has values beside Null, we will be using below query.

Select * From dbo.Customer
where Address isnot Null
Get all the records from table where column has the value beside Null values in SQL Server Database


How to Replace Null values with "Unknown" in Select Statement in SQL Server - SQL Server / TSQL Tutorial Part 111

$
0
0

Scenario:


You are working as SQL Server developer, you need to query dbo.Customer table and replace Null values in Name column to  "Unknown Name". Which SQL functions will you use to replace Null value with "Unknown Name"?


Solution:

You can use ISNULL or COALESCE functions to replace Null with value we like. Let's create dbo.Customer table and insert sample records by using below statements.


--Create dbo.Customer table
Createtable dbo.Customer(
Id int,
Name VARCHAR(10),
Address VARCHAR(100))

--Insert records in dbo.Customer table
Insertinto dbo.Customer
Values(1,'Aamir','XyZ Address')
,(2,'Raza',Null)
,(3,null,'abc address')
Let's use ISNULL or COALESCE functions to replace Null with "Unknown Name".

Select Id,ISNULL(Name,'Unknown Name') AS NameByISNull,
COALESCE(Name,'Unknown Name') NamebyCoalesce,
Address From dbo.Customer
How to replace Null with Values in SQL Server - TSQL Tutorial


As you can see that we used ISNULL and replaced the Null with "Unknown Name" but it returned "Unknown Na", it did not returned complete "Unknown Name". The reason, the data type of an ISNULL expression is the data type of the first input ( Name column) that is varchar(10), that means it will always return us 10 characters.

If you have situations like this, you better use COALESCE.The data type of a COALESCE expression is the data type of the input argument with the highest data type precedence. In our case "Unknow Name" is 12 characters and it chose to use that instead of Name column data type which is varchar(10).


How to get Distinct Records from a table in SQL Server - SQL Server / TSQL Tutorial 112

$
0
0

Scenario:

You are working as SQL Server developer, you need to get distinct (different) records from a table. Which statement will you use to get unique records from a table.


Solution:

Select distinct can be used to get different records from a table. The syntax for Select distinct is

Select distinct Column1,Column2, Column3.... from SchemaName.TableName.

Let's create sample dbo.Customer table and then insert test records by using below statements.

--Create dbo.Customer table
Createtable dbo.Customer(
Id int,
Name VARCHAR(10),
Address VARCHAR(100))

--Insert records in dbo.Customer table
Insertinto dbo.Customer
Values(1,'Aamir','XyZ Address')
,(2,'Raza',Null)
,(1,'Aamir','XyZ Address')
,(3,'John','XyZ Address')


As you can see that we have duplicate record 1,'Aamir','XyZ Address. Now if we would like to get distinct records from this table, we can use below query. If all columns are involved in your select, you can use * as shown below or type the names of columns.

Selectdistinct * From dbo.Customer

OR
Selectdistinct ID,Name,Address From dbo.Customer

How to get distinct records from SQL Server Table - SQL Server / TSQL Tutorial

As we can see that our query returned distinct records. We had duplicate records in table but it only display distinct as we have used Distinct in our Select statement.

You can always run distinct on single or more columns if you like. If I want to get only distinct Names from dbo.Customer table, I can use below query.

Selectdistinct Name From dbo.Customer
How to use Distinct in Select query in SQL Server to get distinct (difference) records




How to get Top / Bottom N Records from SQL Server Table in SQL Server - SQL Server / TSQL Tutorial Part 113

$
0
0

Scenario:


You are working as SQL Server or TSQL Developer, you need to get top/bottom x rows from a table. How would you do that?

Solution:

You can use TOP clause in your query to return top x records. Top clause is really helpful to take a quick look into some data points instead of returning all the records. 

The syntax for top is 

Select TOP Number | Percent column1,column2,column3... From SchemaName.TableName

Let's create our sample table dbo.Customer with sample data and try TOP.

--Create dbo.Customer table
Createtable dbo.Customer(
Id int,
Name VARCHAR(10),
Address VARCHAR(100))

--Insert records in dbo.Customer table
Insertinto dbo.Customer
Values(1,'Aamir','XyZ Address')
,(2,'Raza',Null)
,(3,'Rita','XyZ Address')
,(4,'John','XyZ Address')
,(5,'Lisa','XyZ Address')

1) Let's say if we would like to get Top 3 records from dbo.Customer with all columns, we can use below query.

Selecttop 3 * from dbo.Customer
How to get top x rows from a table in SQL Server - SQL Server / TSQL Tutorial

The select query with top returned us top 3 records successfully. You can also sort the records and then get top x records by using Top. 

2) Sort the records by Name and get top 3 records from dbo.Customer table.

Selecttop 3 * from dbo.Customer
Orderby Name
How to get Top N Rows from SQL Server Table with order by - SQL Server Tutorial
3) How to get Bottom n Rows from table
As we have seen that we can sort the records first and then get top x rows. If we have a column such as id (auto incremental), sequence number or createdOn (datetime) column, we can sort by desc and then get the top x rows, that will return us the bottom rows.
In our case we have Id, if we sort as desc and then get Top 3, we will be able to get bottom 3 records.


Selecttop 3 * from dbo.Customer
Orderby ID desc


How to get Bottom N rows from table by using Top and Order by in SQL Server


4) Use Percent with Top
Let's say if we would like to get 50% of records from dbo.Customer table, we can use percent with Top in our select query. As we have only 5 records in our dbo.Customer table, 50% will be 2.5, 2.5 rows can't be returned:) so SQL will round to 3 and we will get 3 row. 

Selecttop 50 Percent * from dbo.Customer
How to get Percent Rows from SQL Server Table - SQL Server / TSQL Tutorial
Again, Order by clause can be used with Percent the same way we did use with Top Number in example 1, 2 and 3.


How to use Top with Ties in SQL Server - SQL Server / TSQL Tutorial Part 114

$
0
0
In last post, we learnt how to return top / bottom x rows from sql server table. In this post, we will learn Top with ties.

According to BOL
 "WITH TIES
Used when you want to return two or more rows that tie for last place in the limited results set. Must be used with the ORDER BY clause. WITH TIES may cause more rows to be returned than the value specified in expression. For example, if expression is set to 5 but 2 additional rows match the values of the ORDER BY columns in row 5, the result set will contain 7 rows."

Let's create dbo.Customer table and find out the difference between Top and Top With Ties.

Createtable dbo.Customer(
Id
int,
Name
VARCHAR(10),
Address
VARCHAR(100))

--Insert records in dbo.Customer table
Insertinto dbo.Customer
Values(1,'Aamir','XyZ Address')
,(2,
'Raza',Null)
,(1,'Aamir','XyZ Address')
,(1,'John','XyZ Address')

,(5,
'Lisa','XyZ Address')

Noticed that we have duplicate records as high lighted above. Let's run the below queries, first with only Top and second with "With Ties" and observe the output.

Selecttop (2) * From dbo.Customer 
orderby ID



how to use Top x to get top records from table in SQL Server - TSQL Tutorial

Selecttop (2) WITH TIES * From dbo.Customer
orderby ID

How to use Top with Ties in SQL Server to get Top x rows - SQL Server / TSQL Tutorial

The first query returned only 2 records but second query with "With Ties" returned three records as the value for Id for third record was also 1 that matched with second row ( id column value=1). If you use "With Ties" with Top, the query will also give you all ties with the last row based on the ordering column.



Understand Column Alias in Select Query in SQL Server - SQL Server / TSQL Tutorial Part 115

$
0
0

Scenario:


You are working as SQL Server developer, you need to extract the data from dbo.Customer table and provide in an Excel Sheet. Your table has difference columns such as FName, LName but you want the output to come with FirstName and LastName. How would you do that?

Solution:

Alias is a great way to make your column names more readable. As in our question above, we want to display FName as FirstName and LName as LastName, Alias is the way to go. Let's create dbo.Customer table with columns and then use select query with alias to display Columns as we like.

Createtable dbo.Customer
(Id int,
FName VARCHAR(50),
LName VARCHAR(50))
GO
insertinto dbo.Customer
Values (
1,'Raza','M'),
(2,'Rita','John')

To create Alias you can use "AS" after column name or simply provide the alias right after column name. In below query, I have use "as" for FName but did not use for LName.

SelectFName as FirstName,
LName LastName
From dbo.Customer
How to use Alias in SQL Server to Rename Column for output - SQL Server / TSQL Tutorial
If you would like to have space between your Alias Column Name such as "First Name". You can use [ ] around the alias or double quotes e.g "First Name".

Select FName as [First Name],
LName as"Last Name"
From dbo.Customer
How to use Alias in SQL Server - SQL Server / TSQL Tutorial

How to use Case Statement for Conditional Formatting in Select Query - SQL Server / TSQL Tutorial Part 116

$
0
0

Scenario:

You are working as SQL Server developer, you need to query dbo.Customer table that has CountryShortName column with country abbreviations. You want to generate another columns with Country Full name by using CountryShortName column values. How would you do that?

Solution:

You can use Case expressions to generate this new column depending upon the value of CountryShortName. In our example we are using only single columns but you can use multiple columns and check for multiple conditions.

Let's create dbo.Customer table with some sample data and then we will write our Select statement with Case expression.

Createtable dbo.Customer
(Id int,
FName VARCHAR(50),
LName VARCHAR(50),
CountryShortName CHAR(2))
GO
insertinto dbo.Customer
Values (
1,'Raza','M','PK'),
(2,'Rita','John','US'),
(3,'Sukhi','Singh',Null)


1) You can use Column Name for which you want to check the values right after Case as shown below. Then write all the conditions on that column and finally use End as NewColumnName

Select
FName,
LName,
CountryShortName,
Case CountryShortName
When'Pk'Then'Pakistan'
When'US'Then'United States of America'
When'IN'Then'India'
Else'Not Provided'
EndAS CountryFullName
From dbo.Customer

How to use Case Statement in SQL Server - SQL Server / TSQL Tutorial

If you don't like to use Else part, you can remove that but in case when you will have value and it does not match with your conditions, It will return Null. In my case,If value does not match with my conditions, I would like to show as "Not Provided" by using Else part.

2) Don't use Column Name right after Case keyword
You can also write the case statement as shown below. In below example, we did not write Column Name right after Case. In this case we have to type column after every When. This way of writing is used when you want to check conditions for multiple columns or range of values.

Select
FName,
LName,
CountryShortName,
Case
When CountryShortName='Pk'Then'Pakistan'
When CountryShortName='US'Then'United States of America'
When CountryShortName='IN'Then'India'
Else'Not Provided'
EndAS CountryFullName

From dbo.Customer

How to use Case Statement for Conditional Formatting in SQL Query - SQL Server / TSQL Tutorial

How to get random rows from SQL Server Table - SQL Server / TSQL Tutorial Part 117

$
0
0

Scenario:

You are working as SQL Server developer. You are asked to provide sample random data from dbo.Customer table. You might asked to provide random 100 rows or some percent of total data from table. What query you will use to provide required output?

Solution:

In previous post, we learnt how to get top n rows from table. We can either provide row count or percent of records we want to get from a table by using TOP in our select query.

We can use the same Top clause but as we are asked to provide the random records, we need to sort them randomly first. We can use newid() function in order by clause to sort them randomly.

Let's create dbo.Customer table with some sample data.

Createtable dbo.Customer
(Id int,
FName VARCHAR(50),
LName VARCHAR(50),
CountryShortName CHAR(2))
GO
insertinto dbo.Customer
Values (
1,'Raza','M','PK'),
(2,'Rita','John','US'),
(3,'Sukhi','Singh',Null),
(4,'James','Smith','CA'),
(5,'Robert','Ladson','US'),
(6,'Alice','John','US')

1) use NewID ( ) in Order by to get random records
Let's say if we are interested to get 3 random records from dbo.Customer table, we can use below query.

Selecttop 3 * From dbo.Customer
orderby NEWID()

How to get Random records from SQL Server Table - SQL Server / TSQL Tutorial
you can also use percent if you like as shown below

Selecttop 30 percent * From dbo.Customer
orderby NEWID()

How to get random records from SQL Server table by using Top Percent with NewID() - SQL Server / TSQL Tutorial

2)  By using TABLESAMPLE SYSTEM 
As per Microsoft Books Online "TABLESAMPLE SYSTEM returns an approximate percentage of rows and generates a random value for each physical 8-KB page in the table. Based on the random value for a page and the percentage specified in the query, a page is either included in the sample or excluded. Each page that is included returns all rows in the sample result set".

From here you can understand that if you have small table with few pages , you might not want to use TableSample as it will include or exclude the entire page. With few records in table, you might want to use method 1 and for large tables you can use TableSample.

If I would run below query on my dbo.Customer table, Sometime I will get no records and when get the records, it will return all the records as they are placed on single page.

Select * From dbo.Customer tablesample (30 percent)
You can also use Rows you want with table sample as shown below. The rows returned can vary. you can limit them by using top n in select query.


Select * From dbo.Customer tablesample (2 rows)

When I executed above query on dbo.Customer table with total of 6 rows. It either returned me no rows or all six of them.

If you want to limit, you can use below query. Once again, I will suggest to use TableSample with big table where you have data on multiple data pages.

Selecttop 2 * From dbo.Customer tablesample (2 rows)



Viewing all 1874 articles
Browse latest View live