SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
Home Contents




Constraints

In this part of the SQLite tutorial, we will work with constraints


Constraints are placed on columns. They limit the data, that can be inserted into tables.


We have the following constraints:


    •   NOT NULL

    •   UNIQUE

    •   PRIMARY KEY

    •   FOREIGN KEY

    •   CHECK

    •   DEFAULT




NOT NULL constraint

A column with a NOT NULL constraint, cannot have NULL values.




  sqlite> CREATE TABLE People(Id integer, LastName text NOT NULL,




                                      FirstName text NOT NULL, City text);


We create two columns with NOT NULL constraints.




  sqlite> INSERT INTO People VALUES(1, 'Hanks', 'Robert', 'New York');




  sqlite> INSERT INTO People VALUES(2, NULL, 'Marianne', 'Chicago');




  SQL error: People.LastName may not be NULL


The first SELECT statement is executed OK, the second one fails. The SQL error says, the LastName

column may not be NULL.
UNIQUE constraint

The UNIQUE constraint ensures, that all data are unique in a column.




  sqlite> CREATE TABLE Brands(Id integer, BrandName text UNIQUE);


Here we create a table Brands. The BrandName column is set to be UNIQUE. There cannot be two

brands with a same name.




  sqlite> INSERT INTO Brands VALUES(1, 'Coca Cola');




  sqlite> INSERT INTO Brands VALUES(2, 'Pepsi');




  sqlite> INSERT INTO Brands VALUES(3, 'Pepsi');




  SQL error: column BrandName is not unique


We get an SQL error 'column BrandName is not unique'. There can only be one Pepsi.


Note that a PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.




Primary key

The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more

UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the

database tables. Primary keys are unique ids. We use them to refer to table rows. Primary keys become

foreign keys in other tables, when creating relations among tables. Due to to a 'long-standing coding

oversight', primary keys can be NULL in SQLite. This is not the case with other databases.




  sqlite> CREATE TABLE Brands(Id integer PRIMARY KEY, BrandName text);


The Id column of the Brands table becomes a primary key.




  sqlite> INSERT INTO Brands(BrandName) VALUES('Coca Cola');
sqlite> INSERT INTO Brands(BrandName) VALUES('Pepsi');




  sqlite> INSERT INTO Brands(BrandName) VALUES('Sun');




  sqlite> INSERT INTO Brands(BrandName) VALUES('Oracle');




  sqlite> SELECT * FROM Brands;




  Id             BrandName




  ----------     ----------




  1              Coca Cola




  2              Pepsi




  3              Sun




  4              Oracle


In SQLIte if a column is integer and primary key, it is also autoincrement.




Foreign key

A FOREIGN KEY in one table points to a PRIMARY KEY in another table. It is a referential constraint

between two tables. The foreign key identifies a column or a set of columns in one (referencing) table

that refers to a column or set of columns in another (referenced) table.


We will be demonstrating this constraint on two tables. Authors and Books.




  CREATE TABLE Authors(AuthorId integer PRIMARY KEY, Name text);
Here we create the Authors table.




  CREATE TABLE Books(BookId integer PRIMARY KEY, title text, AuthorId integer,




                          FOREIGN KEY(AuthorId) REFERENCES Authors(AuthorId));


We create the Books table. Here we have an AuthorId column name, which acts as a foreign key. It

references to the primary key of the Authors table.


In SQLite, foreign keys are not enforced by default. To enforce the foreign key, the library must be

compiled with proper flags, it must be at least version 3.6.19 and the pragma key for foreign keys must

be set.


What would foreign key enforcement mean in our example? We could not insert a row into the Books

table with an AuthorId, which is not present in Authors book.




Check constraint

A CHECK constraint is a condition that defines valid data of a relational database. The check is

executed when adding or updating data to the column in question.




  sqlite> .schema Orders




  CREATE TABLE Orders(Id integer PRIMARY KEY, OrderPrice integer
  CHECK(OrderPrice>0),




                           Customer text);


We look at the definition of the Orders table. We see a CHECK constraint imposed on the OrderPrice

column. Logically, the price of an order must be a positive value.




  sqlite> INSERT INTO Orders(OrderPrice, Customer) VALUES(-10, 'Johnson');




  SQL error: constraint failed
If we try to insert an invalid value, we get an error saying: 'constraint failed'.




Default constraint

The DEFAULT constraint inserts a default value into the column, if no value is available.




  sqlite> CREATE TABLE Hotels(Id integer PRIMARY KEY, Name text,




                                       City text DEFAULT 'not available');


To demonstrate the DEFAULT constraint, we create a Hotels table. The City column has a default 'not

available' value.




  sqlite> INSERT INTO Hotels(Name, City) VALUES('Kyjev', 'Bratislava');




  sqlite> INSERT INTO Hotels(Name) VALUES('Slovan');




  sqlite> SELECT * FROM Hotels;




  Id     Name       City




  ---    -------    --------------




  1      Kyjev      Bratislava




  2      Slovan     not available


In the first statement, we provide both hotel name and city name. In the second statement, we provide

only the hotel name. SQLite puts the default value there, the 'not available' text.


In this part of the SQLite tutorial, we have worked with views, triggers and transactions in SQLite.

Más contenido relacionado

La actualidad más candente

06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinctBishal Ghimire
 
Avinash database
Avinash databaseAvinash database
Avinash databaseavibmas
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)Tâm
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setupvkeeton
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1Iblesoft
 
Oracle apps financial online training
Oracle apps financial online trainingOracle apps financial online training
Oracle apps financial online trainingmagnifics
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
How to create Xpath, CSS, DOM for your Selenium script
How to create Xpath, CSS, DOM  for your Selenium scriptHow to create Xpath, CSS, DOM  for your Selenium script
How to create Xpath, CSS, DOM for your Selenium scriptRakesh Hansalia
 
mysql 1st. act.
mysql 1st. act.mysql 1st. act.
mysql 1st. act.von lozano
 
20150730 Sql AutoCommannotator - sac v2
20150730  Sql AutoCommannotator - sac v220150730  Sql AutoCommannotator - sac v2
20150730 Sql AutoCommannotator - sac v2Sharon Liu
 
Let's build a website with Dreamweaver I
Let's build a website with Dreamweaver ILet's build a website with Dreamweaver I
Let's build a website with Dreamweaver INarayan Kumar
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1Sharon Liu
 

La actualidad más candente (20)

06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinct
 
DBI
DBIDBI
DBI
 
Sql commands
Sql commandsSql commands
Sql commands
 
Avinash database
Avinash databaseAvinash database
Avinash database
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1
 
Sql injections
Sql injectionsSql injections
Sql injections
 
SQL report
SQL reportSQL report
SQL report
 
MYSQL
MYSQLMYSQL
MYSQL
 
Higher SQL
Higher SQLHigher SQL
Higher SQL
 
Oracle apps financial online training
Oracle apps financial online trainingOracle apps financial online training
Oracle apps financial online training
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Learn plsql
Learn plsqlLearn plsql
Learn plsql
 
How to create Xpath, CSS, DOM for your Selenium script
How to create Xpath, CSS, DOM  for your Selenium scriptHow to create Xpath, CSS, DOM  for your Selenium script
How to create Xpath, CSS, DOM for your Selenium script
 
mysql 1st. act.
mysql 1st. act.mysql 1st. act.
mysql 1st. act.
 
20150730 Sql AutoCommannotator - sac v2
20150730  Sql AutoCommannotator - sac v220150730  Sql AutoCommannotator - sac v2
20150730 Sql AutoCommannotator - sac v2
 
Let's build a website with Dreamweaver I
Let's build a website with Dreamweaver ILet's build a website with Dreamweaver I
Let's build a website with Dreamweaver I
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
MY SQL
MY SQLMY SQL
MY SQL
 

Similar a Constraints

Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating databaseMukesh Tekwani
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09Hassen Poreya
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developerAhsan Kabir
 
Entigrity constraint
Entigrity constraintEntigrity constraint
Entigrity constraintsuman kumar
 
MQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxMQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxlemonchoos
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview QuestionsBest SEO Tampa
 
Sql integrity constraints
Sql integrity constraintsSql integrity constraints
Sql integrity constraintsVivek Singh
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2Raj vardhan
 
Sql Commands
Sql CommandsSql Commands
Sql CommandsSachin MK
 
Using mySQL in PHP
Using mySQL in PHPUsing mySQL in PHP
Using mySQL in PHPMike Crabb
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginnersISsoft
 
RDBMS Lab03 applying constraints (UIU)
RDBMS Lab03 applying constraints (UIU)RDBMS Lab03 applying constraints (UIU)
RDBMS Lab03 applying constraints (UIU)Muhammad T Q Nafis
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfDraguClaudiu
 

Similar a Constraints (20)

Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
SQL & PLSQL
SQL & PLSQLSQL & PLSQL
SQL & PLSQL
 
Entigrity constraint
Entigrity constraintEntigrity constraint
Entigrity constraint
 
MQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxMQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptx
 
Sql basics
Sql basicsSql basics
Sql basics
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview Questions
 
Sql integrity constraints
Sql integrity constraintsSql integrity constraints
Sql integrity constraints
 
Sql commands
Sql commandsSql commands
Sql commands
 
Integrity and security
Integrity and securityIntegrity and security
Integrity and security
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Bn1017 a demo rdbms
Bn1017 a demo  rdbmsBn1017 a demo  rdbms
Bn1017 a demo rdbms
 
Sql Commands
Sql CommandsSql Commands
Sql Commands
 
Using mySQL in PHP
Using mySQL in PHPUsing mySQL in PHP
Using mySQL in PHP
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginners
 
RDBMS Lab03 applying constraints (UIU)
RDBMS Lab03 applying constraints (UIU)RDBMS Lab03 applying constraints (UIU)
RDBMS Lab03 applying constraints (UIU)
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 

Último

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 
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
 
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
 
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
 
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.pptxRustici Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
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 Takeoffsammart93
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 

Último (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
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...
 
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...
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 

Constraints

  • 1. Home Contents Constraints In this part of the SQLite tutorial, we will work with constraints Constraints are placed on columns. They limit the data, that can be inserted into tables. We have the following constraints: • NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK • DEFAULT NOT NULL constraint A column with a NOT NULL constraint, cannot have NULL values. sqlite> CREATE TABLE People(Id integer, LastName text NOT NULL, FirstName text NOT NULL, City text); We create two columns with NOT NULL constraints. sqlite> INSERT INTO People VALUES(1, 'Hanks', 'Robert', 'New York'); sqlite> INSERT INTO People VALUES(2, NULL, 'Marianne', 'Chicago'); SQL error: People.LastName may not be NULL The first SELECT statement is executed OK, the second one fails. The SQL error says, the LastName column may not be NULL.
  • 2. UNIQUE constraint The UNIQUE constraint ensures, that all data are unique in a column. sqlite> CREATE TABLE Brands(Id integer, BrandName text UNIQUE); Here we create a table Brands. The BrandName column is set to be UNIQUE. There cannot be two brands with a same name. sqlite> INSERT INTO Brands VALUES(1, 'Coca Cola'); sqlite> INSERT INTO Brands VALUES(2, 'Pepsi'); sqlite> INSERT INTO Brands VALUES(3, 'Pepsi'); SQL error: column BrandName is not unique We get an SQL error 'column BrandName is not unique'. There can only be one Pepsi. Note that a PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Primary key The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique ids. We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to to a 'long-standing coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases. sqlite> CREATE TABLE Brands(Id integer PRIMARY KEY, BrandName text); The Id column of the Brands table becomes a primary key. sqlite> INSERT INTO Brands(BrandName) VALUES('Coca Cola');
  • 3. sqlite> INSERT INTO Brands(BrandName) VALUES('Pepsi'); sqlite> INSERT INTO Brands(BrandName) VALUES('Sun'); sqlite> INSERT INTO Brands(BrandName) VALUES('Oracle'); sqlite> SELECT * FROM Brands; Id BrandName ---------- ---------- 1 Coca Cola 2 Pepsi 3 Sun 4 Oracle In SQLIte if a column is integer and primary key, it is also autoincrement. Foreign key A FOREIGN KEY in one table points to a PRIMARY KEY in another table. It is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. We will be demonstrating this constraint on two tables. Authors and Books. CREATE TABLE Authors(AuthorId integer PRIMARY KEY, Name text);
  • 4. Here we create the Authors table. CREATE TABLE Books(BookId integer PRIMARY KEY, title text, AuthorId integer, FOREIGN KEY(AuthorId) REFERENCES Authors(AuthorId)); We create the Books table. Here we have an AuthorId column name, which acts as a foreign key. It references to the primary key of the Authors table. In SQLite, foreign keys are not enforced by default. To enforce the foreign key, the library must be compiled with proper flags, it must be at least version 3.6.19 and the pragma key for foreign keys must be set. What would foreign key enforcement mean in our example? We could not insert a row into the Books table with an AuthorId, which is not present in Authors book. Check constraint A CHECK constraint is a condition that defines valid data of a relational database. The check is executed when adding or updating data to the column in question. sqlite> .schema Orders CREATE TABLE Orders(Id integer PRIMARY KEY, OrderPrice integer CHECK(OrderPrice>0), Customer text); We look at the definition of the Orders table. We see a CHECK constraint imposed on the OrderPrice column. Logically, the price of an order must be a positive value. sqlite> INSERT INTO Orders(OrderPrice, Customer) VALUES(-10, 'Johnson'); SQL error: constraint failed
  • 5. If we try to insert an invalid value, we get an error saying: 'constraint failed'. Default constraint The DEFAULT constraint inserts a default value into the column, if no value is available. sqlite> CREATE TABLE Hotels(Id integer PRIMARY KEY, Name text, City text DEFAULT 'not available'); To demonstrate the DEFAULT constraint, we create a Hotels table. The City column has a default 'not available' value. sqlite> INSERT INTO Hotels(Name, City) VALUES('Kyjev', 'Bratislava'); sqlite> INSERT INTO Hotels(Name) VALUES('Slovan'); sqlite> SELECT * FROM Hotels; Id Name City --- ------- -------------- 1 Kyjev Bratislava 2 Slovan not available In the first statement, we provide both hotel name and city name. In the second statement, we provide only the hotel name. SQLite puts the default value there, the 'not available' text. In this part of the SQLite tutorial, we have worked with views, triggers and transactions in SQLite.