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

Chapter 4 SQL DDL DML

db

Uploaded by

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

Chapter 4 SQL DDL DML

db

Uploaded by

hijaziahmad102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Abdallah EL Asmar

 SQL (Structured Query Language) is a database computer language designed for managing
data in relational database management systems (RDBMS).
 SQL, is a standardized computer language that was originally developed by IBM for
querying, altering and defining relational databases, using declarative statements.
 Even if SQL is a standard, many of the database systems that exist today implement their
own version of the SQL language.
 There are lots of different RDBMS such as:
• Microsoft SQL Server
• Oracle
• MySQL
• IBM DB2
• Sybase
• …

Abdallah EL Asmar 2
➢ Data Definition Language (DDL)
The DDL manages database, table and index structure. The most basic items of DDL are
the CREATE, ALTER and DROP statements:
▪ CREATE creates a database or an object (table, view, index, … ) in the database.
▪ DROP deletes a database or an object in the database, usually irreversibly.
▪ ALTER modifies the structure an existing object in various ways—for example, adding a
column to an existing table.
➢ Database identifiers
The database object name is referred to as its identifier. Everything in Microsoft SQL Server
can have an identifier: Databases, and database objects, such as tables, views, columns,
indexes, constraints, …
▪ The identifier can include letters, digits, and the special characters : @ $ # _
▪ The identifier, in general, must start with a letter
▪ The identifier must not be a reserved word.

Abdallah EL Asmar 3
➢ Database
Database is a collection of objects such as table, index, function, trigger, etc.
In MS SQL Server, two types of databases are available.
• System databases: created automatically when we install MS SQL Server. Following is
a list of system databases: Master, Model, MSDB, Tempdb, Resource, Distribution.
• User Databases created by users (Administrators, developers, and testers who have
access to create databases)
 Create a database
The basic syntax for creating a database : CREATE DATABASE <databaseName>
For example: CREATE DATABASE company ;
 Select a database
To run a query to on a database, first we must select the database; the syntax for
selecting a database is: USE <databaseName>
For example: USE company ;
 Remove a database
To remove a database : DROP DATABASE <databaseName>

Abdallah EL Asmar 4
➢ Create table
 General syntax
Create a table and specify its columns with their data types and constraints.
CREATE TABLE tableName (
columnName dataType [DEFAULT expr] [column constraints]
[, columnName dataType ...,]
[table constraints]
);

Example
CREATE TABLE employees (
id INT,
name VARCHAR (20) NOT NULL,
country VARCHAR(20) NOT NULL,
age TINYINT NOT NULL ,
salary DECIMAL (16, 2),
PRIMARY KEY (id)
);

Abdallah EL Asmar 5
➢ Data types
Numeric types

Data type Range Range expression Storage


int -2,147,483,648 to 2,147,483,647 -2^31 to 2^31-1 4 Bytes

smallint -32,768 to 32,767 -2^15 to 2^15-1 2 Bytes

tinyint 0 to 255 2^0-1 to 2^8-1 1 Byte

bit An integer data type that can take a value of 1, 0, or NULL.

decimal (p, s) P : number of digits (1 – 38) , S : digits after decimal point, 5 to 17


Valid values are from - 10^38 +1 through 10^38 – 1 bytes

Character types
Data type Description

char ( n ) Fixed-length data with a maximum length of 8,000 characters.

varchar ( n ) Variable-length data with a maximum length of 8,000 characters.

Abdallah EL Asmar 6
➢ Data types
 Date & time types

Data type Default string literal format Default value Storage

date yyyy-MM-dd 1900-01-01 3 Bytes

datetime yyyy-MM-dd hh:mm:ss[.nnn] 1900-01-01 00:00:00 8 Bytes

time hh:mm:ss[.nnnnnnn] 00:00:00 5 Bytes

▪ The GETDATE( ) function return the current system date and time as DATETIME type.
▪ To only get the system time : CONVERT (TIME, GETDATE( ) )
▪ To only get the system date : CONVERT (DATE, GETDATE( ) )

Abdallah EL Asmar 7
➢ The DEFAULT property
▪ Specifies the value provided for the column when a value isn't explicitly supplied during
an insert.
▪ DEFAULT definitions can be applied to any columns except those defined with the
IDENTITY property.
▪ Only a constant value, a system function or NULL can be used as a default.
▪ A constraint name can be assigned to a DEFAULT (Using the keyword CONSTRAINT).
▪ Example
CREATE TABLE invoice (
invoiceNbr INT,
invvoiceDate DATE DEFAULT CONVERT (DATE, GETDATE()),
clientName VARCHAR(20) CONSTRAINT defaultclient DEFAULT 'Unknown',
branchNbr TINYINT DEFAULT 10,
invoiceAmount DECIMAL (14, 2)
);

Abdallah EL Asmar 8
➢ Constraints
 A constraint can be defined
▪ during the creation of a table (CREATE TABLE)
▪ or after the creation using the ALTER TABLE statement.
 A constraint may affect one or more columns and as a result it can be defined at column
level or table level.
 A column can have several constraints.
 A name can be assigned to a constraint (Using the keyword CONSTRAINT), otherwise the
system generates a name.
CREATE TABLE table
(column datatype [DEFAULT expr] [CONSTRAINT constraint_name] constraint_type […] ,
column ... ,
[CONSTRAINT constraint_name] constraint_type (column, ...), [,...]);

Abdallah EL Asmar 9
➢ Constraints
 NOT NULL constraint
The NOT NULL constraint enforces a column to NOT accept NULL values. This means
that you cannot insert a new row or update a row without adding a value to this column.
 CHECK constraint
The CHECK constraint enforces domain integrity by limiting the possible values that can
be entered into a column or columns.
 PRIMARY KEY constraint
The PRIMARY KEY is a column (or columns) that uniquely identifies each row in a table.
A PRIMARY KEY constraint does not allow null values in the column and keeps unique
values throughout the column. Only one PRIMARY KEY constraint can be created per
table.
 UNIQUE constraint
The UNIQUE constraint keeps unique values throughout the column. A table can have
multiple UNIQUE constraints.

Abdallah EL Asmar 10
➢ Constraints
 IDENTITY property
▪ When a new row is added to the table, the Database Engine provides a unique,
incremental value for the column.
▪ Identity columns are typically used with PRIMARY KEY constraints.
▪ The IDENTITY (seed, increment ) can be assigned to tinyint, smallint, int, columns.
▪ Seed: The value used for the first row loaded into the table.
▪ Increment: The incremental value added to the identity value of the previous row
loaded.
▪ Both the seed and increment or neither must be specified. If neither is specified, the
default is (1,1).
▪ Only one identity column can be created per table.
▪ DEFAULT constraint can't be used with an identity column.

Abdallah EL Asmar 11
➢ Constraints

CREATE TABLE Product ( CREATE TABLE Product (


pID INT IDENTITY (1, 1) PRIMARY KEY, pID INT IDENTITY (1, 1),
pName VARCHAR(20) NOT NULL UNIQUE, pName VARCHAR(20) NOT NULL,
pBrand VARCHAR(15) DEFAULT 'New brand’, pBrand VARCHAR(15) DEFAULT 'New brand’,
purchasePrice INT NOT NULL purchasePrice INT NOT NULL,
CHECK (purchasePrice > 0), sellingPrice INT NOT NULL,
sellingPrice INT NOT NULL PRIMARY KEY (pid),
CHECK (sellingPrice > 0), UNIQUE (pName),
CHECK (sellingPrice >= purchasePrice) CHECK (purchasePrice > 0),
); CHECK (sellingPrice > 0),
CHECK (sellingPrice >= purchasePrice)
);

Abdallah EL Asmar 12
➢ Constraints
 FOREIGN KEY constraint
The FOREIGN KEY constraint establishes and enforces a foreign key relationship
between the column and the primary key of the referenced table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
It also prevents that invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the table it points to.
column datatype [CONSTRAINT constraint_name] REFERENCES referencedTable (primaryKey)
or
[CONSTRAINT constraint_name] FOREIGN KEY (column) REFERENCES referencedTable (primaryKey)

Category Product
PK
cID PID
cName cName
Price
FK
#cID
Abdallah EL Asmar 13
➢ Constraints
 FOREIGN KEY constraint
Two options can be used with the foreign key constraint:
▪ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }
Specifies what action happens to rows in the table created, if those rows have a
referential relationship and the referenced row is deleted from the parent table. The
default is NO ACTION.
NO ACTION: The Database raises an error and the delete action on the row in the parent
table is rolled back.
CASCADE: Corresponding rows are deleted from the referencing table if that row is
deleted from the parent table.
SET NULL: All the values that make up the foreign key are set to NULL.
SET DEFAULT: All the values that make up the foreign key are set to their default values
▪ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }
Specifies what action happens to rows in the table altered when those rows have a
referential relationship, and the referenced row is updated in the parent table. The
default is NO ACTION.

Abdallah EL Asmar 14
➢ Constraints
 FOREIGN KEY constraint

CREATE TABLE Category ( CREATE TABLE Product (


cID INT PRIMARY KEY, pID INT PRIMARY KEY,
cName VARCHAR(20) NOT NULL, pName VARCHAR(20) UNIQUE,
); price INT NOT NULL CHECK (price > 0),
cID INT,
CREATE TABLE Product (
quantity INT,
pID INT PRIMARY KEY,
FOREIGN KEY (cID) REFERENCES Category (cID)
pName VARCHAR(20) UNIQUE,
ON DELETE SET NULL
price INT NOT NULL CHECK (price > 0),
ON UPDATE CASCADE
cID INT REFERENCES Category (cID)
);
ON DELETE SET NULL
ON UPDATE CASCADE ,
quantity INT);

Abdallah EL Asmar 15
➢ ALTER TABLE
Modifies a table definition by altering, adding, or dropping columns and constraints.
 Add new columns
ALTER TABLE tableName
ADD columnName dataType [DEFAULT expr] [column constraints]
[, columnName dataType ...];
If the table contains rows, the values of the new column are initialized to NULL.
 Alter column
ALTER TABLE tableName
ALTER COLUMN columnName dataType [NOT NULL] ;
The ALTER COLUMN command allows to modify an existing column within a table. It
allows to change the data type, length and nullability.
Example : Consider the "Employees" table with a column named "Salary" that currently has a data
type of INT, and we want to change it to DECIMAL(10,2) and make it a non-nullable column:
ALTER TABLE Employees
ALTER COLUMN Salary DECIMAL(10,2) NOT NULL;

Abdallah EL Asmar 16
➢ ALTER TABLE
 Alter column
Restrictions
▪ To modify the data type of a column: The new data type must be compatible with the old one,
otherwise, you will get a conversion error in case the column has data and it fails to convert.
▪ To decrease the size of a column: SQL Server checks the existing data to see if it can convert
data based on the new size. If the conversion fails, SQL Server terminates the statement and
issues an error message.
▪ To add NOT NULL constraint: in case the column has NULL values, we must update NULL to
non-null first.

 Drop columns
ALTER TABLE tableName
DROP columnName [, columnName...];
Drop one or many columns.

Abdallah EL Asmar 17
➢ ALTER TABLE
 Add constraints
ALTER TABLE tableName
ADD [CONSTRAINT constraintName] constraintType (columns) ;
After the table creation, using this syntax, we can add the following constraints to the
table : PRIMARY KEY, UNIQUE, CHECK, and FOREIGN KEY.
ALTER TABLE Employee
ADD UNIQUE (Fname, Lname);
 N.B.
To add the NOT NULL constraint, we can use ALTER COLUMN
 DROP constraints
ALTER TABLE tableName
DROP CONSTRAINT constraintName;

Abdallah EL Asmar 18
➢ DROP TABLE
DROP TABLE tableName;

➢ Rename a table
EXEC sp_rename 'old_table_name', 'new_table_name’

➢ Rename a column
EXEC sp_rename 'table_name.old_column_name', 'new_column_name’, 'COLUMN’
➢ Show the table structure
EXEC sp_help 'table_name'
➢ Show the table constraints
EXEC sp_helpconstraint 'table_name'

Abdallah EL Asmar 19
➢ Data Manipulation Language
▪ The Data Manipulation Language (DML) is the subset of SQL statements used to query,
insert, update, and delete data within database tables.
▪ DML statements
o SELECT : To retrieve data from a database
o INSERT INTO : To insert new rows into database tables
o UPDATE : To update data of the database tables
o DELETE : To delete rows from database tables
▪ SELECT (will be detailed in next chapters)
The basic syntax of the SELECT statement :
SELECT column_name1, column_name2, …
FROM table_name
WHERE condition_ expression;
Example: All data for all employees Name and salary for employees of
the department 5.
SELECT *
SELECT employeeName, Salary
FROM Employee; FROM Employee
WHERE departmentID = 5;
Abdallah EL Asmar 20
➢ INSERT INTO
▪ used to add new rows of data to a database table.
▪ Syntax
INSERT INTO table_name [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN) [, (value1, value2, value3,...valueN) ] [, …];
You need not specify the column(s) name if you are adding values for all columns of the
table in the same order as the columns in the table.
INSERT INTO table_name VALUES (value1, value2,...valueN) [, …];

insert into client values (1,


'Sami', 'karam', '[email protected]’);

insert into client values (2, 'Jad',


'khalil', '[email protected]'), (3,
'Fadi', 'karim', '[email protected]');

Abdallah EL Asmar 21
➢ INSERT INTO
▪ It is also possible to only add data in specific columns (all columns that cannot be NULL
must be included).
insert into client (clientID, first_name, last_name)
values (4, 'Ali', 'Nader’);
we can specify null values:
insert into client (clientID, first_name, last_name, email)
values (5, 'Chadi', 'Dib', NULL);

▪ If a column is set to IDENTITY, values of this column will be generated by the system:

Abdallah EL Asmar 22
➢ UPDATE
▪ used to modify one or many columns of the table rows.
▪ Syntax
UPDATE table_name
SET column1 = value1 [, column2 = value2, ....]
[WHERE condition];
o The WHERE clause specifies which rows that should be updated.
o An UPDATE statement without the WHERE clause will update values in all the rows of the
table.
o Typically, condition has the : column comparison_operator value
Comparison operators : = <> > >= < <=
We can use logical operators : AND, OR, NOT
AND : Combines two conditions and evaluates to TRUE when both conditions are TRUE.
OR : Combines two conditions and evaluates to TRUE when either condition is TRUE.
NOT : (NOT condition) gives the opposite result of the condition.

Abdallah EL Asmar 23
➢ UPDATE
o Change the values of the columns last_name and email of the client with id 5.
UPDATE client
SET last_name = 'Deeb', email = '[email protected]'
WHERE clientID = 5;
o Consider the Invoice table:

Increase the invoice amount 10% for all invoices of the clients with IDs 5 and 7.
UPDATE invoice
SET amount = amount * 1.1
WHERE clientID = 5 OR ClientID = 7;
Increase the invoice amount 10% for all invoices.
UPDATE invoice
SET amount = amount * 1.1 ;

Abdallah EL Asmar 24
➢ DELETE FROM
▪ Removes one or more rows from a table.
▪ Syntax
DELETE FROM table_name
[WHERE condition];
o The WHERE clause specifies which rows that should be removed.
o A DELETE statement without the WHERE clause will REMOVE all rows of the table.
o Condition : The same as the UPDATE condition

▪ Remove all invoices of the client 5 with an amount < 100.


DELETE FROM invoice
WHERE clientID = 5 AND amount < 100;

Abdallah EL Asmar 25

You might also like