sql server basic

15
Deccansoft Software Services SQL Server Introduction 1 Relational Database Models Relational Model: The data is stored in two-dimensional tables (rows and columns). The data is manipulated based on the relational theory of mathematics. Exploring RDBMS With E-R Modeling RDBMS: RDBMS is a database management system based on relational model defined by E.F.Codd. A relational database allows the definition of data structures, storage and retrieval operations and integrity constraints. In such a database the data and relations between them are organized in tables. A table is a collection of records and each record in a table contains the same fields. The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL. E-R Modeling: E-R Modeling is a technique of data modeling that is useful in developing a conceptual design for a database. The whole purpose of ER modeling is to create an accurate reflection of the real world in a database. Entity: It is a real world object which is distinguishable from any other object. Entity is a person, place, object, event or concept in the user environment about which the organization wishes to maintain Data. Entity can be concrete or abstract Concrete entity Example : Specific person, Company, Course Abstract entity Example: Specific Order, Holiday Attributes: A named property or characteristic of an entity that is of interest to an organization Example: People have names and addresses. Entity Type: It is collection of same types of entities having same attributes. Example: people, company, course, order, transaction. Entity set Collection of Entities which contain entities of particular entity type It is referred using the same name as entity type. Each Entity set has a key. Relationship: It is association between entities. representation of the fact that certain entities are related to each other Example: Customer buys a product, Artist performs a song, Mapping Cardinalities: Relationship is expressed in terms of cardinality. Cardinality gives number of entities in one entity set, to which another entity in another entity set can be associated via a relationship. For a binary relationship set the mapping cardinality must be one of the following types: One to One, One to Many, Many to One and Many to Many One to One One to Many (Department Address) (Department Employee) Many to One Many to Many (Order Customer) (Faculty Course)

Upload: anul-jain

Post on 21-Jul-2016

45 views

Category:

Documents


9 download

DESCRIPTION

tutorial for sql server basice ny deccansoft

TRANSCRIPT

Page 1: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

1

Relational Database Models

Relational Model:

The data is stored in two-dimensional tables (rows and columns).

The data is manipulated based on the relational theory of mathematics.

Exploring RDBMS With E-R Modeling

RDBMS: RDBMS is a database management system based on relational model defined by E.F.Codd. A relational database allows the definition of data structures, storage and retrieval operations and

integrity constraints. In such a database the data and relations between them are organized in tables. A table is a collection of

records and each record in a table contains the same fields. The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL.

E-R Modeling: E-R Modeling is a technique of data modeling that is useful in developing a conceptual design for a database. The whole purpose of ER modeling is to create an accurate reflection of the real world in a database. Entity:

It is a real world object which is distinguishable from any other object. Entity is a person, place, object, event or concept in the user environment about which the organization

wishes to maintain Data. Entity can be concrete or abstract Concrete entity Example : Specific person, Company, Course Abstract entity Example: Specific Order, Holiday

Attributes: A named property or characteristic of an entity that is of interest to an organization Example: People have names and addresses.

Entity Type: It is collection of same types of entities having same attributes. Example: people, company, course, order, transaction.

Entity set Collection of Entities which contain entities of particular entity type It is referred using the same name as entity type. Each Entity set has a key.

Relationship: It is association between entities. representation of the fact that certain entities are related to each other Example: Customer buys a product, Artist performs a song,

Mapping Cardinalities: Relationship is expressed in terms of cardinality. Cardinality gives number of entities in one entity set, to which another entity in another entity set can be

associated via a relationship. For a binary relationship set the mapping cardinality must be one of the following types: One to One, One to Many, Many to One and Many to Many

One to One One to Many (Department – Address) (Department – Employee)

Many to One Many to Many (Order – Customer) (Faculty – Course)

Page 2: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

2

What are Key attributes of Entity set?

Super Key: A super key of an entity set is a set of one or more attributes whose values uniquely identify each entity.

Candidate Key: A candidate key of an entity set is a minimal super key.

Primary Key: Primary key is one of the candidate keys which can identify the entity uniquely.

Example: Person (Name, Age, SSN, Phone Extension) This Entity set has many possible super keys. <SSN>, <Phone Extension, Name> and <SSN, Name>. Of those listed, only <SSN> is a candidate key, as the others contain information not necessary to uniquely identify records.

Symbols used in ER Diagram: It is a detailed, logical representation of the entities, associations and data elements for an organization or business.

Crow feet Notation

Creating Table from ER Diagram:

ID Name Salary

1001 John 10000

1002 Allen 15000

1003 Smith 18000

Employee Table:

ID Name Salary

1001 John 10000

1002 Allen 15000

1003 Smith 18000

ID Name Location

101 Sales Block A

102 IT Block B

103 Accounting Block C

Foreign Key: A field (or fields) on the many side of a one-to-many relationship between tables that relates to the primary key of the other table.

Page 3: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

3

Creating Foreign key: Employee Table:

ID Name Salary Department

1001 John 10000 101

1002 Allen 7000 102

1003 Smith 15000 103

Properties of Relational Tables:

Values Are Atomic

Each Row is Unique

Column Values Are of the Same Kind

The Sequence of Columns is Insignificant

The Sequence of Rows is Insignificant

Each Column Has a Unique Name

E-R Modeling Case Study

Requirement: Creating an E-R Model for training institute and translate it in relational schema. Step1: Analyze the requirement.

1. Training Institute has many Trainers and many courses. 2. Each trainer can take only one course. 3. Each Course can be taken by multiple trainers. 4. New batches start by particular course and by particular trainer. 5. A student can enroll for multiple batches. 6. Batch can contain multiple students.

Step 2: Identify the Entities 1. Trainer 2. Course 3. Student 4. Batch

Step3: Identify the Relationship 1. Course can be taken by multiple trainers and each trainer can take only one course

Relationship between Course and Trainer is One to Many 2. New batches start by particular course and by particular trainer.

Relationship between course and batch is One to Many Relationship between Trainer and Batch is One to Many

3. A student can enroll for multiple batches and Batch can contain multiple students. Relationship between Batch and student is Many to Many Step4: Identify the Key attributes and other relevant attributes of Entities

1. Trainer(TrainerId,Name,Qualification,Experience,DateOfJoin) 2. Course(CourseId,Name,Duration,Fees) 3. Batch(BatchId,BatchName,StartDate,Duration) 4. Student(StudentId,Name,PhoneNo,Email)

Page 4: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

4

5. Step5:Draw E-R Diagram

Step6: Translate E-R diagram in Relational Schema. Create tables with following columns:

1. Relationship between Course and Trainer is one to Many Course (PKCourseId, CourseName, Duration, Fees) Trainer (PKTrainerId, TrainerName, Qualification, Experience, DateOfJoin, FKCourseId)

2. Relationship between course and batch is One to Many and Relationship between Trainer and Batch is One to Many

Batch (PKBatchId, BatchName, StartDate, Duration, FKCourseId, FKTrainerId) 3. Relationship between Batch and student is Many to Many so one more table is needed.

Enrollment (FKStudentId, FKBatchId, DateofEnroll) Student (PKStudentId, StudentsName, PhoneNo, Email)

Page 5: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

5

NORMALIZATION

Normalization is step by step process of decomposing the data in two or more tables and establishing

relationship between them so that data redundancy is reduced.

Normalization is done through changing or transforming data into various Normal Forms

1NF :First Normal Form:

Each cell is single-valued

There are no duplicated rows in the table.

After applying 1NF

Values are atomic.

The two columns that together uniquely identify each row are order_id and item_id.

2NF:Second Normal Form

Meet all requirements of 1NF

No Partial dependencies on concatenated key After applying 2NF

Page 6: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

6

3NF:Third Normal Form

Meet all requirements of 2NF

Remove Transitive Dependencies After applying 3NF

E-R Model after Normalization

Page 7: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

7

INTRODUCTION TO SQL SERVER

SQL Server History:

Prior to version 7.0 the code base for MS SQL Server was sold by Sybase SQL Server to Microsoft, and was Microsoft's entry to the enterprise-level database market.

SQL Server Versions are as follows: o SQL Server 7.0 o SQL Server 8.0 (2000) o SQL Server 9.0(2005) o SQL Server 10.0(2008) o SQL Server 11.0(2012)

SQL Server Editions:

There are different editions available aimed at different audience and workload on databases. Ex:Enterprise,Standard,Compact,Developer, Workgroup,Express etc.

Enterprise Edition: o This is high end edition used for mission critical databases. It includes Core Engine and add-on

services.

Express Edition: o This is light weight edition and it includes core database engine. There is 10 GB limit on database

size. o This is great for learning SQL Server and also used for small and medium sized database

applications o It provide realistic testing environment though it is restricted to no of processors and database

size etc.

SQL Express with tools includes management studio along with Core database engine.

SQL Server Express with Advanced Services includes reporting services. SQL Server Management Studio:

SSMS is Integrated environment(GUI Tool) to access,configure,maintain,administer and develope the components of SQL Server.

SQL Server Management Studio Express is freeware. SQL Server Browser Service:

The SQL Server Browser program runs as a Windows service.

It listens for incoming requests for Microsoft SQL Server resources and provides information about SQL Server instances installed on the computer.

It contributes to the following actions: o Browsing a list of available servers o Connecting to the correct server instance

SQL Server Instance:

SQL Server can be installed multiple times on a same computer.Each installation is called instance.

Each instance has separate SQL server service,system databases,user databases

Each instance can be started or stopped independent of other instance.

Types of Instances: o Default Instance:

One instance can be default instance. Default instance is identified by machine name. Ex:Deccansoft

o Named Instance: All other instances on same machine must be given unique name and called named instance. Named instance is identified by Machinename\Instancename Ex:Deccansoft\Instance1

Page 8: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

8

Starting and Stopping SQL Server Service

Method1: Control Panel Adminitrative Tools Services Sql Server (SQLEXPRESS) Right Click Start if not already started or stop Method 2: StartAll ProgramsSQL Server 2012Configuration ToolsSQL Server Configuration ManagerClick SQL Server ServicesSelect particular SQL Server InstanceRight ClickStart or Stop

Types of Authentication in SQL Server

Windows Authentication:

The identity of the client on the Domain of the OS / Network is used by Sql Server to allow or deny access to the resources in the database

SQL Server Authentication:

The permissions to the client are granted based on the identity which was created and stored in SQL Server database.

Steps for Configuring Sql Server to support both the types of Authentication: 1. Start Programs Microsoft Sql Server 2012 SQL Server Management Studio Connect… Right

Click on Root of the Tree Properties Select Security Check SQL Server and Windows Authentication Mode.

2. Expand Security Logins Select User “sa” Right Click - Properties Set Password 3. Also Select Status (on left side) Check Login Enabled. 4. Disconnect and Connect again with SQL Server Authentication so that we are sure the above steps are

correct perfomed.

Types of System Databases

Master:

The master database contains all information about running servers configuration .It includes all of the logins, linked servers, endpoints, and other system-wide configuration settings.

The master database is also where SQL Server stores information about the other databases on this instance and the location of their files and records initialization information for the instance.

Master database is the logical repository for the system objects residing in the sys schema.

It holds information for all databases located on the SQL Server instance and is the glue that holds the engine together.

SQL Server cannot start without a functioning master database, you must administer this database with care and it is vital to make regular backups of this database.

Resource: The resource database is hidden, read-only system database.

System objects are no longer stored in master but the Resource database from SQL Server 2005.

System objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database.

The Resource database does not contain user data or user metadata.

The resource database is designed to make it easy for quick database upgrades. If new system objects are being put in place, it is only necessary to swap out the resource database MDF file

Model:

Model is essentially a template database used in the creation of any new user database created in the instance.

You can place any stored procedures, views, users, etc. in the model database so that when a new database is created, the database will contain the objects you have placed in the model database.

Tempdb:

As its name implies, Tempdb holds temporary objects such as global and local temporary tables and stored procedures.

Page 9: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

9

This database is recreated every time SQL Server starts, and the objects contained in it will be based upon the objects defined in the model database.

Tempdb also houses other objects such as table variables, results sets from table-valued functions, and temporary table indexes.

Because tempdb will hold these types of objects for all of the databases on the SQL Server instance, it is important that the database is configured for optimal performance.

Msdb:

The Msdb database is used by SQL Server Agent for scheduling alerts and jobs

The msdb database stores information regarding database backups (backup history), SQL Agent information, SQL Server jobs, Database mail, and some replication information such as for log shipping

Note: Database Mail is an enterprise solution for sending e-mail messages from the SQL Server Database Engine. Using Database Mail, your database applications can send e-mail messages to users. The messages can contain query results, and can also include files from any resource on your network.

Types of SQL Statements

1) Data Definition Language (DDL) : Create, Alter, Drop, Truncate 2) Data Manipulation Language (DML) : Insert , Update , Delete 3) Data Query Language(DQL) : Select 4) Transaction Control Language (TCL) : Commit , RollBack , SavePoint 5) Data Control Language (DCL) : Grant , Revoke

Data types in SQL Server

Datatype Min Max Storage Notes

Bigint -2^63 2^63-1 8 bytes

Int -2,147,483,648 2,147,483,647 4 bytes

Smallint -32,768 32,767 2 bytes

Tinyint 0 255 1 bytes

Bit 0 1 1 to 8 bit columns in the same table requires a total of 1 byte

Decimal ,Numeric -10^38+1 10^38–1 Precision 1-9 = 5 bytes, precision 10-19 = 9 bytes, precision 20-28 = 13 bytes, precision 29-38 = 17 bytes

Precision is the total number of digits. Scale is the number of decimals.

Money -2^63 / 10000 2^63-1 / 10000 8 bytes

Smallmoney -214,748.3648 214,748.3647 4 bytes

Float -1.79E + 308 1.79E + 308 4 bytes when precision < 25 and 8 bytes when precision >= 25 through 53

Precision is specified from 1 to 53.

Real -3.40E + 38 3.40E + 38 4 bytes Precision is fixed to 7.

Datetime 1753-01-01 00:00:00.000

9999-12-31 23:59:59.997

8 bytes 3.33 miliseconds accuracy

Smalldatetime 1900-01-01 00:00 2079-06-06 23:59 4 bytes 1 min accuracy

Date 0001-01-01 9999-12-31 3 bytes 1 day accuracy

Time 00:00:00.0000000 23:59:59.9999999 3-5 bytes Specifying the precision is possible. TIME(3) will have milliseconds precision. 100 nanosecond accuracy

Page 10: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

10

Datetime2 0001-01-01 00:00:00.0000000

9999-12-31 23:59:59.9999999

Presicion 1-2 = 6 bytes precision 3-4 = 7 bytes precision 5-7 = 8 bytes

100 nanosecond accuracy

Datetimeoffset 0001-01-01 00:00:00.0000000 -14:00

9999-12-31 23:59:59.9999999 +14:00

Presicion 1-2 = 8 bytes precision 3-4 = 9 bytes precision 5-7 = 10 bytes

Is a datetime2 datatype with the UTC offset appended.

Char 0 chars 8000 chars Defined width Fixed width

Varchar 0 chars 8000 chars 2 bytes + number of chars

Variable width

Varchar(max) 0 chars 2^31 chars 2 bytes + number of chars

Variable width maximum 2GB

Text 0 chars 2,147,483,647 chars

4 bytes + number of chars

Variable width

Nchar 0 chars 4000 chars Defined width x 2 Fixed width

Nvarchar 0 chars 4000 chars Variable width

Nvarchar(max) 0 chars 2^30 chars Variable width

Ntext 0 chars 1,073,741,823 chars

Variable width

Binary 0 bytes 8000 bytes Fixed width

Varbinary 0 bytes 8000 bytes Variable width

Varbinary(max) 0 bytes 2^31 bytes Variable width

Image 0 bytes 2,147,483,647 bytes

Variable width

Sql_variant Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.

Timestamp Stores a database-wide unique number that gets updated every time a row gets updated.

Uniqueidentifier Stores a globally unique identifier (GUID).

Xml Stores XML data. You can store xml instances in a column or a variable.

Cursor A reference to a cursor.

Table Stores a result set for later processing.

CREATE DATABASE Create Database DemoDb

Use DemoDb (To use the newly created database) Sp_helpdb DemoDb (Describes the structure of a database) CREATE TABLE Create Table <Table Name> (Column name_ 1 data type [column Attributes] [, Column name_2 data type [column Attributes] ]……. [, table Attributes] ) Attributes:

Null/Not Null:Indicates whether or not a particular column can accept Null values.

Primary Key/Unique:Indicates primary key or unique key for the table.

Identity:Indicates that the column is Identity column.For this column values are system generated depending on (seed, Increment).

Default:Specifies default value for column.

Page 11: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

11

Create Table Employee ( ID int Identity (10, 1) Primary key, Empname Varchar (15) Not Null, Salary Money Not Null Default 500 )

ALTER TABLE Alter Table <table name > Add <column name> <data type> Alter Table <table name> Alter Column <column name> <data type> Alter Table <table name> Drop Column <column name> [, …..N]

Example: Alter table Employee add Address varchar (30) Alter table Employee alter column Address varchar (50) Not Null Alter table Employee drop column Address

DROP TABLE Drop Table <TableName>[, ….N]

*DDL (Create, Alter, Drop) Statements cannot be rolledback.

INSERT Syntax: Insert into <table name> (column list) values (value1, value2…) Example

Insert into Employee Values('JOHN',3000,'NEW YORK')

Insert into Employee(Empname, Salary) Values('SMITH',DEFAULT)

Insert into Employee Values('ROBERT',4000,'NULL),('ALLEN',DEFAULT,NULL) Note: For inserting NULL value into a column either column name can be skipped or NULL can be used for value

Set IDENTITY_INSERT <table name> ON: Allows inserting value for Identity column – This can be done on only one table at a time

Set Identity_Insert 'EmployeeDemo' ON

Insert into Employee Values (100,'BLAKE', 5000, NULL) Inserting Multiple Rows with single insert statement:

Insert into Employee Values ('BLAKE', 5000, NULL),('Harry',4000,'Dallas'),('Roger',5000,'New York')

Insert into Employee Select 'blake',5000,Null Union all Select 'John',5000,'New York' Union all Select 'Harry',5000,'Dallas'

UPDATE Syntax: update <table name> set col1 = val1, col2 = val2

Update Employee Set Salary = Salary +100 Where Id=10 DELETE Syntax: delete from <table name> [where expression]

Delete from Employee where Id=10 –Deletes only one record

Delete from Employee –Deletes all the records from the Employee table TRUNCATE

It is functionally identical to delete statement but is much faster when compared to delete as Delete removes rows one at a time and records an entry in the transaction log for each deleted row so delete execution is slower when compared to truncate.

Records deleted using truncate cannot be rolled back. Also the identity column value is reset. Syntax: truncate table <table name>

Page 12: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

12

EXAMPLE: Creating Department and Employee table with one to many relationship. Create Table Department

( PKDeptId Int Primary Key DeptName Varchar(14) Not Null , Location Varchar(13) Not Null ) Create Table Employee (

PKEmpId Int Primary Key, EmpName Varchar(10) Not Null, Job Varchar(9) Not Null, Manager Integer Null, HireDate DateTime Not Null, Salary Decimal(7,2) Not Null, Commission Decimal(7,2) Null, FKDeptId Integer References Department(PKDeptId)

)

DQL

SELECT SELECT select_list

[ INTO new_table ] FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ]

Examples:

Select * From Employee

Select PkEmpId,,EmpName, Salary From Employee It is recommended to always replace “*” with column names in the select statement. By doing this we can mention only the required columns and this optimizes the performance of the query.

Select PkEmpId as ID, EmpName as EmployeeName From Emp– Aliasing a Column

Select DISTINCT Salary From Employee

Select IDENTITYCOL From Employee

Select TOP 3 * From Employee

Select TOP 50 PERCENT * From Employee

Select EmpName+'_'+Job AS NAME From Employee

Select EmpName+'''s'+' job is ' + Job as information From Employee

Select EmpName, Salary*12 As AnnualSalary from Employee

Select cast(EmpName as varchar(5)) as ShortName From Employee

Select 'The Salary is' + cast(sal as varchar(9)) from Employee Operators:

Arithmetic operators + , - , * , / , %

Basic Relational operators = , > , < , >= , <= , ! , != , <> , !> , !<

Logical operators And , or , Not

Advanced Relational operators In , Not In , Is Null , Is Not Null , Between , Not Between , Like , Not Like, Any, ALL

Select EmpName,Salary,Job From Employee Where Salary>2000

Select * From Employee Where Salary > 1000 and Job = 'clerk'

Page 13: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

13

Select * From Employee Where Salary > 1000 and NOT Job = 'clerk'

Select * From Employee Where Job In ('clerk', 'manager') – case insensitive comparison is done

Select * From Employee Where PkDeptId=10 or PkdeptId=20

Select * From Employee Where PkdeptId in (10,20)

Select * From Employee Where HireDate Between '12-17-1980' and '05-17-1981'

Select * From Employee Where Salary Not between 1000 and 1800

Select * From Employee Where Salary is null

Select * From Employee Where Salary is Not Null

Select * From Employee Where Salary > SOME (Select Salary From EmpLoyee Where PkDeptId=20)

Select * From Employee Where Salary > ALL (Select Salary From Employee Where PkDeptId=20)

Select * From Employee Where PkempId >= ALL(Select PkEmpId From Employee)

Select * From Employee Order By EmpName, Salary DESC Note:

ntext, text, or image columns cannot be used in an ORDER BY clause.

Null values are treated as the lowest possible values.

Wild card Matches

% Represents a set of characters

_ Represents any one character

[ ] Any single character within the specified range

[^] Any single character not within the specified range

Select * From Employee where EmpName like 'B%'

Select * From Employee where EmpName like '___'

Select * From Employee where EmpName like 'B__'

Select * From Employee where EmpName like '[a-c]%'

Select * From Employee where EmpName like '[^a-c]%'

Select * From Employee where EmpName like 'A[c-e]%'

Select * From Employee where EmpName like '%\_%' escape '\'

AGGRIGATE FUNCTIONS

Aggregate Functions

SQL aggregate functions return a single summary value, calculated from values in a column.

These functions Except count(*) ignore NULL values.

If SELECT Clause includes a GROUP BY, the SELECT clause can include aggregate functions, column used for grouping and expression that result in constant value.

HAVING specifies the condition for groups. It determines which group should be included in final result.It can refer to the column included in select clause or an aggregate function.

HAVING condition is applied after the rows filtered by WHERE condition are grouped.

Select AVG(Salary), COUNT(*), MAX(Salary), MIN(Salary), SUM(Salary) From Employee

Select Count(Commission) From Employee (This function gives no of employees which don’t have null value for commission)

Select Count(Distinct fkDeptId) From Employee

Select Min(Sal) as ‘Min salary’ From Employee Group by When Aggrigate Function is used ,every column in the select list must be either in group by or must be an aggregate function.

Select FkDeptId, Min(Salary) as 'Min salary' from Employee group by FkDeptId (Grouping min (Salary) by deptno)

Select FkDeptId ,Min(Salary) as MIN ,Max(Salary) as MAX From Employee Group by FkDeptId

Select FkDeptId ,Min(Sal) as 'Min salary' From Employee Where job='clerk' Group by FkDeptId (First filtering records by job then grouping by deptno)

Select FkDeptId, Max(Salary) From Employee Where commission > 100 Group By ALL FkDeptId

Page 14: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

14

Note: ALL is meaningful only when the SELECT statement also includes a WHERE clause.

Select FkDeptId, Count(*) as EmpCount From Employee Group By DeptNo Having Count(*) > 2

Note: With HAVING clause condition can have aggregate function

Select FkDeptId, Avg(Sal) as AverageSalary, Sum(Sal) as TotalSalary From Employee Where Sal > 1000 Group By FkDeptId Having Avg(Salary) >= 1500

Note: Having is applied to aggregated value for that group and Where is applied to each row .

Rollup Operator

It adds summary row for each specified group.

If group by clause specifies a single group then final summary row is aded at the end.

If more then one groups are there summary row is specified for each group and final summary row is also added at the end.

Examples:

Select FkDeptID,count(*),Max(Salary) From employee Group by FkDeptId With Rollup

Select FkDeptID,job ,count(*),Max(Salary) From employee Group by FkDeptId,job With Rollup

Cube Operator

If Group by clause specifies a single group then final summary row is added at the end.

If Group by clause specifies more than one group, it adds summary row for each combination of specified group.

Examples:

Select FkDeptID,count(*),Max(Salary) From employee Group by FkDeptId with Cube Select FkDeptID,job ,count(*),Max(Salary) From employee Group by FkDeptId,job with Cube

Classroom Practice Examples: 1. Get total number of employees department wise 2. Get Min, Max Salary offered by each department 3. Get total number of employees for each job 4. Get Avg Salary offered by each job 5. Get Total number of employees in each department having salary >1500 6. Get Min ,Max Salary for each department and department should have more than 3 Employees 7. Get total employees in each department and Avg salary for each department should be more than 1500 8. Get Min,Max Salary offered for each job except Analyst 9. Get Min,Max salary for each job and Min Salary should be more than 1000 10. Get the job which offers highest Salary 11. Get Employee details whose salary is greater than

a. Avg salary of department 10 b. Max salary of department 30

12. Get total number of employees hired in different years 13. Get total number of employees whose name starts with same letter 14. Get maximum salary 15. Get second maximum salary 16. Get total number of employees under manager Jones. 17. Get Total number of jobs in employee table

Page 15: SQL Server Basic

Deccansoft Software Services – SQL Server Introduction

15

PKEmpId EmpName Job Manager HireDate Salary Commission FKDeptId ------------ --------------- ---------- ------------- ----------------------------------- ------------- ------------------------- ----------------- 7369 SMITH CLERK 7902 1980-12-17 00:00:00.000 800.00 NULL 20 7499 ALLEN SALESMAN 7698 1981-02-20 00:00:00.000 1600.00 300.00 30 7521 WARD SALESMAN 7698 1981-02-22 00:00:00.000 1250.00 500.00 30 7566 JONES MANAGER 7839 1981-04-02 00:00:00.000 2975.00 NULL 20 7654 MARTIN SALESMAN 7698 1981-09-28 00:00:00.000 1250.00 1400.00 30 7698 BLAKE MANAGER 7839 1981-05-01 00:00:00.000 2850.00 NULL 30 7782 CLARK MANAGER 7839 1981-06-09 00:00:00.000 2450.00 NULL 10 7788 SCOTT ANALYST 7566 1987-07-13 00:00:00.000 3000.00 NULL 20 7839 KING PRESIDENT NULL 1981-11-17 00:00:00.000 5000.00 NULL 10 7844 TURNER SALESMAN 7698 1981-09-08 00:00:00.000 1500.00 0.00 30 7876 ADAMS CLERK 7788 1987-07-13 00:00:00.000 1100.00 NULL 20 7900 JAMES CLERK 7698 1981-12-03 00:00:00.000 950.00 NULL 30 7902 FORD ANALYST 7566 1981-12-03 00:00:00.000 3000.00 NULL 20 7934 MILLER CLERK 7782 1982-01-23 00:00:00.000 1100.00 NULL 10 PKDeptId DeptName Location ----------- ---------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON