SlideShare a Scribd company logo
1 of 7
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)

Sql
SqlSql
Sql
 
A Tour to MySQL Commands
A Tour to MySQL CommandsA Tour to MySQL Commands
A Tour to MySQL Commands
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Dbms practical list
Dbms practical listDbms practical list
Dbms practical list
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
Sql
SqlSql
Sql
 
Commands of DML in SQL
Commands of DML in SQLCommands of DML in SQL
Commands of DML in SQL
 
4 execution plans
4 execution plans4 execution plans
4 execution plans
 
1 data types
1 data types1 data types
1 data types
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
 

Similar to My Sql concepts

Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlnishantdavid9
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Achmad Solichin
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).pptarjun431527
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2Dan D'Urso
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfFederico Razzoli
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancementsinfusiondev
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 

Similar to My Sql concepts (20)

Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Les09
Les09Les09
Les09
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 
Chap 7
Chap 7Chap 7
Chap 7
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdf
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancements
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
 
Less08 Schema
Less08 SchemaLess08 Schema
Less08 Schema
 

More from Pragya Rastogi (20)

Gl android platform
Gl android platformGl android platform
Gl android platform
 
Qtp questions
Qtp questionsQtp questions
Qtp questions
 
Qtp not just for gui anymore
Qtp   not just for gui anymoreQtp   not just for gui anymore
Qtp not just for gui anymore
 
Qtp tutorial
Qtp tutorialQtp tutorial
Qtp tutorial
 
Qtp4 bpt
Qtp4 bptQtp4 bpt
Qtp4 bpt
 
Get ro property outputting value
Get ro property outputting valueGet ro property outputting value
Get ro property outputting value
 
Bp ttutorial
Bp ttutorialBp ttutorial
Bp ttutorial
 
Gl istqb testing fundamentals
Gl istqb testing fundamentalsGl istqb testing fundamentals
Gl istqb testing fundamentals
 
Gl scrum testing_models
Gl scrum testing_modelsGl scrum testing_models
Gl scrum testing_models
 
Oops
OopsOops
Oops
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
70433 Dumps DB
70433 Dumps DB70433 Dumps DB
70433 Dumps DB
 
70 433
70 43370 433
70 433
 
70562-Dumps
70562-Dumps70562-Dumps
70562-Dumps
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
32916
3291632916
32916
 
70 562
70 56270 562
70 562
 
Mobile testingartifacts
Mobile testingartifactsMobile testingartifacts
Mobile testingartifacts
 
GL_Web application testing using selenium
GL_Web application testing using seleniumGL_Web application testing using selenium
GL_Web application testing using selenium
 
Gl qtp day 3 1
Gl qtp day 3   1Gl qtp day 3   1
Gl qtp day 3 1
 

Recently uploaded

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

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