0% found this document useful (0 votes)
8 views14 pages

DBMS Constraint

The document provides an overview of MySQL constraints, which are rules that enforce data integrity in tables. It details various types of constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, along with their syntax for creation and modification. Additionally, it covers the use of AUTO_INCREMENT for generating unique identifiers and discusses MySQL date data types and views.

Uploaded by

guyoboru12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

DBMS Constraint

The document provides an overview of MySQL constraints, which are rules that enforce data integrity in tables. It details various types of constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, along with their syntax for creation and modification. Additionally, it covers the use of AUTO_INCREMENT for generating unique identifiers and discusses MySQL date data types and views.

Uploaded by

guyoboru12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

MySQL Constraint

 Constraints are rules that enforce the integrity of data in a table.

Create constraints

Constraints can be specified when the table is created with the CREATE TABLE statement,
or after the table is created with the ALTER TABLE statement.

Syntax

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
);
SQL constraints are used to specify rules for the data in a table.

 Constraints are used to limit the type of data that can go into a table.
 This ensures the accuracy and reliability of the data in the table.
 If there is any violation between the constraint and the data action, the action is aborted.
 Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table. E.g. 2,3,4 & 5

The following constraints are commonly used in SQL:

1. NOT NULL - Ensures that a column cannot have a NULL value


2. UNIQUE - Ensures that all values in a column are different i.e. prevents duplicate
values
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. CHECK - Ensures that the values in a column satisfies a specific condition

Prevents rows that do not satisfy the CHECK criteria from being stored in the
table.

-
6. DEFAULT - Sets a default value for a column if no value is specified

1. UNIQUE Constraint

 The UNIQUE constraint ensures that all values in a column are different.
 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint. However,
you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
 Primary Key constraints can’t be null. UNIQUE constraints may be null.

UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons"
table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Age int,
2. NOT NULL on CREATE
UNIQUE (ID) TABLE
);

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT
accept NULL values when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
NOT NULL on ALTER TABLE

To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:

Example

ALTER TABLE Persons


MODIFY Age int NOT NULL;

3. PRIMARY KEY Constraint

 The PRIMARY KEY constraint uniquely identifies each record in a table.


 Primary keys must contain UNIQUE values, and cannot contain NULL values.
 A table can have only ONE primary key; and in the table, this primary key can consist
of single or multiple columns (fields).

PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Age int,
PRIMARY KEY (ID)
);

PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already created,
use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (ID);
DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP PRIMARY KEY;

FOREIGN KEY constraint

 The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
 A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
 The table with the foreign key is called the child table, and the table with the primary
key is called the referenced or parent table.

Look at the following two tables:

Persons table.
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

Orders Table
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in
the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign
key column, because it has to be one of the values contained in the parent table.

FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
ID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (ID) REFERENCES Persons(ID)
); FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons (PersonID);

DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;

CHECK Constraint

 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a column it will allow only certain values for this
column.
 If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.
CHECK on CREATE TABLE

The following SQL creates a CHECK constraint on the "Age" column when the "Persons"
table is created. The CHECK constraint ensures that the age of a person must be 18, or older:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

CHECK on ALTER TABLE

To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD CHECK (Age>=18);

DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons


DROP CHECK CHK_PersonAge;

DEFAULT Constraint

 The DEFAULT constraint is used to set a default value for a column.


 The default value will be added to all new records, if no other value is specified.

DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
The DEFAULT constraint can also be used to insert system values, by using functions like
CURRENT_DATE():

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
DEFAULT onOrderDate
ALTER TABLE
date DEFAULT CURRENT_DATE()
);
To create a DEFAULT constraint on the "City" column when the table is already created, use
the following SQL:

ALTER TABLE Persons


ALTER City SET DEFAULT 'Sandnes';

DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT;

What is an AUTO INCREMENT Field?

 Auto-increment allows a unique number to be generated automatically when a new


record is inserted into a table.
 Often this is the primary key field that we would like to be created automatically every
time a new record is inserted.

MySQL AUTO_INCREMENT Keyword

 MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment


feature.
 By default, the starting value for AUTO_INCREMENT is 1, and it will increment by
1 for each new record.

The following SQL statement defines the "Personid" column to be an auto-increment


primary key field in the "Persons" table:

CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Age int,
PRIMARY KEY (Personid)
);
To let the AUTO_INCREMENT sequence start with another value, use the following SQL
statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

When we insert a new record into the "Persons" table, we do NOT have to specify a value for
the "Personid" column (a unique value will be added automatically):

INSERT INTO Persons (FirstName, LastName)


VALUES ('Lars',' Monsen');

The SQL statement above would insert a new record into the "Persons" table. The "Personid"
column would be assigned a unique value automatically. The "FirstName" column would be
set to "Lars" and the "LastName" column would be set to "Monsen".

Working with Dates


MySQL Dates

The most difficult part when working with dates is to be sure that the format of the date you are
trying to insert, matches the format of the date column in the database.
MySQL Date Data Types

MySQL comes with the following data types for storing a date or a date/time value in the
database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
 YEAR - format YYYY or YY

Note: The date data type are set for a column when you create a new table in your database!

Look at the following table:

Orders Table
OrderId ProductName OrderDate
1 Geitost 2008-11-11
2 Camembert Pierrot 2008-11-09
3 Mozzarella di Giovanni 2008-11-11
4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

MySQL Views

MySQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the data were
coming from one single table.

A view is created with the CREATE VIEW statement.

CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
Note: A view always shows up-to-date data! The database engine recreates the view, every
time a user queries it.

MySQL CREATE VIEW Examples

The following SQL creates a view that shows all customers from Brazil:

Example

CREATE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

We can query the view above as follows:

###
SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products" table with a
price higher than the average price:

Example

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

We can query the view above as follows:

SELECT * FROM [Products Above Average Price];

MySQL Updating a View

A view can be updated with the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW Syntax


The following SQL adds the "City" column to the "Brazil Customers" view:

CREATE OR REPLACE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
DROP VIEW Syntax: DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

MySQL ALTER TABLE Statement


ALTER TABLE table_name
ADD column_name datatype;

Ex for Add column

ALTER TABLE Customers


ADD Email varchar(255);

Drop column

ALTER TABLE table_name


DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

ALTER TABLE Customers


DROP COLUMN Email;

ALTER TABLE - MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Column-Level Constraints Vs Table-Level Constraints

Column-Level Constraints

Column-level constraints are applied directly to a single column within a table. These
constraints define rules specific to the data in that column, and they are written right after the
column definition.

Key Characteristics of Column-Level Constraints:

 Scope: They apply only to the individual column.


 Syntax: The constraint is specified inline with the column definition.

 Examples: NOT NULL, UNIQUE, DEFAULT, CHECK.

CREATE TABLE Employees (

EmployeeID INT NOT NULL, -- Column-level constraint (NOT NULL)

FirstName VARCHAR (50) DEFAULT 'John' -- Column-level constraint (DEFAULT)


2. Table-Level Constraints

Table-level constraints are applied to the entire table and can reference multiple columns at
once. These constraints are typically used when the rule involves more than one column (e.g.,
a PRIMARY KEY or FOREIGN KEY constraint).

Key Characteristics of Table-Level Constraints:

Examples: PRIMARY KEY, FOREIGN KEY, CHECK, UNIQUE.

CREATE TABLE Orders (

OrderID INT,

CustomerID INT,

OrderDate DATE,

PRIMARY KEY (OrderID), -- Table-level constraint (PRIMARY KEY)

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) -- Table-level constraint


(FOREIGN KEY)

);

SQL DEFAULT Constraint


The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
The DEFAULT constraint can also be used to insert system values, by using functions like
GETDATE():

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

Key Differences: Mysql and SQL server

 In MySQL, to modify a column, you use MODIFY COLUMN, while in SQL


Server, the command is ALTER COLUMN.

ALTER TABLE table_name ALTER COLUMN column_name new_data_type;

ALTER TABLE users ALTER COLUMN name VARCHAR(150);

Auto Increment vs Identity

 MySQL:
o AUTO_INCREMENT is used for automatically incrementing primary key
values.

Example

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100)

);

QL Server:

 IDENTITY is used for automatically incrementing primary key values.

CREATE TABLE users (

id INT IDENTITY(1,1) PRIMARY KEY,

name VARCHAR(100)

);
3. String Concatenation

MySQL:

o Uses CONCAT() function to concatenate strings.

Example

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;

SQL Server:

 You can use + operator to concatenate strings.

Example

SELECT first_name + ' ' + last_name AS full_name FROM users;

4. Limit vs Top

 MySQL:
o Uses LIMIT to restrict the number of rows returned.

SELECT * FROM users LIMIT 10;

SQL Server:

 Uses TOP to restrict the number of rows returned.

SELECT TOP 10 * FROM users;

You might also like