Thursday, July 21, 2011

Group By VS Distinct in SQL


Group by VS Distinct

Group By : The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns. 
Distinct : The DISTINCT keyword can be used to return only distinct (different) values.

Orders table :
OrderId
PersonName
Price
Quantity
101
John
12
1
102
Sam
4
1
103
John
14
2
104
Brendon
12
1
106
Allen
2
11
107
Allen
3
11

Query 1: Select PersonName,Price from Orders group by PersonName,Price
Query 2:Select distinct PersonName,Price from Orders

Execution plan for both queries are same and return 5 records.

But the purpose of Group by is different it is used to group the records and apply aggregate function on it.

Query 3: Select PersonName,Sum(Price) as ‘Total’ from Orders group by PersonName

Query 3 returns only for records like below
PersonName
Total
Allen
5
Brendon
12
John
26
Sam
4

Distinct in SQL


Distinct : The DISTINCT keyword can be used to return only distinct (different) values.

Orders table :
OrderId
PersonName
Price
Quantity
101
John
12
1
102
Sam
4
1
103
John
14
2
104
Brendon
12
1
106
Allen
2
11
107
Allen
2
11


Query 1:Select distinct PersonName from Orders
Query 2:Select distinct PersonName,Price from Orders


Query 1 : Even though price is different we used ‘distinct’ only on PersonName so it return only 4 records.
Query2 : Return 4 rows because Allen is repeated twice with same price so it returns Allen only Once

Wednesday, July 20, 2011

SQL Group By


Group By in SQL:

The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns. 

Example :

Sales(OrderId,Customer,Price,Date)

1.Select Customer,sum(price) from Sales group by Customer

Sunday, July 17, 2011

What is SQL Server datatypes?

Datatype is an attribute which specifies what type of data you can store in an object.

Like any other RDBMS and programming language SQL Server uses datatype's to specify type of the data can be store in local variables,expressions,parameters and each column data.

Example:
Numeric types : int,tiny int,big int,float,decimal etc
Character types : Char,Varchar,Text etc


What is SQL Server?

SQL Server is Relational Database Management System ( RDBMS),which responds to SQL queries originated from the client machine.

RDBMS : Relational database groups data by using common characteristics.
SQL Queries : Declarative code used to Insert,update and delete data in a RDBMS database.