Uploaded by idizdar45

SQL-Revisions-Tables-Group1

advertisement
SQL Revision
Pereira Martins Pauline - Adjerit Marwan - Jaeger Killian - Allal Ewan - Gentilhomme Amaury
13th March 2023
Room 432
Table of contents :
I - Creating tables with constraints
II - Data types, sequences and identities
III - Changing tables
2
I - Creating tables with constraints
3
PRIMARY key Constraint :
FOREIGN key Constraint :
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES
Customers(CustomerID)
);
NULL Constraint :
CHECK Constraint :
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
HireDate DATE,
TerminationDate DATE NULL
);
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Price DECIMAL(10,2),
Quantity INT,
CONSTRAINT Product_Quantity
CHECK (Quantity >= 0)
);
I - Creating tables with constraints
Examples of table creations with constraints
4
II - Data types, sequences
and identities
5
CHAR : ‘E’
VARCHAR(15) : “dzieƄ dobry”
INT : 7
FLOAT : 7.2
DATE : ‘2023-12-31’
TIME : ‘15:30:16
TIMESTAMP : ‘2023-12-31 15:30:16’
BINARY : 1 or 0
Required Storage and Range for
Integer Types Supported by MySQL
II - Data types, sequences and identities
II - Data types, sequences
and identities
6
SYNTAX :
CREATE SEQUENCE
sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
cycle: When sequence reaches its
set_limit it starts from beginning.
Example :
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
nocycle;
CREATE TABLE persons(
ID number(10),
NAME char(20)
);
Use it with insert :
nocycle: An exception will be thrown
if sequence exceeds its max_value.
INSERT into persons(ID,NAME)
VALUES(sequence_1.nextval,’Paul’);
II - Data types, sequences and identities
Example of table creations with sequences
7
Example :
SYNTAX :
IDENTITY[(seed,increment)]
IDENTITY (10,10)
CREATE TABLE person (
person_id INT IDENTITY(1,1) PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender CHAR(1) NOT NULL
);
How to use it with insert :
INSERT INTO person(first_name, last_name, gender)
OUTPUT inserted.person_id VALUES('Jane','Doe','F');
II - Data types, sequences and identities
Example of table creations with identity
8
CREATE TABLE persons (
ID int NOT NULL AUTO_INCREMENT,
NAME char(20)
PRIMARY KEY (ID)
);
Use it with insert :
INSERT into persons(ID,NAME) VALUES(’Paul’);
You don’t even
need to specify the ID,
it
will be automatic
II - Data types, sequences and identities
NB : You can also use AUTO_INCREMENT
9
III - Changing tables
10
11
12
13
IV - Deleting tables
14
Drop Table
15
Truncate Table
16
Thank you for your
attention
17
Download