SQL Server Till Basic Group by
SQL Server Till Basic Group by
use RajuDB
select DB_NAME()
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
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
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
What is a Key?
Key is an attribute which does not allow duplicate values.
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
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
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
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.
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.
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
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
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
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:
AS : (Alias Name)
As we used to give tempory column names for table as below
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.
-----------------------------------------------------------------------------------------
-- SUM Function
select SUM(Clearbalance) TotalBalance from AccountMaster
-----------------------------------------------------------------------------------------
-- 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
-- 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
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