0% found this document useful (0 votes)
10 views

SQL Server Till Basic Group by

The document outlines a training course on SQL Server. It includes 31 topics that will be covered ranging from introductions to databases, SQL Server editions, installation and management to more advanced topics like transactions, control of flow commands, stored procedures, triggers and exception handling. It also provides introductory examples on accessing databases and tables in SQL Server.

Uploaded by

Burugolla Ravi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

SQL Server Till Basic Group by

The document outlines a training course on SQL Server. It includes 31 topics that will be covered ranging from introductions to databases, SQL Server editions, installation and management to more advanced topics like transactions, control of flow commands, stored procedures, triggers and exception handling. It also provides introductory examples on accessing databases and tables in SQL Server.

Uploaded by

Burugolla Ravi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Table Of Content:

1. Introduction to Databases & RDBMS


2. Introduction to SQL Server & Editions
3. Installation of SQL Server & Management Studio
4. Accessing Data base Engine & Login Database
5. SQL Server Architecture
6. Introducing to Database Management IDE
7. Introduction to T-SQL
8. Comments in SQL Server
9. Database Operations
10. SQL Server Data Types
11. Data Definition Language Commands
 CREATE
 DROP
 ALTER
 TRUNCATE
 RENAME
12. Integrity Constraints
 NOTNULL
 UNIQUE
 CHECK
 DEFAULT
 INDEX
 PRIMARY KEY
 FOREIGN KEY
13. Data Manipulation Language Commands
 USE
 INSERT INTO
 UPDATE
 DELETE
 MERGE
 SELECT
 CUBE
 ROLLUP
 OFFSET
 FETCH
 TOP
 PIVOT
14. SQL Server Operators
 Arithmetic Operators
 Assignment Operators
 Bitwise operators
 Comparison Operators
 Compound Operators
 Logical Operators
 Scope Resolution Operators
 Set Operators
 String Concatenation Operators
15. SQL Server Built-in Functions
 Math & Numeric Functions
 Date & Time Functions
 String Functions
 Other & Advanced Functions
 Aggregate Functions
16. SQL Server Clauses
 DISTINCT Clause
 GROUP BY
 WHERE
 ORDER BY
 HAVING
 SELECT
 GROUPING SETS
17. Sub Queries & Nested Queries
18. Joins
19. Indexes
20. Views
21. Synonyms
22. Sequences.
23. Common Table Expression (CTE) In SQL Server
24. Data Control Language Commands (DCL)
 Grant
 Revoke
25. Transaction Control Language Commands (TCL)
 COMMIT
 ROLLBACK
 SAVEPOINT
26. Control Of Flow Commands
 BEGIN ..END
 BREAK
 CONTINUE
 GOTO
 IF ELSE
 RETURN
 WAITFOR
 WHILE
27. User Defines Functions
28. Stored Procedures
29. Cursors
30. Triggers
31. Exception Handling
32. Backup & Restore Database.
Intro Queries:
select * from sysdatabases

select * from sysdatabases where dbid > 4

use RajuDB

select DB_NAME()

select * from RajuDB.INFORMATION_SCHEMA.tables;

To return all tables and views in one query, execute the following TSQL statement:
SELECT * FROM INFORMATION_SCHEMA.TABLES;
GO
It may also be wise to specify the database you wish to query:
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;
GO
SQL Server Data Types

Data Types for Characters:


>> Non-Unicode – Data Types
1) Char (<8K bytes)
2) Varchar (<8k Bytes)
3) Varchar (Max)
>> Unicode – Data Types:
1) nchar (<4k bytes)
2) nvarchar (<4k bytes)
3) nvarchar (max)

Char Vs Varchar:
1) use char for fixed, small sizes
2) Use varchar to allow values of differing sizes
3) Avoid varchar for frequently altered columns
Example : address of an employee
Numeric Datatype:

1) Whole Numbers
Tinyint (1 byte) > 0 to 255
Smallint (2 bytes) -> -32768 to 32767
Int (4 Bytes) -> -2,147,483,648 to 2,147,483,647
Bigint (8 bytes)
2) Decimal or Numeric (8 bytes)
38 Digits
3) Approximate Numeric Data
Float (4 bytes)
Real (8 Bytes)

Monetary Data:
1) Smallmoney (4 bytes)
2) Money (8 bytes)
Date And Time Data Types:
1) Smalldatetime (4 bytes)
January 1, 1900 through June 6, 2079
2) Datetime (6 bytes) (YYYY-MM-DD HH:MM:SS)
January 1, 1753 through December 31, 9999
3) Datetime2 (7 bytes)
01-01-01 through 9999-12-31
4) Date (3 bytes) (YYYY-MM-DD)
01-01-01 through 9999-12-31
5) Time
6) DateTimeOffset (7 bytes)

Binary Data:
Binary Data (For Hexadecimal data)

 Binary (<8k)
 Varbinary(<8k)
 Varbinary(max)
To Store Pictures, Media files, Docs etc.
To Migrate data from one platform to another
Special Data Types:
Time Stamp (8 bytes):
 Indicate activity
 Known as ‘Row Version’ column
 Changed whenever a row is modified
 Not related to date and time
 Updated by SQL Server engine itself
 Only One per table
Bit:
0 or 1 or Null

Global Unique Identifier:


 GUID (16 byte)
 One Per Table
 Hexa Decimal Data
 SS Insert new GUID per each row using NewID() Fucntion
Eg: Bar Code number on the products
XML Data Types:
 To make platform independent
 Store other platform xml data.

Spatial Data Types:


 Geometry
 Geography : to store maps
 Hierarchyid
To get the level in a hierarchy
Business Integrity: (Data Validation)

Constraints:
 Null
 Default
 Primary Key
 Unique Key
 Foreign Key
 Check Constraints
 Triggers
 Identity
Note: The Above features are used to validate the data in SQL Server.
Null:
 Represents ‘unspecified’ value
 For Example: Hobbies , Mobile No columns
Note: Storing NULL Values as part of table is Bad. Avoid Storing NULL value, Replace
it with DEFAULT value.
 Why Storing Null values are bad?
Ans) Cannot perform arithmetical and string operations such as sort etc.
Any Value + Null - Null

Default:
 The Following ways in which we can provide default values in a table.
Constant Value: 0, 1, N/A
Expression: Price * Qty
Built in Function: getdate ()

Keys:
Key means which is an attribute (Col) or multiple attributes. Using which any one retrieve a
single instance from the group instances.
RDBMS:
Entities: Tables
Attritbutes : Cols
Entity Instance – Rows / Records

EMPID NAME Passport DLNO


101 AMAN A123 456
102 BABITA Z126 978
103 AKASH D728 478
KEYS Are: EMPID, Passport, DLNo
Primary key : EMP Id
Alternative Keys : Passport, DL No

Alternative Keys: Unique Keys


Primary Key: Primary Key
Candidate Keys = Primary Key + Alternative Keys

What is a Key?
Key is an attribute which does not allow duplicate values.

What is purpose of the Key?


To retrieve single instance.

Primary Key:
 Ensures uniqueness.
 No null
 Auto-creation of index (clustered)
 One per table
 Composite Primary key
 Not Mandatory
Recommended
Unique Key:
 For alternative keys
 Ensures uniqueness.
 Allows Null
>> Only One NULL Value
 Auto creation of index (non-clustered)
 Many unique keys per table
 Composite unique keys.

PK Vs UK
Primary key Unique Key
It does not allow null values It allows ONLY one null value
One PK per table Many UKs per table
It Creates clustered index It creates non clustered index

Composite Primary Key:


A key which has multiple attributes called as composite key.
 Made up of more than 1 column.
 Each combination of values must be unique.
 Order of the columns in PK should match the order of the columns as shown in the
table.
 No Null values allowed in part of the PK.
Example:
TrainNo + CoachNo + SeatNo
TowerNo + HouseNo
ClassNo + SectionNO + RollNo
Relations Ships:
Conditions: To make relations we must follow below conditions
 One table should contain PK & Another table Contains FK.
 A Common Column in Both tables
 The common column datatype must be same in both tables.
Types:
 There are 3 types of relationships b/w tables.
1 to 1
1 to m
m to m
1 to 1 Relationship:

1 to many Relations:
Many to Many Relations:

Referential Integrity:
SQL Server performs existing check when we create relationship. This existence check is called.
As referential integrity.
Deptid Name
1 Accountant
2 Purchase
3 Marketing

EID Name DeptID


1001 A 1
1002 B 3
1003 C 2
1004 D 2
1005 E 3
1006 F 99

Data Modeling:
What Is FK?
It is used to establish relationship between tables in RDBMS tools.
It is also checking existence check.
1 to 1 (Any PK can become FK) -- 2 Tables, 2 PK, 2 FK
1 to M (Parent table PK – FK in the child table) – 2 Tables, 2 PK, 2FK ( P to Child)
M to M (Bridge table will be needed) – 3 tables, 2 PK, 2 FK

Can I have duplicate values in FK?


Yes
Can I have NULL values in FK?
Yes
How many FKs per table?
Many per table.
How many PKs per table?
Only One.
How many UKs per table?
Many.
Can We have NULL in PK?
No
Can We have NULL in UK?
Yes (Only one)

Self-Referential Table:
PK and FK both are there in same table.
A FK referring its own table PK. Then that table called as self-referential table.
Cascade Features:
 What if PK/UK column in parent table changes.
 What if a row in parent table is deleted.
 Solution: cascade update, delete features
Note: cascade features cannot be implemented on self-referential table.

Cascade Delete ON: if you delete record from parent table automatically related records in
child table. Get deleted.
Cascade Delete OFF: No action taken in child table.

Cascade Update ON: changes copied to child table.


Cascade Update OFF: changes wont copied to child table

Check Constraints:
 Column level
Expression involving only 1 column.
 Table level.
Expression can involving more than one column from the same table.
 Multiple check constraints per column.

 It will allow following operators.


=,<>,>,>=,<=,<,~,IN,OR,AND,NOT Etc.
 No Programing
IF …ELSE
LOOP Etc.
 It always works within the same table. Cannot work across tables.
 Use check constraints when the requirement is simple. Else use Triggers.
 Check constraints are faster in performance.
Identity Property: (Eg Automatically generate EMPId for each new Employee)
 Set for INTEGER or Decimal columns.
 Identity seed (initial values) & Increment or Decrement.
Integers
Negative Integers
 Only one column per table
 No NULL & Default values.
 Unique values.
 It may have gaps when data is deleted.
DBCC CHECKIDENT(<<table>>, RESEED, <Deleted Record No>)
 Decimal Values not allowed.
SQL Commands:
Create Database:
.mdf(data file) – Data
.ldf (log file) – log

Database Types:
 System DB: installation time data base engine will create below databases.
Master:
>> configuration & user informations.
>> all other db info
>> What happened if master db is deleted?
SQL Server will not start.

Model:
>> template & create new db.
Msdb:
>> jobs (backup of DB)
>> Alerts (SMS/ Email)
Tempdb

 User defined DB : Which are created by user.

SQL Comments:
Comments are used to understand the commands.
2 Types
 Single line comment : -- (symbol)
 Multiline Comments: /* line1, Line2, line3…..*/

Create: (database)
1) Create database syntax:
Create database <dbname>
Go

2) Drop database syntax:


Drop database <dbname>
Go
3) Modify database syntax:
Alter database<dbname>
Go
Create Table:

Find Schema Name Of Table


SP_Help <table_name>
go

Update:

TCL Commands:
Finding DB Comptability:

Question:1
 Basically, Identity column will default value, In case if we delete any row it takes next
identity number.

Delete VS Truncate:
Case Studies:
SCHOOL CASE STUDY
SUPPLIER CASE STUDY
INDIAN BANK CASE STUDY

SQL Server Basic Queries:

Topics:
 Retrieving Data
 Aggregating Data to Information
 Filtering
 Sorting
 Grouping
 Joins
 Sub Queries And Correlated Sub Queries
 Derived Tables
 Ranking Functions And CTE
Filtering:

Sorting:
Q) List ACID and Name Only for SB accounts and list the names in descending
order.
InterView Questions:

 Why we used constant is to Declared any value as column names.

AS : (Alias Name)
As we used to give tempory column names for table as below

 As is Key word which we used to Define Column Names for temporarily.


 As key Word Optional to declare column names.
 If is they Space in Alias Name will get error.
 If we want space Soourand it with [ ].
Concatinate:

Type Cast:
Some times When we do Concatinate With INT + CHAR / CHAR + Money Will get errors like
below

To avoid Type cast errors We can use below Any method to Resolve it.

select ACID, Name , cast(UnClearBalance as varchar) + ' USD' from


AccountMaster
select ACID, Name , Convert(varchar , UnClearBalance) + ' USD' from
AccountMaster
Cast (Column Name as Datatype)
 It is ANSI Fucntion its used to convert data types.
Convert (datatype, column name , stylename)
 It is SQL Server function its used convert date and time styles.
Aggrigate Functions:
 COUNT (*)
It count No of Rows in a table.
 SUM (Col Name)
It gets the total value.
 MIN (Col Name)
It gets the Minimum value.
 MAX (Col Name)
It gets the Maximum value.
 AVG (Col Name)
It gets the average value.
-- Aggrigate Fucntions
-- Find Out No Of Coustomer
select count(*) as 'No Of Coustomer' from AccountMaster

-- Find Out No Of Coustomer in BR1


select COUNT(*) from AccountMaster where BRID='BR1'

-- Find Out No Of Coustomer in BR5


select COUNT(*) from AccountMaster where BRID='BR6'

-- Find Out No Of Coustomer in BR1 & BR6


select COUNT(*) from AccountMaster where BRID='BR6' OR BRID='BR1'

-- Find Out No Of Coustomer in BR1 OR BR6 , BR9 Using IN


select COUNT(*) from AccountMaster where BRID IN('BR6','BR1','BR9')

-----------------------------------------------------------------------------------------
-- SUM Function
select SUM(Clearbalance) TotalBalance from AccountMaster

-- To find Only BR1 Total balance


select SUM(Clearbalance) TotalBalance from AccountMaster Where BRID='BR1'

-- To find Only BR1 Total balance


select SUM(Clearbalance) TotalBalance from AccountMaster Where BRID IN('BR1','BR2','BR3')

-----------------------------------------------------------------------------------------
-- MIN Fucntion
select MIN(Clearbalance) MinBalance from AccountMaster
-- Want to find FInd BR1, BR2, BR3
select MIN(Clearbalance) MinBalance from AccountMaster where BRID IN ('BR1','BR2','BR3')
-----------------------------------------------------------------------------------------
-- MAX Fucntion
select MAX(Clearbalance) MaxBalance from AccountMaster
-- Want to find FInd BR1, BR2, BR3
select MAX(Clearbalance) MaxBalance from AccountMaster where BRID IN ('BR1','BR2','BR3')
-----------------------------------------------------------------------------------------
-- AVG Fucntion
select AVG(Clearbalance) AvgBalance from AccountMaster
-- Want to find FInd BR1, BR2, BR3
select AVG(Clearbalance) AvgBalance from AccountMaster where BRID IN ('BR1','BR2','BR3')

-----------------------------------------------------------------------------------------
-- ALL in One Query
Select Count(*) NoCoutomers,
MIN(Clearbalance) MinBalance,
MAX(Clearbalance) MaxBalance,
Avg(Clearbalance) AvgBalance,
Sum(Clearbalance) TotalBalance
From AccountMaster

Advanced Aggregate Functions:


Group BY:
Instead of Writing Single Where class, we can go with Group BY clause.
It will group similar data on top it will perform Aggregate functions / Any user functions.

Select * from AccountMaster

-- Count In Advanced Level


Select count(1) from AccountMaster -- Count() Expect Junk Value And Column Value as well

-- No Coustomer in BR1
select Count(*) As Cont from AccountMaster where BRID='BR1'

-- No Coustomer in BR2
select Count(*) As Cont from AccountMaster where BRID='BR2'

-- No Coustomer in BR3
select Count(*) As Cont from AccountMaster where BRID='BR3'

-- Instead Of Using Multiple Where cluases We can go use the Group By As like Below
-- Branch Wise No Coustomers
select Brid, count(*) Count from AccountMaster group by BRID

-- Using Where cluase to gether with group By


select BRID,Count(*)
from AccountMaster
where PID='SA'
Group by BRID

-- Using Group by & Where & Order BY cluase


select BRID,count(*) as cnt
From AccountMaster
where PID='SA'
group by BRID
Order By BRID DESC

-- using Group BY With Aggrigatror


select PID,Sum(clearbalance) As TotalBal , Min(Clearbalance) As MinBal ,
Max(clearbalance) as MaxBal ,Count(*) As Cnt
From AccountMaster
group by PID
Order by MaxBal Desc

GROUP IN GROUP:
>> Group by Cluase wont display the Data for Zero Count.
-- Group With in Group
-- Branch wise product wise no of coustomers
select PID,BRID, SUM(ClearBalance) as TotalBalance
from AccountMaster
group by BRID, PID
Order by BRID

 Using Distinct With Aggrigations (It allows)

You might also like