CREATE TABLE T_CLIENT
(CLI_ID INTEGER NOT NULL PRIMARY KEY,
CLI_NOM VARCHAR(32) NOT_NULL)
CREATE TABLE T_FACTURE
(FCT_ID INTEGER NOT NULL PRIMARY KEY,
CLI_ID INTEGER NOT NULL REFERENCES T_CLIENT (CLI_ID),
FCT_DATE DATE NOT NULL DEFAULT CURRENT_DATE,
FCT_MONTANT DECIMAL (16,2) NOT NULL,
FCT_PAYE BIT(1) NOT NULL DEFAULT 0)
CREATE TABLE T_COMPTE
(CPT_ID INTEGER NOT NULL PRIMARY KEY,
CLI_ID INTEGER NOT NULL REFERENCES T_CLIENT (CLI_ID),
CPT_CREDIT DECIMAL (16,2)
CPT_DEBIT DECIMAL (16,2)
CPT_DATE DATE NOT NULL DEFAULT CURRENT_DATE)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
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);
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL 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.
Example: GROUP BY Amount Spent By Each
Customer
-- calculate the total amount spent by each customer
SELECT customer_id, SUM(amount) AS total
FROM Orders
GROUP BY customer_id;
Run Code
Here, the SQL command sums the amount after grouping rows by customer_id .
Exa
mple: SQL GROUP BY