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

What's hot (20)

PDF
Sql
satu2412
 
PDF
A Tour to MySQL Commands
Hikmat Dhamee
 
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
PDF
Database Systems - SQL - DDL Statements (Chapter 3/2)
Vidyasagar Mundroy
 
PPT
Select To Order By
Krizia Capacio
 
PDF
Nested Queries Lecture
Felipe Costa
 
DOCX
Dbms practical list
RajSingh734307
 
DOC
A must Sql notes for beginners
Ram Sagar Mourya
 
PPT
SQL212.2 Introduction to SQL using Oracle Module 2
Dan D'Urso
 
PDF
dbms lab manual
stalinjothi
 
PPT
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
PPT
Sql
jyothislides
 
PPTX
Commands of DML in SQL
Ashish Gaurkhede
 
PDF
4 execution plans
Ram Kedem
 
PDF
1 data types
Ram Kedem
 
DOC
Dbms lab Manual
Vivek Kumar Sinha
 
PPT
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
PPTX
New Features of SQL Server 2016
Mir Mahmood
 
A Tour to MySQL Commands
Hikmat Dhamee
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Vidyasagar Mundroy
 
Select To Order By
Krizia Capacio
 
Nested Queries Lecture
Felipe Costa
 
Dbms practical list
RajSingh734307
 
A must Sql notes for beginners
Ram Sagar Mourya
 
SQL212.2 Introduction to SQL using Oracle Module 2
Dan D'Urso
 
dbms lab manual
stalinjothi
 
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
Commands of DML in SQL
Ashish Gaurkhede
 
4 execution plans
Ram Kedem
 
1 data types
Ram Kedem
 
Dbms lab Manual
Vivek Kumar Sinha
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
New Features of SQL Server 2016
Mir Mahmood
 

Similar to My Sql concepts (20)

PPT
Sql Portfolio(March 31)
iceolated
 
PDF
Master SQL from Scratch_ Beginners to Advanced 📝.pdf
gobilgobil
 
PDF
sql ppt for students who preparing for sql
bharatjanadharwarud
 
PPTX
Stored procedure tuning and optimization t sql
nishantdavid9
 
PPT
Greg Lewis SQL Portfolio
gregmlewis
 
PPTX
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
PDF
SQL Joins and Query Optimization
Brian Gallagher
 
PPTX
Oracle sql high performance tuning
Guy Harrison
 
PDF
2 designing tables
Ram Kedem
 
PPT
MS SQL Server.ppt sql
NaheedBaloxh
 
PDF
Sql Commands
Sachin MK
 
PPTX
DOAG: Visual SQL Tuning
Kyle Hailey
 
PPTX
Sql server
Fajar Baskoro
 
PPTX
Training on Microsoft SQL Server(older version).pptx
naibedyakar00
 
PPT
Oracle tips and tricks
Yanli Liu
 
PPT
MS SQL Server.ppt
QuyVo27
 
PPTX
SQL Server - Introduction to TSQL
Peter Gfader
 
PPT
Sql server introduction to sql server
Vibrant Technologies & Computers
 
DOCX
SQL-RDBMS Queries and Question Bank
Md Mudassir
 
PPTX
SQL Server Select Topics
Jay Coskey
 
Sql Portfolio(March 31)
iceolated
 
Master SQL from Scratch_ Beginners to Advanced 📝.pdf
gobilgobil
 
sql ppt for students who preparing for sql
bharatjanadharwarud
 
Stored procedure tuning and optimization t sql
nishantdavid9
 
Greg Lewis SQL Portfolio
gregmlewis
 
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
SQL Joins and Query Optimization
Brian Gallagher
 
Oracle sql high performance tuning
Guy Harrison
 
2 designing tables
Ram Kedem
 
MS SQL Server.ppt sql
NaheedBaloxh
 
Sql Commands
Sachin MK
 
DOAG: Visual SQL Tuning
Kyle Hailey
 
Sql server
Fajar Baskoro
 
Training on Microsoft SQL Server(older version).pptx
naibedyakar00
 
Oracle tips and tricks
Yanli Liu
 
MS SQL Server.ppt
QuyVo27
 
SQL Server - Introduction to TSQL
Peter Gfader
 
Sql server introduction to sql server
Vibrant Technologies & Computers
 
SQL-RDBMS Queries and Question Bank
Md Mudassir
 
SQL Server Select Topics
Jay Coskey
 
Ad

More from Pragya Rastogi (20)

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

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

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