Table of Contents
- Create and Insert Query
- Simple SQL Select Query
- Aggregate and Scalar Function
- Date Function
- Other Select Function
- Where
- Group BY and Having Clause
- Sub Query
- Joins
- UNION and UNION ALL.
- Common Table Expressions(CTE) - With
- View
- Pivot
- Stored Procedure (SP)
- Functions
- SQL Server Coding Standards
- Few Worked Examples
1. Create and Insert Query
Before we start we will first create a table and insert some sample data into it so we can use these tables in our select class. I want to explain the table design with actual data since that will help the reader to understand this in detail.
In database design the important phase is to create a table with proper normalization with primary and foreign key relationships.
Now in this example we will assume we need to create a restaurant Order Management tables with relationships.
For this we need an Order Master, an Order Detail and an Item Master as the major tables. We will use these 3 tables in this article. First let's start by creating the tables. As I have said, we will use the 3 tables here in this article so we start by creating the Item Master as the first table. As the name suggests this table will be used to store the items.
Create Table
Item Master: Here we have created an ItemMaster with the necessary fields. As I already said, we need to make a plan about our project. List all the necessary tables we need to create for the project and describe and list all the fields to be created for each table. Here I used Item_Code as a primary key field that will be used in another table for the reference to this main table.
- CREATE TABLE [dbo].[ItemMasters](
- [Item_Code] [varchar](20) NOT NULL,
- [Item_Name] [varchar](100) NOT NULL,
- [Price] Int NOT NULL,
- [TAX1] Int NOT NULL,
- [Discount] Int NOT NULL,
- [Description] [varchar](200) NOT NULL,
- [IN_DATE] [datetime] NOT NULL,
- [IN_USR_ID] [varchar](20) NOT NULL,
- [UP_DATE] [datetime] NOT NULL,
- [UP_USR_ID] [varchar](20) NOT NULL,
- CONSTRAINT [PK_ItemMasters] PRIMARY KEY CLUSTERED
- (
- [Item_Code] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
- ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Item001','Coke',55,1,0,'Coke which need to be cold',GETDATE(),'SHANU'
- ,GETDATE(),'SHANU')
- INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
- ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Item002','Coffee',40,0,2,'Coffe Might be Hot or Cold user choice',GETDATE(),'SHANU'
- ,GETDATE(),'SHANU')
- INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
- ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Item003','Chiken Burger',125,2,5,'Spicy',GETDATE(),'SHANU'
- ,GETDATE(),'SHANU')
- INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
- ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Item004','Potato Fry',15,0,0,'No Comments',GETDATE(),'SHANU'
- ,GETDATE(),'SHANU')
Note: First please understand what Master and Detail means. If you don't understand what a Master and a Detail are then I will explain that first. Master means there is one main record and in the details we have all the details of the main record.
Say for example we have a restaurant and an order for one Coke, one Burger and one Potato Fries. Which means I have make an order from the waiter with 3 Items. So the Order_No for the example can be “Ord0001” and this Order_No will have the 3 items so first we create the Order Master.
- CREATE TABLE [dbo].[OrderMasters](
- [Order_No] [varchar](20) NOT NULL,
- [Table_ID] [varchar](20) NOT NULL,
- [Description] [varchar](200) NOT NULL,
- [IN_DATE] [datetime] NOT NULL,
- [IN_USR_ID] [varchar](20) NOT NULL,
- [UP_DATE] [datetime] NOT NULL,
- [UP_USR_ID] [varchar](20) NOT NULL,
- CONSTRAINT [PK_OrderMasters] PRIMARY KEY CLUSTERED
- (
- [Order_No] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- INSERT INTO [OrderMasters]
- ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Ord_001','T1','',GETDATE(),'SHANU' ,GETDATE(),'SHANU')
- INSERT INTO [OrderMasters]
- ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Ord_002','T2','',GETDATE(),'Mak' ,GETDATE(),'MAK')
- INSERT INTO [OrderMasters]
- ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('Ord_003','T3','',GETDATE(),'RAJ' ,GETDATE(),'RAJ')
- CREATE TABLE [dbo].[OrderDetails](
- [Order_Detail_No] [varchar](20) NOT NULL,
- [Order_No] [varchar](20) CONSTRAINT fk_OrderMasters FOREIGN KEY REFERENCES OrderMasters(Order_No),
- [Item_Code] [varchar](20) CONSTRAINT fk_ItemMasters FOREIGN KEY REFERENCES ItemMasters(Item_Code),
- [Notes] [varchar](200) NOT NULL,
- [QTY] INT NOT NULL,
- [IN_DATE] [datetime] NOT NULL,
- [IN_USR_ID] [varchar](20) NOT NULL,
- [UP_DATE] [datetime] NOT NULL,
- [UP_USR_ID] [varchar](20) NOT NULL,
- CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED
- (
- [Order_Detail_No] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- --Now let’s insert the 3 items for the above Order No 'Ord_001'.
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_001','Ord_001','Item001','Need very Cold',3
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_002','Ord_001','Item004','very Hot ',2
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_003','Ord_001','Item003','Very Spicy',4
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')

Here we can see the same ordre_No for 3 different details with different items. Refer to the Item Master for the Item Name details. We will see in detail the select query uses the following in this article. Now we insert another Order Master detail into the Detail tables.
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_004','Ord_002','Item002','Need very Hot',2
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_005','Ord_002','Item003','very Hot ',2
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
- INSERT INTO [OrderDetails]
- ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
- ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
- VALUES
- ('OR_Dt_006','Ord_003','Item003','Very Spicy',4
- ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
Can someone tell me what a Select Query in SQL is? A Select is the one basic and most important DML statement of SQL. So what is DML in SQL? DML stands for Data Manipulation Language. That means these statements are used to manipulate the data that already exists. As the name suggests the SELECT statement selects one or more columns with one or more data to display from our DB with our optional filters.
For example now I want to display my Name in the SQL Server. So as a result I will use the select statement here as an example.
- SELECT 'My Name Is SYED SHANU'
- -- With Column Name using 'AS'
- SELECT 'My Name Is SYED SHANU' as 'MY NAME'
- -- With more then the one Column
- SELECT 'My Name' as 'Column1', 'Is' as 'Column2', 'SYED SHANU' as 'Column3'

Select Statement from Table
- -- To Display all the columns from the table we use * operator in select Statement.
- Select * from ItemMasters
- -- If we need to select only few fields from a table we can use the Column Name in Select Statement.
- Select Item_Code
- ,Item_name as Item
- ,Price
- ,Description
- ,In_DATE
- FROM
- ItemMasters

3. Simple Aggregate and Scalar Function
Aggregate and Scalar Functions are builtin functions of SQL Server that we can be use in our select statements. For example a few Aggregate and Scalar functions are Count, Max, Sum, Upper, lower, Round and and so on. Here in comments I have explained each of its uses.
We can use our tblItemMaster with all these builtin functions.
- select * from ItemMasters
- -- Aggregate
- -- COUNT() -> returns the Total no of records from table , AVG() returns the Average Value from Colum,MAX() Returns MaX Value from Column
- -- ,MIN() returns Min Value from Column,SUM() sum of total from Column
- Select Count(*) TotalRows,AVG(Price) AVGPrice
- ,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) PriceTotal
- FROM ItemMasters
- -- Scalar
- -- UCASE() -> Convert to Upper Case ,LCASE() -> Convert to Lower Case,
- -- SUBSTRING() ->Display selected char from column ->SUBSTRING(ColumnName,StartIndex,LenthofChartoDisplay)
- --,LEN() -> lenth of column date,
- -- ROUND() -> Which will round the value
- SELECT UPPER(Item_NAME) Uppers,LOWER(Item_NAME) Lowers,
- SUBSTRING(Item_NAME,2,3) MidValue,LEN(Item_NAME) Lenths
- ,SUBSTRING(Item_NAME,2,LEN(Item_NAME)) MidValuewithLenFunction,
- ROUND(Price,0) as Rounded
- FROM ItemMasters

4. Date Function
In all our projects and tables we use the date column. The Date function plays a very important role in all our projects. So we should be very careful with date functions since sometimes these functions will be trickier. We need to select appropriate date functions and formats in our projects. Let's see a few examples of those here.
- -- GETDATE() -> to Display the Current Date and Time
- -- Format() -> used to display our date in our requested format
- Select GETDATE() CurrentDateTime, FORMAT(GETDATE(),'yyyy-MM-dd') AS DateFormats,
- FORMAT(GETDATE(),'HH-mm-ss')TimeFormats,
- CONVERT(VARCHAR(10),GETDATE(),10) Converts1,
- CONVERT(VARCHAR(24),GETDATE(),113),
- CONVERT(NVARCHAR, getdate(), 106) Converts2 ,-- here we used Convert Function
- REPLACE(convert(NVARCHAR, getdate(), 106), ' ', '/') Formats-- Here we used replace and --convert functions.
- --first we convert the date to nvarchar and then we replace the '' with '/'
- select * from Itemmasters
- Select ITEM_NAME,IN_DATE CurrentDateTime, FORMAT(IN_DATE,'yyyy-MM-dd') AS DateFormats,
- FORMAT(IN_DATE,'HH-mm-ss')TimeFormats,
- CONVERT(VARCHAR(10),IN_DATE,10) Converts1,
- CONVERT(VARCHAR(24),IN_DATE,113),
- convert(NVARCHAR, IN_DATE, 106) Converts2 ,-- here we used Convert Function
- REPLACE(convert(NVARCHAR,IN_DATE, 106), ' ', '/') Formats
- FROM Itemmasters
- DatePart: We use the datepart to display the selected Year, Month and Day.
- DateADD: We use dateadd to display or add or subrtract days from the selected date.
- DateDIff: We use dateDiff to calculate the difference between 2 dates.
- --Datepart DATEPART(dateparttype,yourDate)
- SELECT DATEPART(yyyy,getdate()) AS YEARs ,
- DATEPART(mm,getdate()) AS MONTHS,
- DATEPART(dd,getdate()) AS Days,
- DATEPART(week,getdate()) AS weeks,
- DATEPART(hour,getdate()) AS hours
- --Days Add to add or subdtract date from a selected date.
- SELECT GetDate()CurrentDate,DATEADD(day,12,getdate()) AS AddDays ,
- DATEADD(day,-4,getdate()) AS FourDaysBeforeDate
- -- DATEDIFF() -> to display the Days between 2 dates
- select DATEDIFF(year,'2003-08-05',getdate()) yearDifferance ,
- DATEDIFF(day,DATEADD(day,-24,getdate()),getdate()) daysDifferent,
- DATEDIFF(month,getdate(),DATEADD(Month,6,getdate())) MonthDifferance

5. Other Select Function
Top: To display the Top First or Last selected records first we see how to select the first or Top records and last to the Top records from the Select statement.
Order By: This is used in a SQL Select statement to display the records in ascending or descending order by the columns.
- <a name="5">
- --Top to Select Top first and last records using Select Statement.
- Select * FROM ItemMasters
- --> First Display top 2 Records
- Select TOP 2 Item_Code
- ,Item_name as Item
- ,Price
- ,Description
- ,In_DATE
- FROM ItemMasters
- --> to Display the Last to Records we need to use the Order By Clause
- -- order By to display Records in assending or desending order by the columns
- Select TOP 2 Item_Code
- ,Item_name as Item
- ,Price
- ,Description
- ,In_DATE
- FROM ItemMasters
- ORDER BY Item_Code DESC</a>

Distinct: The distinct keyword is used in select statements to avoid the duplicate records.
- <a name="5">
- Select * FROM ItemMasters
- --Distinct -> To avoid the Duplicate records we use the distinct in select statement
- -- for example in this table we can see here we have the duplicate record 'Chiken Burger'
- -- but with different Item_Code when i use the below select statement see what happen
- Select Item_name as Item
- ,Price
- ,Description
- ,IN_USR_ID
- FROM ItemMasters
- -- here we can see the Row No 3 and 5 have the duplicate record to avoid this we use the distinct Keyword in select statement.
- select Distinct Item_name as Item
- ,Price
- ,Description
- ,IN_USR_ID
- FROM ItemMasters</a>

6. Where Clause
The where clause is very important in SQL Select statements. Why we use a where clause and what is use of where clause. Where clause is nothing but a filter of the records using some condition.
Now for example we consider a table has 10,000 records. If we use a select query to display the records then the load time might be long to display all the data. In that case we can use a condition and display some specific data.
For example we can use the Where Clause to display the records for the past 1 week or 1 month.
We can consider our restaurant Order Detail table, for example we consider an Order Detail table to have 10,000 records but for sure for one Order_No there will not be more than 100 records in the Order Detail. Now let's see a few where clause uses.
- Select * from ItemMasters
- Select * from OrderDetails
- --Where -> To display the data with certain conditions
- -- Now below example which will display all the records which has Item_Name='Coke'
- select * FROM ItemMasters WHERE ITEM_NAME='COKE'
- -- If we want display all the records Iten_Name which Starts with 'C' then we use Like in where clause.
- SELECT * FROM ItemMasters WHERE ITEM_NAME Like 'C%'
- --> here we display the ItemMasters where the price will be greater then or equal to 40.
- --> to use more then one condition we can Use And or Or operator.
- --If we want to check the data between to date range then we can use Between Operator in Where Clause.
- select Item_name as Item
- ,Price
- ,Description
- ,IN_USR_ID
- FROM ItemMasters
- WHERE
- ITEM_NAME Like 'C%'
- AND
- price >=40
- --> here we display the OrderDetails where the Qty will be greater 3
- Select * FROM OrderDetails WHERE qty>3

Where In Clause
- -- In clause -> used to display the data which is in the condition
- select *
- FROM ItemMasters
- WHERE
- Item_name IN ('Coffee','Chiken Burger')
- -- In clause with Order By - Here we display the in descending order.
- select *
- FROM ItemMasters
- WHERE
- Item_name IN ('Coffee','Chiken Burger')
- ORDER BY Item_Code Desc

Where Between keyword
- -- between -> Now if we want to display the data between to date range then we use betweeen keyword
- select * FROM ItemMasters
- select * FROM ItemMasters
- WHERE
- In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'
- select * FROM ItemMasters
- WHERE
- ITEM_NAME Like 'C%'
- AND
- In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'

To display the records within a range we use the between keyword in the where clause.
7. Group BY Clause
A Group by Clause will display records as a result of a combined set or result of the same related records.
- --Group By -> To display the data with group result.Here we can see we display all the AQggregate result by Item Name
- Select ITEM_NAME,Count(*) TotalRows,AVG(Price) AVGPrice
- ,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) PriceTotal
- FROM
- ItemMasters
- GROUP BY ITEM_NAME
- -- Here this group by will combine all the same Order_No result and make the total or each order_NO
- Select Order_NO,Sum(QTy) as TotalQTY
- FROM OrderDetails
- where qty>=2
- GROUP BY Order_NO
- -- Here the Total will be created by order_No and Item_Code
- Select Order_NO,Item_Code,Sum(QTy) as TotalQTY
- FROM OrderDetails
- where qty>=2
- GROUP BY Order_NO,Item_Code
- Order By Order_NO Desc,Item_Code

Group By and Having Clause
The Having and Group By clauses don't support aggregate functions. To use aggregate functions we use a having clause in a Select statement.
- --Group By Clause -- here this will display all the Order_no
- Select Order_NO,Sum(QTy) as TotalQTY
- FROM OrderDetails
- GROUP BY Order_NO
- -- Having Clause-- This will avoid the the sum(qty) less then 4
- Select Order_NO,Sum(QTy) as TotalQTY
- FROM OrderDetails
- GROUP BY Order_NO
- HAVING Sum(QTy) >4













Udaya kumarPosted Apr 15, 2015, 1:17 AM
Nice article
sreenivasa kPosted Feb 24, 2015, 12:35 PM
nice article for startup
Rahul Kumar SaxenaPosted Feb 24, 2015, 7:20 AM
All the best Syed Shanu....
Syed ShanuPosted Feb 24, 2015, 7:04 AM
Thank you rahul.Now writing one article related to Angular Js and mvc ur article help me lot.
Rahul Kumar SaxenaPosted Feb 24, 2015, 6:50 AM
Good Collection...
Keyur PatelPosted Feb 24, 2015, 6:42 AM
Good effort. It would be really helpful. Nice!
Ramchand RepallePosted Feb 24, 2015, 6:19 AM
Great effort..!!. Nice to see mostly used examples at one place.
Hussain AhmedPosted Feb 24, 2015, 5:32 AM
Very Nice
Prasham SabadraPosted Feb 24, 2015, 4:56 AM
Thanks for sharing! Nice Article.
swapnilPosted Feb 24, 2015, 3:17 AM
good article