SlideShare a Scribd company logo
1 of 17
Introduction to AdvancedIntroduction to Advanced
SQL Concepts - CheckingSQL Concepts - Checking
of Constraintsof Constraints
Check ConstraintsCheck Constraints
• Limits values that may appear in components for
some attributes
• Expressed as either
o Constraint on attribute in definition of its relation’s schema
o Constraint on a tuple as a whole; part of relation schema, but not
associated with individual attributes
Attribute CheckAttribute Check
ConstraintConstraint
Simple Case:
• Assume in table Studio we have declaration:
presC# INT REFERENCES MovieExec(cert#) NOT NULL
• Cannot use set-null policy to fix referential int. violation
General Case:
• Attached to attribute declaration
• Keyword CHECK followed by any condition that could follow
WHERE clause in SQL query
o Checked whenever any tuple gets a new value for this attribute (incl.
on inserts of new tuples)
o Not checked when modification does not change the value of the
attribute to which CHECK belongs
ExampleExample
CREATE TABLE MovieStar (
…
gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)),
…
);
Condition being checked can be anything that could
follow WHERE in SFW query
ExampleExample
• Can the following attribute-based CHECK constraint
simulate a referential integrity constraint?
CREATE TABLE Studio (
Name CHAR(30) PRIMARY KEY,
Address VARCHAR(255),
presC# INT CHECK
(presC# IN (SELECT cert# FROM MovieExec));
• No, updates to MovieExec are invisible to the
above CHECK constraint
Tuple-Based CheckTuple-Based Check
ConstraintConstraint• Add a tuple-based CHECK constraint to MovieStar
schema that prevents the insertion of male stars
whose name begin with “Ms.”
o Checked after insertions and updates to tuples of the
relation on which it is defined
CREATE TABLE MovieStar (
Name CHAR(30) PRIMARY KEY,
Address VARCHAR(255),
Gender CHAR(1),
Birthdate DATE,
CHECK (gender <> ‘M’ OR name NOT LIKE ‘Ms.%’)
//forbid the insertion of tuples that satisfy multiple conditions,
namely “male and name starts with ‘Ms.’ ”
//equivalent to the OR of the negation of the same terms
AssertionsAssertions
• More powerful mechanism of constraining
values in database are part of database
schema
o First-class database citizens like views or relations
• Assertion is a boolean-valued SQL expression
that must be true at all times
o Easy to state for DB implementer, simply state
what must be true
o Harder to implement efficiently since DBMS must
deduce whether or not a given database
modification could affect truth of assertion
ExampleExample
• Express that no one can become president of
a studio unless net worth greater than $10M
MovieExec(name, address, cert#, netWorth)
Studio(name, address, presC#)
CREATE ASSERTION RichPres CHECK
(NOT EXISTS
(SELECT *
FROM Studio, MovieExec
WHERE presC# = cert# AND netWorth < 10000000)
)
);
• Can this be simulated with tuple-based CHECK
constraints?
Using a Tuple-BasedUsing a Tuple-Based
CHECKCHECKCREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES MovieExec(cert#),
CHECK (presc# NOT IN
(SELECT cert#
FROM MovieExec
WHERE netWorth < 10000000)
)
);
ExampleExample
• Assert that the total length of all movies by a given
studio shall not exceed 10,000 minutes
Movie(title,year,length,inColor,studioName,producerC#)
CREATE ASSERTION SumLength CHECK
(10000 >= ALL
(SELECT SUM(length)FROM Movie
GROUP BY StudioName));
 Is the effect the same as that of the following tuple-based CHECK:
CHECK (10000 >= ALL
(SELECT SUM(length) FROM Movie
GROUP BY studioName));
TriggersTriggers
• Aka “event-condition-action” (ECA) rules
• Three important facts about triggers
o Only awakened when certain events, specified by db
programmer, occur
o Executing triggers involves testing a condition first
o If condition satisfied, action of trigger is executed
ExampleExample• Write trigger to prevent any attempt to lower networth of movie exec
MovieExec(name,address,cert#,netWorth)
CREATE TRIGGER NetWorthTrigger
AFTER UPDATE OF netWorth ON MovieExec
REFERENCING
OLD ROW AS OldTuple,
NEW ROW AS NewTuple,
FOR EACH ROW
WHEN (OldTuple.netWorth > NewTuple.netWorth)
UPDATE MovieExec
SET netWorth = OldTuple.netWorth
WHERE cert# = NewTuple.cert#;
Event
Condition
Action
CommentsComments
• The action rule may be executed BEFORE or AFTER the event
o If before, when clause is tested before triggering event
• Besides update, other triggering events are insert and delete
• When clause is optional
• The action may contain any number of SQL statements,
separated by BEGIN … END
• If triggering event is insert, may use a NEW ROW AS clause to
give name to inserted row
o Conversely, may use OLD ROW AS in case of a deletion
More CommentsMore Comments
• If we omit FOR EACH ROW clause, trigger becomes
statement-level trigger (as opposed to row-level trigger)
• Statement-level trigger is executed ONCE no matter how
many rows it actually effects
o Cannot refer to old and new tuples
• However, both types of triggers can access old and new set
of tuples
o OLD TABLE AS … (i.e., deleted tuples or old versions of
updated tuples)
o NEW TABLE AS … (i.e., inserted tuples or new versions of
updated tuples)
ExampleExample
• Prevent average net worth of movie executives to drop below $500K
• Violation on insert, update, delete => need three triggers!
MovieExec(name,address,cert#,netWorth)
CREATE TRIGGER AvgNetWorthTrigger
AFTER UPDATE OF netWorth ON MovieExec
REFERENCING
OLD TABLE AS OldStuff,
NEW TABLE AS NewStuff
FOR EACH STATEMENT
WHEN (500000 > (SELECT AVG(netWorth) FROM MovieExec))
BEGIN
DELETE FROM MovieExec
WHERE (name,address,cert#,netWorth) IN NewStuff;
INSERT INTO MovieExec
(SELECT * FROM OldStuff);
END;
ThankThank You !!!You !!!
For More Information click below link:
Follow Us on:
http://vibranttechnologies.co.in/sql-classes-in-mumbai.html

More Related Content

What's hot

Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 

What's hot (15)

JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
 
Effective Readable unit testing with junit5
Effective Readable unit testing with junit5Effective Readable unit testing with junit5
Effective Readable unit testing with junit5
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Mxunit
MxunitMxunit
Mxunit
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Scala test
Scala testScala test
Scala test
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKE
 
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
 
Anatomy of a Gem: Bane
Anatomy of a Gem: BaneAnatomy of a Gem: Bane
Anatomy of a Gem: Bane
 

Viewers also liked

wallplate layout
wallplate layoutwallplate layout
wallplate layout
april webb
 
Grafico semanal del ibex 35 para el 11 05 2012
Grafico semanal del ibex 35 para el 11 05 2012Grafico semanal del ibex 35 para el 11 05 2012
Grafico semanal del ibex 35 para el 11 05 2012
Experiencia Trading
 
Case Study - Windows Azure
Case Study - Windows AzureCase Study - Windows Azure
Case Study - Windows Azure
msgtscindia
 
Exposicion competencias
Exposicion competenciasExposicion competencias
Exposicion competencias
dckyam
 
Lo malo competencias
Lo malo competenciasLo malo competencias
Lo malo competencias
dckyam
 
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
SQL Server 2008 R2 - Developing Rich Reporting Solutions PresentationSQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
Microsoft Private Cloud
 
Lg e510 series batería at www baterias-portatil-es (1)
Lg e510 series batería at www baterias-portatil-es (1)Lg e510 series batería at www baterias-portatil-es (1)
Lg e510 series batería at www baterias-portatil-es (1)
batteryes
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
Logan Palanisamy
 

Viewers also liked (17)

Oracle Query Tuning Tips - Get it Right the First Time
Oracle Query Tuning Tips - Get it Right the First TimeOracle Query Tuning Tips - Get it Right the First Time
Oracle Query Tuning Tips - Get it Right the First Time
 
Really using Oracle analytic SQL functions
Really using Oracle analytic SQL functionsReally using Oracle analytic SQL functions
Really using Oracle analytic SQL functions
 
wallplate layout
wallplate layoutwallplate layout
wallplate layout
 
Inicializar windows 8
Inicializar windows 8Inicializar windows 8
Inicializar windows 8
 
Grafico semanal del ibex 35 para el 11 05 2012
Grafico semanal del ibex 35 para el 11 05 2012Grafico semanal del ibex 35 para el 11 05 2012
Grafico semanal del ibex 35 para el 11 05 2012
 
Scribd
ScribdScribd
Scribd
 
Case Study - Windows Azure
Case Study - Windows AzureCase Study - Windows Azure
Case Study - Windows Azure
 
Exposicion competencias
Exposicion competenciasExposicion competencias
Exposicion competencias
 
Lo malo competencias
Lo malo competenciasLo malo competencias
Lo malo competencias
 
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
SQL Server 2008 R2 - Developing Rich Reporting Solutions PresentationSQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
 
Business Strategy - Blue Ocean Strategy
Business Strategy - Blue Ocean StrategyBusiness Strategy - Blue Ocean Strategy
Business Strategy - Blue Ocean Strategy
 
Lg e510 series batería at www baterias-portatil-es (1)
Lg e510 series batería at www baterias-portatil-es (1)Lg e510 series batería at www baterias-portatil-es (1)
Lg e510 series batería at www baterias-portatil-es (1)
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
 
Building Applications for SQL Server 2008
Building Applications for SQL Server 2008Building Applications for SQL Server 2008
Building Applications for SQL Server 2008
 
Remote DBA Experts SQL Server 2008 New Features
Remote DBA Experts SQL Server 2008 New FeaturesRemote DBA Experts SQL Server 2008 New Features
Remote DBA Experts SQL Server 2008 New Features
 
Amy Carmichael, Lady Christian missionary in Indian Christian Missionary in ...
Amy Carmichael, Lady Christian missionary in Indian Christian  Missionary in ...Amy Carmichael, Lady Christian missionary in Indian Christian  Missionary in ...
Amy Carmichael, Lady Christian missionary in Indian Christian Missionary in ...
 
Tecnologias na escola: hábitos, oportunidades e riscos
Tecnologias na escola: hábitos, oportunidades e riscosTecnologias na escola: hábitos, oportunidades e riscos
Tecnologias na escola: hábitos, oportunidades e riscos
 

Similar to SQL- Introduction to advanced sql concepts

A testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-ServerA testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-Server
elliando dias
 

Similar to SQL- Introduction to advanced sql concepts (20)

Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusion
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Adding unit tests with tSQLt to the database deployment pipeline
Adding unit tests with tSQLt to the database deployment pipelineAdding unit tests with tSQLt to the database deployment pipeline
Adding unit tests with tSQLt to the database deployment pipeline
 
Adding unit tests with tSQLt to the database deployment pipeline
 Adding unit tests with tSQLt to the database deployment pipeline Adding unit tests with tSQLt to the database deployment pipeline
Adding unit tests with tSQLt to the database deployment pipeline
 
Adding unit tests to the database deployment pipeline
Adding unit tests to the database deployment pipelineAdding unit tests to the database deployment pipeline
Adding unit tests to the database deployment pipeline
 
Adding unit tests to the database deployment pipeline
Adding unit tests to the database deployment pipelineAdding unit tests to the database deployment pipeline
Adding unit tests to the database deployment pipeline
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Harton-Presentation
Harton-PresentationHarton-Presentation
Harton-Presentation
 
Data integrity
Data integrityData integrity
Data integrity
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
A testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-ServerA testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-Server
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding Guidelines
 
Sva.pdf
Sva.pdfSva.pdf
Sva.pdf
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
chap 9 dbms.ppt
chap 9 dbms.pptchap 9 dbms.ppt
chap 9 dbms.ppt
 

More from Vibrant Technologies & Computers

More from Vibrant Technologies & Computers (20)

Buisness analyst business analysis overview ppt 5
Buisness analyst business analysis overview ppt 5Buisness analyst business analysis overview ppt 5
Buisness analyst business analysis overview ppt 5
 
SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables  SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
SQL- Introduction to SQL database
SQL- Introduction to SQL database SQL- Introduction to SQL database
SQL- Introduction to SQL database
 
ITIL - introduction to ITIL
ITIL - introduction to ITILITIL - introduction to ITIL
ITIL - introduction to ITIL
 
Salesforce - Introduction to Security & Access
Salesforce -  Introduction to Security & Access Salesforce -  Introduction to Security & Access
Salesforce - Introduction to Security & Access
 
Data ware housing- Introduction to olap .
Data ware housing- Introduction to  olap .Data ware housing- Introduction to  olap .
Data ware housing- Introduction to olap .
 
Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.
 
Data ware housing- Introduction to data ware housing
Data ware housing- Introduction to data ware housingData ware housing- Introduction to data ware housing
Data ware housing- Introduction to data ware housing
 
Salesforce - classification of cloud computing
Salesforce - classification of cloud computingSalesforce - classification of cloud computing
Salesforce - classification of cloud computing
 
Salesforce - cloud computing fundamental
Salesforce - cloud computing fundamentalSalesforce - cloud computing fundamental
Salesforce - cloud computing fundamental
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
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- Introduction to SQL Set Operations
SQL- Introduction to SQL Set OperationsSQL- Introduction to SQL Set Operations
SQL- Introduction to SQL Set Operations
 
Sas - Introduction to designing the data mart
Sas - Introduction to designing the data martSas - Introduction to designing the data mart
Sas - Introduction to designing the data mart
 
Sas - Introduction to working under change management
Sas - Introduction to working under change managementSas - Introduction to working under change management
Sas - Introduction to working under change management
 
SAS - overview of SAS
SAS - overview of SASSAS - overview of SAS
SAS - overview of SAS
 
Teradata - Architecture of Teradata
Teradata - Architecture of TeradataTeradata - Architecture of Teradata
Teradata - Architecture of Teradata
 
Teradata - Restoring Data
Teradata - Restoring Data Teradata - Restoring Data
Teradata - Restoring Data
 
Datastage database design and data modeling ppt 4
Datastage database design and data modeling ppt 4Datastage database design and data modeling ppt 4
Datastage database design and data modeling ppt 4
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
panagenda
 

Recently uploaded (20)

Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
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...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
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
 

SQL- Introduction to advanced sql concepts

  • 1.
  • 2. Introduction to AdvancedIntroduction to Advanced SQL Concepts - CheckingSQL Concepts - Checking of Constraintsof Constraints
  • 3. Check ConstraintsCheck Constraints • Limits values that may appear in components for some attributes • Expressed as either o Constraint on attribute in definition of its relation’s schema o Constraint on a tuple as a whole; part of relation schema, but not associated with individual attributes
  • 4. Attribute CheckAttribute Check ConstraintConstraint Simple Case: • Assume in table Studio we have declaration: presC# INT REFERENCES MovieExec(cert#) NOT NULL • Cannot use set-null policy to fix referential int. violation General Case: • Attached to attribute declaration • Keyword CHECK followed by any condition that could follow WHERE clause in SQL query o Checked whenever any tuple gets a new value for this attribute (incl. on inserts of new tuples) o Not checked when modification does not change the value of the attribute to which CHECK belongs
  • 5. ExampleExample CREATE TABLE MovieStar ( … gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)), … ); Condition being checked can be anything that could follow WHERE in SFW query
  • 6. ExampleExample • Can the following attribute-based CHECK constraint simulate a referential integrity constraint? CREATE TABLE Studio ( Name CHAR(30) PRIMARY KEY, Address VARCHAR(255), presC# INT CHECK (presC# IN (SELECT cert# FROM MovieExec)); • No, updates to MovieExec are invisible to the above CHECK constraint
  • 7. Tuple-Based CheckTuple-Based Check ConstraintConstraint• Add a tuple-based CHECK constraint to MovieStar schema that prevents the insertion of male stars whose name begin with “Ms.” o Checked after insertions and updates to tuples of the relation on which it is defined CREATE TABLE MovieStar ( Name CHAR(30) PRIMARY KEY, Address VARCHAR(255), Gender CHAR(1), Birthdate DATE, CHECK (gender <> ‘M’ OR name NOT LIKE ‘Ms.%’) //forbid the insertion of tuples that satisfy multiple conditions, namely “male and name starts with ‘Ms.’ ” //equivalent to the OR of the negation of the same terms
  • 8. AssertionsAssertions • More powerful mechanism of constraining values in database are part of database schema o First-class database citizens like views or relations • Assertion is a boolean-valued SQL expression that must be true at all times o Easy to state for DB implementer, simply state what must be true o Harder to implement efficiently since DBMS must deduce whether or not a given database modification could affect truth of assertion
  • 9. ExampleExample • Express that no one can become president of a studio unless net worth greater than $10M MovieExec(name, address, cert#, netWorth) Studio(name, address, presC#) CREATE ASSERTION RichPres CHECK (NOT EXISTS (SELECT * FROM Studio, MovieExec WHERE presC# = cert# AND netWorth < 10000000) ) ); • Can this be simulated with tuple-based CHECK constraints?
  • 10. Using a Tuple-BasedUsing a Tuple-Based CHECKCHECKCREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# INT REFERENCES MovieExec(cert#), CHECK (presc# NOT IN (SELECT cert# FROM MovieExec WHERE netWorth < 10000000) ) );
  • 11. ExampleExample • Assert that the total length of all movies by a given studio shall not exceed 10,000 minutes Movie(title,year,length,inColor,studioName,producerC#) CREATE ASSERTION SumLength CHECK (10000 >= ALL (SELECT SUM(length)FROM Movie GROUP BY StudioName));  Is the effect the same as that of the following tuple-based CHECK: CHECK (10000 >= ALL (SELECT SUM(length) FROM Movie GROUP BY studioName));
  • 12. TriggersTriggers • Aka “event-condition-action” (ECA) rules • Three important facts about triggers o Only awakened when certain events, specified by db programmer, occur o Executing triggers involves testing a condition first o If condition satisfied, action of trigger is executed
  • 13. ExampleExample• Write trigger to prevent any attempt to lower networth of movie exec MovieExec(name,address,cert#,netWorth) CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD ROW AS OldTuple, NEW ROW AS NewTuple, FOR EACH ROW WHEN (OldTuple.netWorth > NewTuple.netWorth) UPDATE MovieExec SET netWorth = OldTuple.netWorth WHERE cert# = NewTuple.cert#; Event Condition Action
  • 14. CommentsComments • The action rule may be executed BEFORE or AFTER the event o If before, when clause is tested before triggering event • Besides update, other triggering events are insert and delete • When clause is optional • The action may contain any number of SQL statements, separated by BEGIN … END • If triggering event is insert, may use a NEW ROW AS clause to give name to inserted row o Conversely, may use OLD ROW AS in case of a deletion
  • 15. More CommentsMore Comments • If we omit FOR EACH ROW clause, trigger becomes statement-level trigger (as opposed to row-level trigger) • Statement-level trigger is executed ONCE no matter how many rows it actually effects o Cannot refer to old and new tuples • However, both types of triggers can access old and new set of tuples o OLD TABLE AS … (i.e., deleted tuples or old versions of updated tuples) o NEW TABLE AS … (i.e., inserted tuples or new versions of updated tuples)
  • 16. ExampleExample • Prevent average net worth of movie executives to drop below $500K • Violation on insert, update, delete => need three triggers! MovieExec(name,address,cert#,netWorth) CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (500000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (name,address,cert#,netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END;
  • 17. ThankThank You !!!You !!! For More Information click below link: Follow Us on: http://vibranttechnologies.co.in/sql-classes-in-mumbai.html