Table Creation and DML Commands
Table Creation and DML Commands
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)
Following table shows the required storage and range (maximum and minimum value for
signed and unsigned integer) for each floating-point type.
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
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.
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 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.
6
18-10-2023
The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except that they contain binary
strings rather than nonbinary strings.
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
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:
<, <=, >, >=, =, != (<>)
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 delete/drop database:
DROP DATABASE <database name>;
Creating Table
Syntax is:
10
18-10-2023
Constraints
Constraints restricts the data entry to a column.
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.
Or
Or
12
18-10-2023
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.
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
Check constraint
Can be applied at table level by taking two columns:
14
18-10-2023
DEFAULT value
Specifies default value for a field
Creating Table
create table SUBJECT
( subcode char(2) primary key,
subname varchar(20)
);
15
18-10-2023
Naming a Constraint
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)
);
17
18-10-2023
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; //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
Example
Example:
20
18-10-2023
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:
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
24
18-10-2023
25
18-10-2023
26