chopte 13. TABLE CREATION AND DATA tuvaFULATION cOMaNos
583
Now consider the following examples :
ALTER TABLE Emp
DROP PRIMARY KEY, DROP FOREIGN KEY fk_1,
In the above given A.1ER TBE statement, the
fk.1, and the column namely deptno
OROP COLUM deptno ;
Primary key, the FOREIGN KEY constraint namely
are all removed form the Empl table.
Exam UE 13.10 Drop the primary hey ofthe DEPT table,
Solution. mysql> ALTER TABLE dept
DROP PRIMARY KEY CASCADE ;
‘The CASCADE option drops any forcign keys that reference the primary key,
EXAMPLE 13.11 Drop the DNAME column of the DEPT table
Solution, mysql> ALTER TABLE dept
ye DROP COLUMN dame ; |
Nos.
13.5.2 The DROP TABLE Command
1, Which command is used for creating
tables ? ‘The DROP TABLE command of SQL lets you drop a table
a the data The syntax for using a DROP TABLE
constraints that you can apply to Command is:
enhance database integrity. OROP TABLE [IF EXISTS]
a PRIMARY EEE etatt? That i, to drop a lable iems, you need to write:
different from UNIQUE constraint ? ‘DROP TABLE items ;
4, What is primary key ? What is PRIMARY — Once this command is given, the table name is no longer
HEY constraint ? recognized and no more commands can be given on that
5. What is NOT NULL constzaint 2 What is object.
ed | sipped in an THIF EXISTS clause of DROP TABLE first checks whether
OS ae ae pooped 27 the given table exists in the database or not. fit does, then it
aor aeees drops the mentioned table from the database. For instance,
1. Gan a column defined vith nor nu, consider the following query :
constraint, be skipped in an INSERT DROP TABLE IF EXISTS players ;
command ?
8 How would you view the structure of The above query will first check for existence of players
table Dept ? table in current database. If it exists, then it (table players)
9, Table Empl has same structure as that will be dropped from the database.
of table EMPL Write a query statement
to insert data from table NewEmpl into
EMPL where salary and comm is more
than Rs. 4000.
10, What isthe error in. following DDL ComMaNps
statement ? iP Progress In Python 13.3
UPDATE EMPL
U1. Identify the error : ‘This ‘Progress in Python’ session is aimed at laying string
DELETEALLFROMTABLEENPL; foundation of decision constructs.
12. ifferentiate between DDL and DML.
votece
— Md
@ scanned with OKEN ScannerCOMPUTER SCIENCE Wat ay
1,
Order of Column 7
With MODIFY clause you can also reorder the columns within a table. For this you p,
FIRST or AFTER clause to specify the poston of the column. To modi
columns of table, ALTER TABLE command can be used according to following sym
ALTER TABLE
MODIFY (colunname newdatatype (newsize) ) [FIRST|AFTER column) ;
To modify column fob of table Empl (Chapter 12) tohave new width of 30 characters, yoy
ALTER TABLE Emp]
MODIFY (Job char(3@) ) ;
Similarly, if you want to reorder an existing column say ProjID to be the first co}
table Assignment, you may write :
ALTER TABLE Assignment
MODIFY ProjID INT FIRST ;
May,
umn ny
Exampte 13.7 In table EMPL, increase the size of the THRIFTPLAN colunmn to nine digits :
Solution, mysql> ALTER TABLE emp]
MOOIFY(thriftplan NUMBER(9,2)) ;
EXAMPLE 13.8 In lable ACCOUNTS, modify the BAL column so that i has a default value of,
Solution. mysql> ALTER TABLE accounts
NODIFY(bal DEFAULT 8) ; a
Example 13.9 Add @ PRIMARY KEY data constraint on the column —__‘E2S€_note that mq ,
s StF
supplier_no belonging to the table supplier master eA fREIGN oa
its database engine ig
Solution. ALTER TABLE supplier_master INNODB. So your queria
ADD PRINARY KEY(supplier_no) ; erect cc
Changing @ Column Nome
Sometimes you may need to change the name of one of your columns,
CHANGE clause of ALTER TABLE command as per following syntax
ALTER TABLE
For this you cant
CHANGE [COLUIN] o14_col_nane new_col_nane colunn_definition ;
For instance, to change the existin,
you may write:
‘See, complete column description is
ALTER TABLE Customers 4 _giten alongwith the nv sone
CHANGE First_Name FirstName VARCHAR(20)
1g column namely First_Name of table Student, to Fire
13.5.1C_ Removing Table Components
If you plan to remove a component of a table,
th f ALT
TABLE. The keywords mostly used with DROP elasce of were Oe cats
P clause of ALTER TABLE command are
EAR ie Drops the table's primary key constraint.
“OLUMN Removes mentioned column from the table
FOREIGN KEY Removes the mentioned foreign key constraint from the
@ scanned with OKEN ScannerChest’ 12 TABLE CREATION AND DATA MANIPULATION COMIALIDS 581
paunie Bae tle EMPL (Chane 12, Table 12.5), add a column named THRIFTPLAN of datatype NUMBLK
geith a maxinur 7 : ne decimal places and a column named LOANCODE: of datatype Cl HAR with a size
fone and at integrity constraint that checks thal load code should be one of these characters : ‘fC, W',
Solution. mysql> ALTER TABLE enpl
ADD ( thriftplan NUMBER(7,2),
Joancode CHAR(1) CHECK (loancode IN("E*, 'C', 'H', 'P'))) +
While adding columns, you can define these ty integrit i
Nh 7 ¢ types of integrity constraints (NOT NULL,
UNIQUE, PRIMARY KEY, referential integrity (REFERENCES), DEFAULT and CHECK
constraints) on existing columns using the ADD clause and in table constraint syntax.
Example 13.6 In table EMPL (Chapter 12, Table 12.5), add a column named SPECIAL PAY of datatype. NUMBER
‘pith maximum of seven digits with 2 digits afer decimal and with a DEFAULT value of 2400.
Solution. mysql> ALTER TABLE empl
‘ADD(specialpay NUMBER(7,2) DEFAULT 2400) ;
Ifyou use the ADD clause to add a new column to the table, then the initial value of each row
for the new column is NULL. You can add a column with a NOT NULL constraint only to a
table that contains no rows.
13.5.1B Modifying Column Definitions
You can use the MODIFY clause to change any of the follo
© datatype © size
© default value © NOT NULL column constraint
© Order of columa |
‘The MODIFY clause need only specify the column name and PE sca corn was
the modified part of the definition, rather than the entire NFATWUIL covtrsint ondy 168
column definition. table that contains no rows.
1g parts of a column defi
Datatypes ond Sizes
You can change a CHAR col
contains nulls in all rows or if
lumn to VARCHAR and a VARCHAR to CHAR only if the column
you do not attempt to change the column size. You can change
any column’s datatype or decrease any column's size if all rows for the column contain nulls.
However, you can always increase the size of a CHAR or VARCHAR column or the precision of a
numeric column. ———
Default Values
‘A change to a column’s default value only affects rows ee ea columats
subsequently inserted into the table. Such a change does not, irs ce ol coms foe te
change default values previously inserted. Gaia conta nul
Integrity Constraints
‘The only type of integrity constraint that you can add to an existing column using the MODIFY
clause with the column constraint syntax is a NOT NULL constraint. However, you can define
ther types of integrity constraints (UNIQUE, PRIMARY KEY, referential integrity, and
CHECK constraints) on existing columns using the ADD clause and the table constraint syntax.
You can define a NOT NULL constraint on an existing column only if the column contains
no nulls.
@ scanned with OKEN Scanner580 COMPUTER scis
To remove all the contents of items table, you use the command :
DELETE FROM items ;
The table would now be empty and could be destroyed with a DROP TABLE
(covered later in the section 13.5.2).
Bven some specific rows froma table can also be deleted, To determine which rons
you use condition, jst as you do for queries For instance to remove the tuples nan SS
table that have gross less than 2200.00, the following command is used : Fy
DELETE FROM employee
WHERE gross < 2200.00 ;
13.5 MORE DDL COMMANDS
As you know, the DDL division of SQL is responsible for defining, red mode
dropping various database objects. Uptil now, you have leamt to use different databasecty
This section is going to discuss some more DDL commands that prove very usehy
redefining or dropping database object. 8
You have already worked with one DDL command ~ the CREATE TABLE command n=
beginning ofthe chapter. Thatis, you already know how to create tables along with cose
definition. This section is going to discuss DDL. commands for altering tables
comments enabling/isabling constraints truncating tables, renaming objects, droppings
views and synonyms etc. Let us begin with ALTER TABLE command that is used tg sie
table's definition.
13.5.1 ALTER TABLE Command
When we define a system, we specify what data we need to store, the size and datatypes
data. What can we do when the requirements change ? We can alter the tables to accommais
the changed requirements,
The ALTER TABLE command is used to change definitions of existing tables. Usuall
add columns to a table. Sometimes it can delete columns (depending on privileges) or
their sizes. In general, in MySQL SQL, ALTER TABLE command is used :
© to add a column © to add an integrity constraint
© to redefine a column (datatype, size, default value).
13.5.1. Adding Columns
Typically, the syntax to add a column to a table is as follows :
SYNTAX
ALTER TABLE ADD [
[WHERE ] 5
@ scanned with OKEN Scanner578 COMPUTER SCIENCE WITH FrtHoy,
13.4.1B Inserting NULL values /
To insert value NULL in a specific column, you can type NULL without quotes and NULL y,
‘be inserted in that column. Consider the following statement :
INSERT INTO EMPL (Enpno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno)
VALUES (8100, 'YASH', 'ANALYST", NULL, '20-MAY-@3", 6000, NULL, 20) ;
serted,
See, for Mgr and Comm columns, NULL values have bee
13.4.1C Inserting Dates
Dates are by default entered in "YYYY-MM-DD' format ic. first four digits depicting yo,
"a hyphen, followed by 2 digits month, followed by a hyphen and a two digit du
1 in single quotes, In the above two INSERT INTO statements given
previous section, the dates (HIREDATE) have been given in the same format,
13.4.1D_ Inserting Data from Another Table
INSERT command ean also be used to take or derive values from one table and place thems
another by using it with a query. To do this, simply replace the VALUES clause with »
appropriate query as shown in the following example
INSERT INTO brancht
SELECT * FROM branch?
WHERE gross > 7000.00 ;
This query wall generate data 19
le inserted into table
It will extract all those rows from branch? that have gross more than 7000.00 and insert ths
produced result into the table branch1. To insert using a query, the following conditions musty
true
( Both the tables must be already created.
(i The columns of the tables being inserted into, must match the columns output by te
subquery.
EXAMPLE 13.4 Insert into empl table, the employee numibers, names, acd salaries ofall those employees of Temp tse
that have completed 2 years. The structure of Temps table ts as follows :
Enum NOT NULL Number (4)
Enane Varchar(10)
sal Number(7,2)
Months Nunber(3)
PNOvE
Solution. mysql> INSERT INTO Empl (Empno, Ename, Sal)
SELECT Env, Enave, Sal Sas oe owe
FROM Temp permanent
WHERE Months >= 24 ;
13.4.2. Modifying Dota with UPDATE Command
Sometimes you need to change some or all of the val
lues in an es v. This can be dom
using the UPDATE command of SQL. The eee cman oe nee cal
UPDATE command specifies the rows to be chang
@ scanned with OKEN Scannerhope 13 : TABLE CREATION AND DATA MANIPULATION COMMANDS 577
For instance, if you want to insert only ecode, ename and sex columns, you use the command :
INSERT INTO enployee (ecode, enane, sex)
VALUES (2014, ‘Manju’, *F*) ; has
The columns that are not listed in the INSERT command will have '" 3" INSERT statement, oly
a , rn those columns can be omitted
their default value, ifitis defined forthem, otherwise, NULL value. thor ove etter defeat vale
If any other column (that does not have a default value and is defined or they allow NULL
defined NOT NULL) is skipped or omitted, an error message is Ye
generated and the row is not added,
Example 13.3 Add the following data in the above Table (Employee) as instructed.
ID FirstName | LastName | UserID | Salary
1 Dim Joseph Jdim 5000
2 Jagannath | Mishra jnmishra 4000
3 Siddharth | Mishra smishra 8000
4 Shankar | Giri sgiti 7000
5 Gautam | Buddha _| bgautam 2000
() Populate table coith first record mentioning the column list in the insert clause.
(ii) Populate table with next two records without mentioning the column list in the insert clause.
(ii) Populate table with 4" record and enter only ID and First_Name.
(iv) Populate table with 5" recorded and enter ID, User_ID, and Last_Name only.
Solution. (j) INSERT INTO Employee (1D, First_nane, Last_nane, User_ID, Salary)
Values (1, 'Dim', ‘Joseph’, ‘dim’, 5800) ;
(i) INSERT INTO Employee
Values (2, ‘Jagannath’, ‘Mishra‘, ‘jnnishra‘ , 4600) ;
INSERT INTO Employee
Values (3, ‘Siddarth’, 'Mishra', ‘smishra’ , 8809) ;
(i) INSERT INTO Employee (1D, First_nane)
Values (4, 'Shankar') 5
(jo) INSERT INTO Employee (ID, User_ID, Last_Nane)
Values (5, ‘bgautan', "Buddha") ;
Asyou know that following command is used to insert a new row with values forall columns of
the table :
INSERT INTO
VALUES (, ...++) 3
‘And the following INSERT INTO command allows you to insert a new row with values of select
columns =
INSERT INTO (, ..
VALUES (, ...+ JE
)
Let us now Jearn how you can insert nulls, date-values and data from other table(s).
@ scanned with OKEN ScannerCOMPUTER SCIENCE Win
576 TION
CREATING TABLES,
Inserring DATAINTARKES _ Progress in SQL 13.1 & yy,
Please check the practical component-book ~ Progress in Computer
4 Science with Python and fill it there in PriS 13.1, 13.2 under Chapter 13
after practically doing it on the computer.
ppoticce,
13.4 CHANGING DATA WITH DML COMMANDS
As you know that DML (Data Manipulation Language) division of SQL, is dedicated
manipulating data in one way or another. This section is going to talk about various Dy
commands that are used for changing data in tables. Of these commands, INSERT 1p
‘command is used for entering data into tables.
13.4.1 Inserting Data into Table
Values are placed in and removed from attributes of a relation with three DML commands
INSERT, DELETE and UPDATE. These are all referred to in SQL as update commands in
generic sense. In our text, lowercase “update” will indicate these commands generically and
uppercase for the keyword UPDATE.
13.4.1A_ INSERT INTO Command
The rows (tuples) are added to relations using INSERT command of SQL. In its simplest form
INSERT takes the following syntax
Syntax
INSERT INTO [ ]
VALUES ( , ... ) ;
For example, to enter a row into employee table (defined earlier), you could use the following
statement :
INSERT INTO employee
VALUES (1001, "Ravi", ‘HM’, "E4", 4670.08) ;
See the order of values matches the order of columns in the CREATE TABLE command ot
‘employee. The same can be done with an alternate command as shown below -
INSERT INTO employee (ecode, enane, sex, grade, gross)
VALUES (1861, "Ravi", ‘MN’, "G4", 4670.0)
Note that the data values are in the same order as the column
names in the table. Data can
added only to some columns in a row by specifying the columns and the date
@ scanned with OKEN Scannerrope 13 = TABLE CREATION AND DATA MANIPULATION Cony
ANDS. 575
For example, if you write
DESC Pet 5
or DESCRIBE Pet ;
MySQL will show you the complete structure of table named PET as shown below :
varchar (20)
varchar (20)
char (1)
date
date
Once you have created tables in your database, you can check the tables’ names in the database.
To check what all tables are there in database, simply write
SHOW TABLES 5
it will show you the names of all the tables in the database.
13.3.1E Creating Table from Existing Table
You can define a table and put data into it without going through the usual data definition
process. This can be done by using SELECT statement with CREATE TABLE,
The new table stores the result produced by the SELECT statement. The name of the new table
must be unique. Following query illustrates this =
CREATE TABLE orditem AS
(SELECT icode, desep
FAO Stns as
WHERE QOH AS SELECT....is useful for creating test tables, new tables as copies
of existing tables, and for making smaller tables out of large tables.
Me
@ scanned with OKEN ScannerCOMPUTER SCIENCE WITH PYTHON
“y
574
ExampLe 13.1 Create table Employee with the following structure
|
——_——,
[Name ofCotumn| 1D __| FirstName | LastName UserID} Salary
eer :
Type T Number | Varchar(30) | Varchar(30) | Varchar(10) | Number(92)
[te |
Ensure the following specification in created table
‘© ID should be declared as Primary Key ¢ User_ID should be unique
© Salary must be greater than 5000. © First_Name & Last_Name must not remain bang
Solution. CREATE TABLE Employee
(TD Number(4) NOT NULL PRIMARY KEY,
First_Name Varchar(38) NOT NULL,
Last_Name Varchar(38) NOT NULL,
User_ID Varchar(10) UNIQUE,
Salary Nunber (9,2) CHECK (Salary > 5000)
3
MySQL responds as: Query OK, @ rows affected
EXAMPLE 13.2 Create another table Job with following structure =
Name of column Type
Job_id Number(4)
Job_des Varchar(30)
Allloc_on Date
Due_on Date
Emp_id Number(4)
Ensure the following specifications in the table :
© Job_id is the primary key © Job_des, Alloc_on, Due_on cannot be left blank,
© Emp_id is foreign key here that is related to ID column of earlier created table Employee.
Solution. CREATE TABLE Job
(. Job_id Number (4) NOT NULL PRIMARY KEY,
Job_Des Varchar(3@) NOT NULL, [NOTE ad
‘Alloc_on Date NOT NULL,
Due_on Date NOT NULL, ii men ven ea
Emp_id Number (4) REFERENCES Employee (ID) ) ; ae a fi el
Query OK, @ rows affected (CREATE TABLE i
ames
MySQL responds as :
3.3.1D Viewing a Table Structure
Once you have created a table, you may want to view its structure. Anytime, if you want ©
view an already created/existing table's structure, you may use DESC[RIBE] commant
of MySQL * Plus,
The syntax of this command is as follows :
SYNTEAX _DESC[RIBE] ;
i
@ scanned with OKEN Scannercope 13 TABLE CREATION AND DATA MANIPULATION COMMANDS 573
CREATE TABLE itens
(© feode char (5) NOT NULL
desep char (28) NOT MULL”
ROL integer, id
GH integer,
CHECK — (ROL < QOH), these are a t
UNIQUE (icode, Boye . a
The above statement ensures thatthe combination of iave and desc in each row must be unique.
Similarly, if you want to define primary key that contains more than one colum
: n, you can use
PRIMARY KEY table constraint. For instance, if you want to declare a primary key for the table
‘members as the combination of columns firstame and lastname, it can be done as follows
CREATE TABLE menbers
(firstname char (15) NOTNULL,
lastname char (15) NOTNULL,
city char (2¢).
)
PRINARY KEY (Firstname, lastnane) ) ; ——
To define foreign key constraint for a group of columns, FOREIGN KEY table constraints
should be used. For example, if a group of columns say ordemo and items, is to be declared
foreign key, it should be done as follows :
CREATE TABLE Orders,
(- Orderno Nunber(6, @) NOT NULL,
Ttemno char(5),
FOREIGN KEY (Orderno, Itenno) REFERENCES Ordlaster (OrderN0, ItenNo)
3
13.3.1C Assigning Names to Constraints
By default, MySQL assigns a unique name to each constraint defined by you. MySQL names
constraints as :
syS_Cn
where 1 is an integer that makes the constraint name unique. For instance, SYS_C003217,
SY$_C001592 etc. are constraint names generated by MySQL. However, you, yourself, can
name a constraint created by you. This can be done as per following syntax :
‘SYNTAX CONSTRAINT
For example, consider the following two CREATE TABLE statements =
CREATE TABLE Items
( Ttemno char(5) CONSTRAINT p_Itemkey PRIMARY KEY,
5
‘CREATE TABLE Orders
( Orderno
CONSTRAINT Group_Fkey_Orders FOREIGN KEY (Onderno, Itemo)
REFERENCES OrdMaster (Order#, Item#) ) ;
@ scanned with OKEN Scannera
COMPUTER SCIENCE Wath pny
572 2,
/t traint
KEY/REFERENCES cons
a eae into the rection of INSERT (statement used to insert new data) op :
° ese to modify existing data) ifa corresponding value does not sineuy
stateme
in the primary table. (See Fig, 13.2) os aa
ion has been set then upot pein th
DELETE CASCADE option has
iseeumetiet aia child table get deleted. In the absence ofthis a
ps the deletion operation if corresponding records in the child table exist, 8)
© The foreign key column in the cil table must reference a PRIMARY KEY oy o
column in the parent table.
¢ Both the lated columns parent table and in chil table) should have the same dat
© May reference to the same table in which it is being defined ice, it may reference thes,
table name as in the CREATE TABLE command.
sats | Be [ ene Tse Tee Toe] =
“Barer” [fettCh| Bean |u| es amor
ton Teen || wena] —F | as tee ea
tse ios Rategs [TP
REFERENCES [Ti04_ | Vansh ™ ws | 24000 Error!! While
creat on
eting
REFERENCES Tam foreign key in
my table
[Peet | _bencip [Eom oe
201 [Sas [1108 | Tanna
)reae | wana ort
7208 | Kuwhaga | ie | tonsa
I
REFERENCES
constraint on
Ecode column
Figure 13.2 FOREIGN KEV/REFERENCE Constraint,
EEE Foreign Key and Storage Engine
MySQL i capable of cresting databases in many diferent Storage engines that offer different features. The
default
forage engine is ISAM but ironically it does not ‘Support foreign keys. So, if you find that you
foreign key constraint are being ignored or not ‘implemented, you need to Change the storage engine of your
database tables to InnoDB storage engine.
To do so you simply need 1 wie following command for your connecting tables :
ALTER TABLE ctablenane> ENGINE = innodb ;
8» ALTER TABLE tablet ENGINE = innod 3
Natasa) ee Abe ap uta
13.3.1B Applying Table Constraints
ee get serie grep obcoterme of table, it is called tlle
constraint. The table constraints i ps
appear in the end of table definition. For instance, if you ¥®*
Se al edo be te ance gor er
@ scanned with OKEN Scanner2024/03/19 09:34
© Scanned with OKEN Scanner2024/03/19 09:3.
© Scanned with OKEN Scanneryer 13 TABLE CREATION AND 569
oot DATA MANIPULATION COMMANDS
2. Primory Key Constraint
This constraint declares a colum i
This constraint is similar to aa ‘he primary key of the table —
one column (or one group of colu; ‘There are differences between
i rim: imns) can be applied
2 ipplied in this
one ae Pas ay keys cannot allow NULL alls ‘hy UMGUE and prMany ie
st applied to columns declared as NOT unique values for each row in a
NULL. Consider the following SQL statement column, but UNIQUE allows
CREATE TABLE employee peed ther
ef ‘Ah, there can
(cade integer oro prinvner, ie “sash
ename char (20) NOT NULL, UNIQUE constraints in 9 table,
sex char (1) NOT NULL, but there can enist only one
grade char (2), column oF ane combanation with
gross decimal ) ; ann en eoeeet
3. Default Constraint
A default value can be specified for a column using the DEFAULT clause. When a user dows not
enter a value for the column (having default value), automatically the defined default value is
inserted in the field. Consider the following SQL statement.
CREATE TABLE employee
( ecode integer NOT NULL PRIMARY KEY,
ename char (20) NOT NULL,
sex char (1) NOTNULL,
grade char (2) DEFAULT ‘E1',
gross decimal) ;
According to above command, if no value is provided for grade, the default value of £1’, will be
entered. The datatype of the default value has to be compatible with the datatype of the column
to which it is assigned. Insertion of NULL (as default value) is possible only if the column
definition permits. (NOT NULL columns cannot have NULL as default). A column can have only
one default value.
4. Check Constraint
This constraint limits values that can be inserted into a column of a table. For instance, consider
the following SQL statement :
CREATE TABLE employee
( ecode integer NOT NULL PRIMARY KEY,
ename char (20) NOT NULL,
sex char (1) NOT NULL,
grade char (2) DEFAULT 'E1',
gross decimal CHECK (gross > 2000) ) ;
This statement ensures that the value inserted for gross must be greater than 2000.
When a check constraint involves more than one column from the same table, it is specified
after all the columns have been defined. For instance,
CREATE TABLE items
(code char (5) NOT NULL PRIMARY KEY,
descp char (28) NOTNULL,
rol integer,
goh integer,
CHECK «(ROL < QOH) ) j
@ scanned with OKEN Scanner© Scanned with OKEN Scanner567
NC
The syntax of CREATE TABLE command is
crea
ABLE
( { ()),
mnnane> cdata type> [ ( ) ... ]) 3
To create an employee table whose schema is as follows
le, ename, sex, grade, gross)
the SQL command will be a
CREATE TABLE enployee Before issuing a CREATE TABLE
( ecode integer, command make assure that its
enane — char(2e), ee
sex char(1), ae
grade char(2),
gross decimal ) ;
When you create a table, you can place constraints on the values that can be entered into its fields.
If this is specified, SQL will reject any values (entered / changed through INSERT/UPDATE
command) that violate the criteria you define. Let us learn about constraints in details.
Zz
3.3.1 Data Integrity Through Constraints
A constraint, in general, refers to a condition or a check that is applied to a column (field) or set
of columns in a table. The constraints applied to maintain data integrity are also known as,
integrity constraints.
‘Once an integrity constraint is enabled, all data in the table
must confirm to the rule that it specifies. Any subsequent SQL A Constraint is a condition or
statement, that tries to enter or modify data in the table, is ___check applicable on afield or set
successfully carried out if and only if the data being entered or OF fckdss
modified satisfies the integrity constraints.
The two basic types of constraints are Column constraints and Table constraints. The
difference between the two is that column constraints apply only to individual columns, whereas
table constraints apply to groups of one or more columns. The following is the syntax for the
CREATE TABLE command, expanded to include constraints :
SYNTAX CREATE TABLE
( [ ( ) ] ,
data type> { ( ) ]
ctable constraint> (, [, ...) «
3
‘The fields given in parenthesis after the table constraint(s) are the fields to which they apply.
The column constraints apply to the columns whose definitions they follow. ‘
For example, if you write the keywords NOT NULL immediately after the data type (and size)
of a column, this means the column can never have empty values (ie, NULL! values).
Otherwise SQL will assume that NULLs are permitted.
4, MULL is a special keyword in SOL that depicts an empty value column having NULL isnot empty but stores an empty
| Value. Two NULLs cannot be added ; subtracted or compared.
Ma,
@ scanned with OKEN ScannerPALTRY ATOR)
© Scanned with OKEN ScannerDp
Table Creation and
Data Manipulation
Commands
Was Charter
413.2 Introduction
132. Databases in MySQL
133 Creating Tables
413.4 Changing Data with DML Commands
435 More DDL Commands
3.1 INTRODUCTION
Uptil now, you have leamt quite a lot about working in MySQL. So far, you have learnt about
writing simple SQL statements and using MySQL functions in queries. This chapter is going
to introduce many new and useful commarids of SQL. In this chapter we shall be discussing
some more commands that let you create tables, add data in tables, modify/change data in
tables, delete tuples from tables etc. Let us begin with table creation command- CREATE
TABLE.
2 DATABASES IN MYSQL
Before you start creating tables, you need a database, which is the container of tables. The
database acts as a central point of administration for the tables in the database. The actual data
is stored in the tables, which provide a structured organization for the data and maintain the
integrity of that data. To create tables, either you can create a new database or use an existing
database. MySQL provides an empty database by the name test, which you can use to store
your tables in. But it is recommended that you create new database before you create a group of
some tables pertaining to a specific application. In the coming lines, you are going to lean how
‘you can create databases in MySQL.
The first step in setting up a MySQL database is to create the actual database object, which
Serves as a container for the tables in that database.
Eo
ial _
@ scanned with OKEN Scanner