SlideShare a Scribd company logo
Some points to consider when choosing Temporary, Global Temp Tables, between them:

       Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If
       you have large amounts of data for which accessing by index will be faster then
       temporary tables are a good option.
       Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If
       you want a non-unique index just include the primary key column as the last column in
       the unique constraint. If you don't have a unique column, you can use an identity
       column.)
       Table variables don't participate in transactions, logging or locking. This means they're
       faster as they don't require the overhead, but conversely you don't get those features. So
       for instance if you want to ROLLBACK midway through a procedure then table variables
       populated during that transaction will still be populated!
       Temp tables might result in stored procedures being recompiled, perhaps often. Table
       variables will not.
       You can create a temp table using SELECT INTO, which can be quicker to write (good
       for ad-hoc querying) and may allow you to deal with changing datatypes over time, since
       you don't need to define your temp table structure upfront.
       You can pass table variables back from functions, enabling you to encapsulate and reuse
       logic much easier (eg make a function to split a string into a table of values on some
       arbitrary delimiter).
       Using Table Variables within user-defined functions enables those functions to be used
       more widely (see CREATE FUNCTION documentation for details). If you're writing a
       function you should use table variables over temp tables unless there's a compelling need
       otherwise.
       Both table variables and temp tables are stored in tempdb. This means you should be
       aware of issues such as COLLATION problems if your database collation is different to
       your server collation; temp tables and table variables will by default inherit the collation
       of the server, causing problems if you want to compare data in them with data in your
       database.
       Global Temp Tables (##tmp) are another type of temp table available to all sessions and
       users.



Retrieving SQL Server Identity Column Values

Function

SCOPE_IDENTITY:: Returns the last identity value within the current execution scope.
SCOPE_IDENTITY is recommended for most scenarios.

@@IDENTITY:: Contains the last identity value generated in any table in the current session.
@@IDENTITY can be affected by triggers and may not return the identity value that you expect.
IDENT_CURRENT:: Returns the last identity value generated for a specific table in any session
and any scope.

                  Default Schema is “dbo.” Or define it
                  nVarchar takes double the size defined. It supports Unicode

create database Pragya

sp_who2
sp_helptext 'sp_who2'

use mydb
select * from demo1

--------------------------
use Pragya
create Table test1 (i int) --permanent
create Table #test1 (i int) --temp
create Table ##test1 (i int) --global temp
Declare test1(i int)

Create Table test2(i int)




Create Table Customer
(CustomerID INT IDENTITY (1000,1) Not Null
, Name nvarchar(100)
,CreateDateTime datetime
,CreditLimit decimal(12,5)
)
insert into Customer( Name,CreateDateTime, CreditLimit
) values ('test', Getdate(), 1000)



select * from Customer

Alter table customer
Add test nvarchar(200)

Alter table Customer
drop column test

Alter table Customer --not preferred
Add Primary Key (CustomerID)

Create Table CustPhone
(PhoneID int Primary Key, CustomerID int Null, Phone Int)

Alter table CustPhone
drop constraint FKCustomerID
Alter table CustPhone
Add Constraint UniqueName


Create Table Orders
(OrderID INT IDENTITY (1,1) Not Null Check (OrderID between 1 and 1000000)
, OrderDate datetime not null, CustomerID integer Foreign Key references
Customer(CustomerID))

insert into Orders(OrderDate) values ( Getdate())

Sp_help Orders



      Four -Part Naming:: Server, Database, Schema, Object Name
      A Cartesian join will get you a Cartesian product.
      A Cartesian join is when you join every row of one table to every row of another table.
      You can also get one by joining every row of a table to every row of itself.
SELECT [CustomerID]
      ,[AddressID]
      ,[AddressType]
      ,[rowguid]
      ,[ModifiedDate]
  FROM [AdventureWorks].[SalesLT].[CustomerAddress]
  where CustomerID= '29489'
  and AddressID=' 1069'

GO

SELECT [CustomerID]
      ,[AddressID]
      ,[AddressType]
      ,[rowguid]
      ,[ModifiedDate]
  FROM [AdventureWorks].[SalesLT].[CustomerAddress]
  where CustomerID= '29489'
  or AddressID=' 1069'

     SELECT [CustomerID]
         ,[AddressID]
         ,[AddressType]
         ,[rowguid]
         ,[ModifiedDate]
     FROM [AdventureWorks].[SalesLT].[CustomerAddress]
     where CustomerID= '29489'
     or AddressID=' 1069'
     and AddressType= 'Main Office'

Click Display Estimated Executed Plan button on top
Retrieve Identity
select IDENT_CURRENT('Pragya')
select SCOPE_IDENTITY()
select @@IDENTITY

insert into Customer(Name, CreateDateTime, CreditLimit) values ('Hello',
GETDATE(), 5000)

sp_help Customer

select * from Customer

--not preferred
-- NON Clustered Primary Key
Alter table Orders
Add constraint PKCustomer1 Primary Key NONCLUSTERED (OrderID)
    Concatenate name
SELECT
       [Title]
       ,[FirstName]
       ,[MiddleName]
       ,[LastName],' '+ isNull (Title, '')+ FirstName +LastName As EmpName

          FROM [AdventureWorks].[SalesLT].[Customer]
--Self Join
SELECT emp.empid, emp.title, m.title, from emp E
inner join emp M on e.m_id=m.e_id

---Without join
SELECT emp.empid, emp.title, m.title, from emp E,
 emp M where e.m_id=m.e_id

 Select mgrId, COUNT(empId)
 from employee
 group by mngrId

 -- for null mngr
 Select EmpID, MngID, Title from Employee where mngrId=3


 begin Tran
 set rowcount 100 -- only 100 rows will get effected like top 100
 Update employee
 set loginId=null

 --Alter query is faster than update
 Alter table Employee
 alter column LoginId nvarchar(256) null

 Select mgrId, COUNT(empId), COUNT(LoginID), SUM(LoginID) --operator datatype
must not b varchar
 from employee E
 group by mngrId


 Select mgrId, COUNT(empId), COUNT(isnull(LoginID, 'a'))
 from employee E
 group by mngrId

----------------------------------------------------
 --------Mngr total emp count is >20-------
 Select mgrId, COUNT(EmpId)
 from Employee E
 group by mngrId
 having COUNT(empId)>20

 -------------Another way---Derived Table-----
 Select * from (Select mgrId, COUNT(EmpId) emp
 from Employee E
 group by mngrId)AA
 where emp>20



---UNION---
select *
from
SalesLT.Customer a
inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID
inner join SalesLT.Address b on CA.AddressID = b.AddressID
where b.StateProvince= 'washington'
--Order byFirstName desc --Cannot use here--At end of query
UNION
select *
from
SalesLT.Customer a
inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID
inner join SalesLT.Address b on CA.AddressID = b.AddressID
where b.StateProvince= 'Texas'
Order by FirstName asc

---------------EXCEPT-----------------------

select *
from
SalesLT.Customer a
inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID
inner join SalesLT.Address b on CA.AddressID = b.AddressID
where b.StateProvince= 'washington'
EXCEPT -- same no of column and same datatype
select *
from
SalesLT.Customer a
inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID
inner join SalesLT.Address b on CA.AddressID = b.AddressID
where b.StateProvince= 'Texas'
Order by FirstName asc

----------Working with Intersect--------HW--------------------
========================
---------UnionAll----------
Create Table t1(i int)
insert into t1
select 1
union
select 2
union select 3

--
select distinct * from t1
select * from t1
union
select * from t1

select * from t1
union all
select * from t1
---
select distinct * from t1
select * from t1 -- Expensive performance
union
select * from t1

select i from t1
group by i
================================================

-------CUrrent Date Time
select   GETDATE()
select   LEFT('Pragya', 2) -- first 2
select   Right('Pragya', 2)
select   MONTH(getdate())
select   DATEPART(M,getdate())
create   table td(dt varchar(10))
Insert   into td values('01/01/2011')
select   * from td
select   dt, CAST(dt as DATE),CAST(dt as datetime) from td

-- first day of month and last day of mnth with date-- HW
DECLARE @Today DATETIME
SELECT @Today = '8/25/2011'
SELECT DATEADD(dd,-(DAY(DATEADD(mm,1,@Today))-1),DATEADD(mm,0,@Today))
-----------------------------------------------------
SELECT DATEADD(dd, -DAY(DATEADD(m,1,@Today)), DATEADD(m,-2,@Today))
Value = 2007-03-31 00:00:00.000

More Related Content

PDF
Sql ch 12 - creating database
PPTX
Introduction to sql new
DOCX
Basic sql(oracle) queries
PPT
Chapter 07 ddl_sql
PPTX
DDL,DML,SQL Functions and Joins
Sql ch 12 - creating database
Introduction to sql new
Basic sql(oracle) queries
Chapter 07 ddl_sql
DDL,DML,SQL Functions and Joins

What's hot (20)

PDF
PDF
A Tour to MySQL Commands
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
PDF
Database Systems - SQL - DDL Statements (Chapter 3/2)
PPT
Select To Order By
PDF
Nested Queries Lecture
DOCX
Dbms practical list
DOC
A must Sql notes for beginners
PPT
SQL212.2 Introduction to SQL using Oracle Module 2
PDF
dbms lab manual
PPT
SQL Inteoduction to SQL manipulating of data
PPT
PPTX
Commands of DML in SQL
PDF
4 execution plans
PDF
1 data types
DOC
Dbms lab Manual
PPT
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
PPTX
New Features of SQL Server 2016
A Tour to MySQL Commands
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/2)
Select To Order By
Nested Queries Lecture
Dbms practical list
A must Sql notes for beginners
SQL212.2 Introduction to SQL using Oracle Module 2
dbms lab manual
SQL Inteoduction to SQL manipulating of data
Commands of DML in SQL
4 execution plans
1 data types
Dbms lab Manual
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
New Features of SQL Server 2016
Ad

Similar to My Sql concepts (20)

PPT
Sql Portfolio(March 31)
PDF
Master SQL from Scratch_ Beginners to Advanced 📝.pdf
PDF
sql ppt for students who preparing for sql
PPTX
Stored procedure tuning and optimization t sql
PPT
Greg Lewis SQL Portfolio
PPTX
SQL Server 2012 Best Practices
PDF
SQL Joins and Query Optimization
PPTX
Oracle sql high performance tuning
PDF
2 designing tables
PPT
MS SQL Server.ppt sql
PDF
Sql Commands
PPTX
DOAG: Visual SQL Tuning
PPTX
Sql server
PPTX
Training on Microsoft SQL Server(older version).pptx
PPT
Oracle tips and tricks
PPT
MS SQL Server.ppt
PPTX
SQL Server - Introduction to TSQL
PPT
Sql server introduction to sql server
DOCX
SQL-RDBMS Queries and Question Bank
PPTX
SQL Server Select Topics
Sql Portfolio(March 31)
Master SQL from Scratch_ Beginners to Advanced 📝.pdf
sql ppt for students who preparing for sql
Stored procedure tuning and optimization t sql
Greg Lewis SQL Portfolio
SQL Server 2012 Best Practices
SQL Joins and Query Optimization
Oracle sql high performance tuning
2 designing tables
MS SQL Server.ppt sql
Sql Commands
DOAG: Visual SQL Tuning
Sql server
Training on Microsoft SQL Server(older version).pptx
Oracle tips and tricks
MS SQL Server.ppt
SQL Server - Introduction to TSQL
Sql server introduction to sql server
SQL-RDBMS Queries and Question Bank
SQL Server Select Topics
Ad

More from Pragya Rastogi (20)

PDF
Gl android platform
DOCX
Qtp questions
PPT
Qtp not just for gui anymore
PDF
Qtp tutorial
PDF
Qtp4 bpt
DOCX
Get ro property outputting value
PDF
Bp ttutorial
PPTX
Gl istqb testing fundamentals
PPTX
Gl scrum testing_models
PDF
Java programming basics
PDF
70433 Dumps DB
PDF
DOC
70562-Dumps
PDF
70562 (1)
ZIP
PDF
DOCX
Mobile testingartifacts
PPTX
GL_Web application testing using selenium
PPT
Gl qtp day 3 1
Gl android platform
Qtp questions
Qtp not just for gui anymore
Qtp tutorial
Qtp4 bpt
Get ro property outputting value
Bp ttutorial
Gl istqb testing fundamentals
Gl scrum testing_models
Java programming basics
70433 Dumps DB
70562-Dumps
70562 (1)
Mobile testingartifacts
GL_Web application testing using selenium
Gl qtp day 3 1

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
KodekX | Application Modernization Development
PPTX
sap open course for s4hana steps from ECC to s4
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
MIND Revenue Release Quarter 2 2025 Press Release
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Spectroscopy.pptx food analysis technology
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Understanding_Digital_Forensics_Presentation.pptx
KodekX | Application Modernization Development
sap open course for s4hana steps from ECC to s4
NewMind AI Weekly Chronicles - August'25 Week I
Review of recent advances in non-invasive hemoglobin estimation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Empathic Computing: Creating Shared Understanding
MIND Revenue Release Quarter 2 2025 Press Release

My Sql concepts

  • 1. Some points to consider when choosing Temporary, Global Temp Tables, between them: Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option. Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) Table variables don't participate in transactions, logging or locking. This means they're faster as they don't require the overhead, but conversely you don't get those features. So for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated! Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not. You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront. You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter). Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise. Both table variables and temp tables are stored in tempdb. This means you should be aware of issues such as COLLATION problems if your database collation is different to your server collation; temp tables and table variables will by default inherit the collation of the server, causing problems if you want to compare data in them with data in your database. Global Temp Tables (##tmp) are another type of temp table available to all sessions and users. Retrieving SQL Server Identity Column Values Function SCOPE_IDENTITY:: Returns the last identity value within the current execution scope. SCOPE_IDENTITY is recommended for most scenarios. @@IDENTITY:: Contains the last identity value generated in any table in the current session. @@IDENTITY can be affected by triggers and may not return the identity value that you expect.
  • 2. IDENT_CURRENT:: Returns the last identity value generated for a specific table in any session and any scope. Default Schema is “dbo.” Or define it nVarchar takes double the size defined. It supports Unicode create database Pragya sp_who2 sp_helptext 'sp_who2' use mydb select * from demo1 -------------------------- use Pragya create Table test1 (i int) --permanent create Table #test1 (i int) --temp create Table ##test1 (i int) --global temp Declare test1(i int) Create Table test2(i int) Create Table Customer (CustomerID INT IDENTITY (1000,1) Not Null , Name nvarchar(100) ,CreateDateTime datetime ,CreditLimit decimal(12,5) ) insert into Customer( Name,CreateDateTime, CreditLimit ) values ('test', Getdate(), 1000) select * from Customer Alter table customer Add test nvarchar(200) Alter table Customer drop column test Alter table Customer --not preferred Add Primary Key (CustomerID) Create Table CustPhone (PhoneID int Primary Key, CustomerID int Null, Phone Int) Alter table CustPhone drop constraint FKCustomerID
  • 3. Alter table CustPhone Add Constraint UniqueName Create Table Orders (OrderID INT IDENTITY (1,1) Not Null Check (OrderID between 1 and 1000000) , OrderDate datetime not null, CustomerID integer Foreign Key references Customer(CustomerID)) insert into Orders(OrderDate) values ( Getdate()) Sp_help Orders Four -Part Naming:: Server, Database, Schema, Object Name A Cartesian join will get you a Cartesian product. A Cartesian join is when you join every row of one table to every row of another table. You can also get one by joining every row of a table to every row of itself.
  • 4. SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' and AddressID=' 1069' GO SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' or AddressID=' 1069' SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' or AddressID=' 1069' and AddressType= 'Main Office' Click Display Estimated Executed Plan button on top Retrieve Identity select IDENT_CURRENT('Pragya') select SCOPE_IDENTITY() select @@IDENTITY insert into Customer(Name, CreateDateTime, CreditLimit) values ('Hello', GETDATE(), 5000) sp_help Customer select * from Customer --not preferred -- NON Clustered Primary Key Alter table Orders Add constraint PKCustomer1 Primary Key NONCLUSTERED (OrderID)  Concatenate name SELECT [Title] ,[FirstName] ,[MiddleName] ,[LastName],' '+ isNull (Title, '')+ FirstName +LastName As EmpName FROM [AdventureWorks].[SalesLT].[Customer]
  • 5. --Self Join SELECT emp.empid, emp.title, m.title, from emp E inner join emp M on e.m_id=m.e_id ---Without join SELECT emp.empid, emp.title, m.title, from emp E, emp M where e.m_id=m.e_id Select mgrId, COUNT(empId) from employee group by mngrId -- for null mngr Select EmpID, MngID, Title from Employee where mngrId=3 begin Tran set rowcount 100 -- only 100 rows will get effected like top 100 Update employee set loginId=null --Alter query is faster than update Alter table Employee alter column LoginId nvarchar(256) null Select mgrId, COUNT(empId), COUNT(LoginID), SUM(LoginID) --operator datatype must not b varchar from employee E group by mngrId Select mgrId, COUNT(empId), COUNT(isnull(LoginID, 'a')) from employee E group by mngrId ---------------------------------------------------- --------Mngr total emp count is >20------- Select mgrId, COUNT(EmpId) from Employee E group by mngrId having COUNT(empId)>20 -------------Another way---Derived Table----- Select * from (Select mgrId, COUNT(EmpId) emp from Employee E group by mngrId)AA where emp>20 ---UNION--- select * from SalesLT.Customer a inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID inner join SalesLT.Address b on CA.AddressID = b.AddressID where b.StateProvince= 'washington'
  • 6. --Order byFirstName desc --Cannot use here--At end of query UNION select * from SalesLT.Customer a inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID inner join SalesLT.Address b on CA.AddressID = b.AddressID where b.StateProvince= 'Texas' Order by FirstName asc ---------------EXCEPT----------------------- select * from SalesLT.Customer a inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID inner join SalesLT.Address b on CA.AddressID = b.AddressID where b.StateProvince= 'washington' EXCEPT -- same no of column and same datatype select * from SalesLT.Customer a inner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerID inner join SalesLT.Address b on CA.AddressID = b.AddressID where b.StateProvince= 'Texas' Order by FirstName asc ----------Working with Intersect--------HW-------------------- ======================== ---------UnionAll---------- Create Table t1(i int) insert into t1 select 1 union select 2 union select 3 -- select distinct * from t1 select * from t1 union select * from t1 select * from t1 union all select * from t1 --- select distinct * from t1 select * from t1 -- Expensive performance union select * from t1 select i from t1 group by i ================================================ -------CUrrent Date Time
  • 7. select GETDATE() select LEFT('Pragya', 2) -- first 2 select Right('Pragya', 2) select MONTH(getdate()) select DATEPART(M,getdate()) create table td(dt varchar(10)) Insert into td values('01/01/2011') select * from td select dt, CAST(dt as DATE),CAST(dt as datetime) from td -- first day of month and last day of mnth with date-- HW DECLARE @Today DATETIME SELECT @Today = '8/25/2011' SELECT DATEADD(dd,-(DAY(DATEADD(mm,1,@Today))-1),DATEADD(mm,0,@Today)) ----------------------------------------------------- SELECT DATEADD(dd, -DAY(DATEADD(m,1,@Today)), DATEADD(m,-2,@Today)) Value = 2007-03-31 00:00:00.000