18-10-2023
Structured Query Language
(DDL & DML)
SQL Datatypes
Each value manipulated by SQL Database has a data type.
A data type specifies the possible values for a variable/identifier, the
operations that can be performed on that type and the way the values of
that type are stored.
The data type of a value associates a fixed set of properties with the value.
In SQL there are three main data types:
• Number
• Date
• Character/String
1
18-10-2023
Integer Types
Type Length Minimum Maximum Minimum Maximum
in Bytes Value Value Value Value
(Signed) (Signed) (Unsigned) (Unsigned)
TINYINT 1 -128 127 0 255
SMALLINT 2 -32768 32767 0 65535
MEDIUMINT 3 -8388608 8388607 to 0 16777215
INT/INTEGER 4 -2147483648 2147483647 0 4294967295
BIGINT 8 -92233720368 92233720368 0 184467440737
54775808 54775807 09551615
Floating Point Types
The FLOAT and DOUBLE types represent approximate numeric data values.
FLOAT(M,D) or DOUBLE(M,D) can store up to M digits in total where D represents the
decimal point. For example, a column defined as FLOAT(8,5) will look like -999.99999.
Following table shows the required storage and range (maximum and minimum value for
signed and unsigned integer) for each floating-point type.
Type Length Minimum Value Maximum Value Minimum Value Maximum
in (Signed) (Signed) (Unsigned) Value
Bytes (Unsigned)
FLOAT 4 -3.402823466E+38 -1.175494351E-38 1.175494351E-38 3.402823466E+
38
DOUBLE 8 -1.7976931348623 -2.22507385850720 0, and 1.79769313486
157E+ 308 14E- 308 2.22507385850720 2315
14E- 308 7E+ 308
2
18-10-2023
Fixed-Point Types
Fixed-Point data types are used to preserve exact precision, for example with currency data. In MySQL
DECIMAL and NUMERIC types store exact numeric data values. MySQL stores DECIMAL values in binary
format.
In standard SQL the syntax DECIMAL(5,2), 5 is the precision and 2 is the scale(number of places after decimal),
be able to store any value with five digits and two decimals. Therefore the value range will be from
-999.99 to 999.99.
The syntax DECIMAL(M) is equivalent to DECIMAL(M,0).
MySQL supports DECIMAL (for default (10,2)).
The maximum number of digits for DECIMAL is 65, but the actual range for a given DECIMAL column can be
constrained by the precision or scale for a given column.
Decimal vs Float
Float is a single precision (32 bit) floating point data type and decimal is a 128-bit floating
point data type.
Floating point data type represent number values with fractional parts.
Decimal accurately represent any number within the precision of the decimal format,
whereas Float cannot accurately represent all numbers.
Decimal used within financial applications that require a high degree of accuracy and easy
to avoid rounding errors whereas Float used when you stores scientific numbers and for
better performance.
Performance of Decimals is slower than float data types.
3
18-10-2023
DATE and TIME type
The date and time types represent DATE, TIME, DATETIME, TIMESTAMP, and YEAR. Each type has a range of
valid values, as well as a “zero” value.
DATETIME, DATE, and TIMESTAMP Types are:
Types Description Display Format Range
DATETIME Use when you need values YYYY-MM-DD '1000-01-01 00:00:00' to
containing both date and time HH:MM:SS '9999-12-31 23:59:59'.
information.
DATE Use when you need only date YYYY-MM-DD '1000-01-01' to
information. '9999-12-31'.
TIMESTAMP Values are converted from the YYYY-MM-DD '1970-01-01 00:00:01' UTC
current time zone to UTC while HH:MM:SS to
storing and converted back from '2038-01-19 03:14:07' UTC
UTC to the current time zone
when retrieved.
UTC or Coordinated Universal Time is the primary time standard by
which the world regulates clocks and time.
The major difference between DATETIME and TIMESTAMP is that TIMESTAMP
values are converted from the current time zone to UTC while storing, and
converted back from UTC to the current time zone when retrieved. The datetime
data type value is unchanged.
If an application is to be used across different time zones and …… time stamp
can be used.
4
18-10-2023
TIME type
MySQL fetches and displays TIME values in 'HH:MM:SS' format or 'HHH:MM:SS' format. The range of TIME
values from '-838:59:59' to '838:59:59'. The hours part may be rather large because not only the TIME type
can be used to represent the time of day, i.e. less than 24 hours, but also the passed time or a time of
interval between two events.
YEAR type
The YEAR type is a 1-byte type used to store a year in a 2-digit or a 4-digit format. If the length is specified
as 2 (for example YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4,
then YEAR can be 1901 to 2155. The default length is 4.
String Types
The string types are:
• CHAR
• VARCHAR
• BINARY
• VARBINARY
• BLOB
• TEXT
• ENUM
• SET
5
18-10-2023
CHAR and VARCHAR Types
The CHAR and VARCHAR types are similar but differ in the way they are stored and retrieved.
They also differ in maximum length and in whether trailing spaces are retained.
Types Description Display Range in characters
Format
CHAR Contains non-binary strings. Length is Trailing The length can be any
fixed as you declare while creating a spaces are value from 0 to 255.
table. When stored, they are right- removed.
padded with spaces to the specified
length.
VARCHAR Contains non-binary strings. Columns As stored. A value from 0 to 255
are variable-length strings. before MySQL 5.0.3, and 0
to 65,535 in 5.0.3 and
later versions.
CHAR vs VARCHAR
CHAR VARCHAR
Used to store character string Used to store variable
value of fixed length. length alphanumeric data.
It can hold a maximum It can hold a maximum of 65,535
of 255 characters. characters.
It's 50% faster than VARCHAR. It's slower than CHAR.
It uses dynamic memory
It uses static memory allocation.
allocation
6
18-10-2023
BINARY and VARBINARY Types
The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except that they contain binary
strings rather than nonbinary strings.
Types Description Range in bytes
BINARY Contains binary 0 to 255
strings.
VARBINARY Contains binary A value from 0 to 255 before MySQL
strings. 5.0.3, and 0 to 65,535 in 5.0.3 and later
versions.
BLOB and TEXT Types
A BLOB is a binary large object (such as images or other types of files) that can hold a variable
amount of data. There are four types of BLOB, TINYBLOB, BLOB, MEDIUMBLOB, and
LONGBLOB. These differ only in the maximum length of the values they can hold.
The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to
the four BLOB types and have the same maximum lengths and storage requirements.
Char and varchar get stored inline with table, blob and text in other location and a pointer to table, so…
7
18-10-2023
Types Description Categories Range
BLOB Large binary object that TINYBLOB Maximum length of 255
containing a variable amount characters.
of data. Values are treated as BLOB Maximum length of 65535
binary strings. You don't need characters.
to specify length while
MEDIUMBLOB Maximum length of
creating a column.
16777215 characters.
LONGBLOB Maximum length of
4294967295 characters
TEXT Values are treated as TINYTEXT Maximum length of 255
character strings having a characters.
character set. TEXT Maximum length of 65535
characters.
MEDIUMTEXT Maximum length of
16777215 characters.
LONGTEXT Maximum length of
4294967295 characters
ENUM Types
A string object whose value is chosen from a list of values given at the time of table
creation. For example -
CREATE TABLE length ( length ENUM('small', 'medium', 'large') );
and only those values (or NULL) could ever populate that field, enum values should be
string in single quote.
SET Types
A string object having zero or more comma separated values (maximum 64). Values are
chosen from a list of values given at the time of table creation.
8
18-10-2023
NULL value
• No value in a cell is NULL/null value.
• Its not equal to zero(ZERO NULL)
• Any arithmetic expression containing a NULL always
evaluates to NULL.
• When displaying the content of a table if a cell contain
null/no value MySQL display it as NULL.
SQL operators
Relational Operators are:
<, <=, >, >=, =, != (<>)
Logical operators are:
AND (&&), OR (II), NOT(!)
Imp:
• String or group of characters in single/double quotes
• Commands not case sensitive but data is case sensitive.
9
18-10-2023
Creating Database
To create database:
CREATE DATABASE [IF NOT EXISTS] <database name>;
To open database:
USE <database name>;
To show names of all databases:
SHOW databases;
To show name of active database:
SELECT database();
To delete/drop database:
DROP DATABASE <database name>;
Creating Table
Syntax is:
CREATE TABLE <table name>
(<column name> <data type> [<size>] [<column constraint>],
…………………….,
[<table constraint>]
);
10
18-10-2023
Constraints
Constraints restricts the data entry to a column.
Different types are:
1. Not Null
2. Unique
3. Check
4. Primary Key
5. Foreign Key
6. Default
Constraints can be applied on column or table level.
NOT NULL constraint
Can be applied at column level only.
Values in this field can not be NULL / left blank.
e.g.
create table STUDENT
(admNo integer NOT NULL,
name varchar(50));
11
18-10-2023
UNIQUE constraint
Can be applied at table or column level.
If applied for a column values have to be unique for the column.
create table STUDENT
(admNo integer NOT NULL UNIQUE, each field contain
unique entries
name varchar(50) UNIQUE );
Or
create table STUDENT
(admNo integer NOT NULL,
firstName varchar(20),
lastName varchar(20),
UNIQUE(firstName, lastName)); (unique entries for firstName + lastName, together)
Primary Key constraint
Can be applied at column or table level.
A column specified as primary key contain unique and no null values.
create table STUDENT
(admNo integer PRIMARY KEY,
stream varchar(20),
name varchar(50));
Or
create table STUDENT
(admNo integer,
stream varchar(20),
name varchar(50)
PRIMARY KEY(admNo, stream));
12
18-10-2023
Foreign Key constraint
Can be applied at column or table level.
Values entered in the field, must be a valid value in the primary key field of the other specified table
create table STUDENT
(admNo integer primary key,
name varchar(50),
subjectCode char(2) REFERENCES SUBJECT(subCode),
stream varchar(20));
create table STUDENT
(admNo integer primary key,
name varchar(50),
subjectCode char(2),
stream varchar(20),
FOREIGN KEY(subjectCode) REFERENCES SUBJECT(subCode));
Foreign Key constraint
Clauses on delete cascade and on update cascade
create table STUDENT
( admNo integer primary key,
name varchar(50),
subjectCode char(2)
stream varchar(20),
foreign key (subjectCode) REFERENCES SUBJECT(subCode)
on delete cascade on update cascade
);
On deleting/updating a record in parent table (primary key table) if the corresponding record exists in
child table (foreign key table), foreign key constraint doesn't permit. But, On delete cascade deletes the
corresponding record from the child table also, similarly on update constraint updates the
corresponding record in child table.
Can there be more than one foreign key in a table? Example??
13
18-10-2023
Check constraint
Can be applied at column or table level.
Values entered in the field, must be a valid value in the primary key field of the other specified table
create table STUDENT
(admNo integer primary key,
name varchar(50),
age smallint CHECK(age>=14 and age<=18),
stream varchar(20));
create table STUDENT
(admNo integer primary key,
create table STUDENT
(admNo integer primary key, name varchar(50),
name varchar(50), age smallint,
age smallint CHECK(age BETWEEN 14 AND 18), stream varchar(20),
stream varchar(20)); check(age>=14 and age<=18));
Check constraint
Can be applied at table level by taking two columns:
create table ITEMS
( icode char(3) primary key,
descp varchar(20) not null check (descp in ('NUT', 'BOLT', 'SCREW', 'WRENCH', NAIL')),
price float check (price>=100 and price<=500), //check price between 100 and 500
qoh tinyint, # quantity on hand
rol tinyint, # reorder level
unique(icode, descp),
check(ROL > QOH)
);
14
18-10-2023
DEFAULT value
Specifies default value for a field
create table STUDENT
( admNo integer primary key,
name varchar(50),
age smallint DEFAULT 15,
subjectcode char(2) DEFAULT '01'
);
Creating Table
create table SUBJECT
( subcode char(2) primary key,
subname varchar(20)
);
create table STREAM
( strCode tinyint(1) primary key,
strName varchar(15)
);
15
18-10-2023
Naming a Constraint
create table DEMO
( id smallint,
name varchar(20),
CONSTRAINT id_pk primary key(id)
);
Creating Table From Existing Table
CREATE TABLE orditem AS
( SELECT icode, descp, rol
from items
where qoh<rol
);
Above command will create orditem table with three columns and
the table will be initialised (with rows satisfying the criteria) with
the content of items table as per the where condition.
16
18-10-2023
Creating Table
create table STUDENT
(admNo integer primary key,
sname varchar(50) NOT NULL,
mname varchar(50),
fname varchar(50),
DOB date,
Xmarks float(5,2) check(Xmarks >= 75) ,
strCode tinyint(1) DEFAULT 1,
sub1 char(2) DEFAULT '01' REFERENCES SUBJECT(subcode),
sub2 char(2) DEFAULT '02' REFERENCES SUBJECT(subcode),
sub3 char(2) DEFAULT '03' REFERENCES SUBJECT(subcode),
sub4 char(2) DEFAULT '04' REFERENCES SUBJECT(subcode),
sub5 char(2) DEFAULT '05' REFERENCES SUBJECT(subcode)
FOREIGN KEY(strCode) REFERENCES Stream(strCode)
);
Inserting data into a table
Syntax is:
INSERT INTO <table name>
(column list) //optional if values for all columns to be entered
VALUES(data values) //if char or date type with in single quote
17
18-10-2023
Inserting data into a table
If table is, Subject:
Example:
SubCode SubName
301 English Core
1. Insert into SUBJECT
042 Physics
(Subcode, SubName) values ('301', 'English Core’);
043 Chemistry 2. Insert into SUBJECT
041 Mathematics values('042', 'Physics'), ('043', 'Chemistry');
048 3. Insert into SUBJECT (SubCode) values ('048');
083 Computer Science 4. Insert into SUBJECT
values ('048', NULL), ('083', 'Computer Science');
Insertion of a record into the table Student:
Insert into STUDENT
(admNo, sname, fname, mname, DOB, Xmarks)
values(3456, 'Anil Kumar', 'ABC', 'XYZ', '20-Sep-98', 92);
Inserting Data from Another Table
Example:
Insert into Achiever
Select * from Student
where Avg>90;
Above command will extract data as per the where condition from
Student table and will insert it into already existing table Achiever.
18
18-10-2023
Deleting Record
Syntax is:
DELETE FROM <tablename>
WHERE <condition>
Example:
delete from Student
where stream = 2; //delete all records corresponding to stream 2
delete from Student; //command will delete all records from the table
Updating/Modifying Record
Syntax is:
UPDATE <tablename>
SET <column1> = <expression1>, ………
WHERE<condition>;
Example1: Example2:
(modifying one column) (modifying two column)
update emp update emp
set sal = sal + 1000 set sal = sal + 1000, comm = comm+500
where deptno = 20; where job = 'SALESMAN';
Example3:
(updating to NULL and a scalar quantity)
Update employee
Set grade=NULL, col_new='ABC'
19
18-10-2023
Altering/Modifying Table Structure
Adding Column
Syntax is:
ALTER TABLE <tablename>
ADD/MODIFY (<column name> [<data type> <size>],
<column name> [<data type> <size>],………);
Example
Alter table emp
ADD (city varchar(15));
Alter table emp
MODIFY (city varchar(25));
Altering/Modifying Table Structure
Dropping a column
Syntax is:
ALTER TABLE <table name>
DROP COLUMN <column name>
Example:
Alter table emp
DROP COLUMN city;
Restrictions on Alter table:
• Table name can't change
• Column size can't decrease if record exists
20
18-10-2023
Altering/Modifying Table Structure
Few more examples:
Adding primary key
Alter table Customer Add Primary Key(SID);
Adding Foreign Key
Alter table Orders
Add Foreign Key(customer_sid) References Customer(SID);
Remaining a column/field of table
Alter table Customers
change First_Name FirstName varchar(20);
Removing Table Components
Alter table Emp1
Drop Primary Key, drop foreign key fk_1, drop column deptno;
Alter table dept
Drop primary key cascade;
(The cascade option drops any foreign keys that reference the primary key.)
21
18-10-2023
Destroying Table
Condition is table must be empty.
If Exists – checks if the table exists
Syntax is:
DROP TABLE [IF EXISTS]<table name>
Example:
DROP TABLE IF EXISTS stream
COMMIT command makes the changes permanent in a table.
The COMMIT Command
The COMMIT command is the transactional command used to save changes
invoked by a transaction to the database.
The COMMIT command is the transactional command used to save changes
invoked by a transaction to the database. The COMMIT command saves all
the transactions to the database since the last COMMIT or ROLLBACK
command.
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo
transactions that have not already been saved to the database. This command
can only be used to undo transactions since the last COMMIT or ROLLBACK
command was issued.
22
18-10-2023
A transaction begins with the first executable SQL statement. A transaction ends
when it is committed or rolled back, either explicitly with
a COMMIT or ROLLBACK statement or implicitly when a DDL (Data Definition
Language (DDL) is used to manage table and index structure and CREATE, ALTER,
RENAME, DROP and TRUNCATE statements are to name a few data definition
elements) statement is issued.
Transactional control commands are only used with the DML Commands such as -
INSERT, UPDATE and DELETE only. They cannot be used while creating tables or
dropping them because these operations are automatically committed in the
database.
In MySQL, all user activity occurs inside a transaction. If autocommit mode is enabled, each SQL statement forms a single
transaction on its own. By default, MySQL starts the session for each new connection with autocommit enabled, so
MySQL does a commit after each SQL statement if that statement did not return an error. If a statement returns an error,
the commit or rollback behavior depends on the error.
A session that has autocommit enabled can perform a multiple-statement transaction by starting it with an explicit START
TRANSACTION or BEGIN statement and ending it with a COMMIT or ROLLBACK statement.
If autocommit mode is disabled within a session with SET autocommit = 0, the session always has a transaction open. A
COMMIT or ROLLBACK statement ends the current transaction and a new one starts.
If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that
transaction.
Some statements implicitly end a transaction, as if you had done a COMMIT before executing the statement. Ex???
A COMMIT means that the changes made in the current transaction are made permanent and become visible to other
sessions. A ROLLBACK statement, on the other hand, cancels all modifications made by the current transaction. Both
COMMIT and ROLLBACK release all MySQL DB locks that were set during the current transaction.
23
18-10-2023
1) Create Suppliers with SuppNo as
primary key, supp_Name as NOT
NULL, status (value>=10)
2) Create table items with
itemNo as primary key,
item_Name not null
3) Create table Shipments
with SuppNo+ItemNo as
primary key, where each of
SuppNo and ItemNo are
Foreign key and
QtySupplied is >=10.
24
18-10-2023
create table department
(deptno integer primary key,
dname varchar(20) not null,
dloc varchar(20));
insert into department values
(10, 'ACCOUNTING', 'NEW YORK'),
(20, 'RESEARCH', 'DALLAS'),
(30, 'SALES', 'CHICAGO'),
(40, 'OPERATIONS', 'BOSTON');
create table employee
(empno integer primary key,
ename varchar(50) not null,
job varchar(20),
mgr integer references employee(empno),
hiredate date,
sal integer check (sal between 0 and 10000),
comm integer,
deptno integer references department(deptno));
INSERT INTO EMPLOYEE
(empno, ename, job, mgr, hiredate, sal, deptno)
VALUES(7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, 20);
25
18-10-2023
INSERT INTO EMPLOYEE VALUES
(7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30),
(7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30),
(7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, NULL, 20),
(7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30),
(7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, NULL, 30)
(7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, NULL, 10),
(7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000, NULL, 20),
(7839, 'KING', 'PRESIDENT', NULL, '1981-11-17', 5000, NULL, 10),
(7844, 'TURNER', 'SALESMAN', 7698, '1981-09-08', 1500, 0, 30),
(7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100, NULL, 20),
(7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, NULL, 30),
(7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20),
(7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10);
26