0% found this document useful (0 votes)
16 views

9) 11th LESSON 11structured Query Langauge

Uploaded by

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

9) 11th LESSON 11structured Query Langauge

Uploaded by

DIVIJ VERMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

LESSON-11

STRUCTURED QUERY
LANGUAGE
STD -11
INFORMATICS PRACTICES(13 T H EDITION SUMITA
ARORA)
I) CREATING A DATABASE-topic 11.4-DataBases in Mysql 11.4+11.7 Show databases like<‘database name’>
Create database <database name>
VI) CREATING A TABLE- Show databases like ‘world’;
Eg-> Create database 11b; Create table tablename Without ‘’ error
Or (colname dt,
Create database [if not exists] <database name> Colname dt, int/integer default size 11
Eg-> Create database if not exists 11b; Colname dt);

II) OPENING DATABASE


default size is 1
Use <database name>
2.6
Eg -> use 11b; Whenever u want 22.22
to work with the 234.22 error
III) REMOVING DATABASE item table next 332.2 error
time 32.228 no error but
drop database <database name> 32.23 will get stored
Decimal(4,6)error
Eg-> drop database 11b; ‘yyyy-mm-dd’ Default(10,0) If default
have to give the and u enter 12.20 it will
IV) SEE DATABASE- store only 12 into the col
length else error 10.511
show databases; VII) VIEW THE STRUCTURE OF THE TABLE-
V) SEE TABLES- describe <table name>
Or
Show tables; desc <table name>
Eg desc item;
It shows you the column names ,DT ,null , key ,Default values and Extra.
VIII) INSERTING RECORDS-
insert into <tablename>
values(‘string’,no,’date’)

Mysql tables
are not sorted
ITEM TABLE by default

Prog1- Insert the following rows into the item table


Inserting null values- 2 ways
a)Insert into item
values(3,’box’,null,’2009-01-01’,’C001’) ;
or
b) Insert into item(itemno,itemname,dop,custno)
values(3,’box’,’2009-01-01’,’C001’);
IX) Topic 11.7 Making simple sql Queries VIEW THE CONTENTS OF THE TABLE-
Prog4- Selecting all columns-
1) SELECT COMMAND- Select * from <tablename>
Prog2-Display itemno and name from the item table

2) ELIMINATING REDUNDANT DATA-


Prog5- Display the diff customers from the item table
Prog3-Change the order of columns Select distinct custno
from item;

only 1 null is returned


You need to write distinct only once in the Select statement, it will get applied to all the columns.
Eg-

3) USING THE ALL CLAUSE-


The opposite of distinct is ‘all’. It is the same as not writing(distinct or all).It will display all the values from a column,
including the duplicate values.
Prog7-(repeated)
Prog6-
4) PERFORMING CALCULATIONS-
Prog-8 Note-
Dual table is provided for compatibility with SQL of other DBMS.
Dual table is a small workable table which has 1 row and 1 column. It can be used for calculation
results and also for system-date.
It is a special one row, one column table present by default in Oracle database. Mysql allows
DUAL to be specified as a table in queries that do not need data from any tables.
Prog-9-WAQ to display the current date- 5) SCALAR EXPRESSIONS WITH SELECTED
Select curdate(); FIELDS-
Or (I,e, to perform calculations with selected fields of
Select curdate() from dual; the table.
Prog-9_a

curdate()
or
current_date()
or
current_date
Note- If any value is null then the result is null.
You can make use of -*+/ or % for calculations.
6) USING COLUMN ALIAS-
I,e, giving different temporary names to the columns of the table is called ‘column alias’ for output purpose only.
Prog10-WAQ to display the dop and custno with the column name as Date of Purchase and Customer Number as
column names-

Note- When the new col name is more than 1 word, it has to be
included in quotes (double quotes or single) or else if the new
column name is only one word no need of quotes.
Giving column alias to an expression-
Prog-11-select 22/7 as “pi”;
Eg-
7) HANDLING NULLS-
An empty value is represented as NULL in a table.
Prog12-

You can see the null


values in the price
column.

SUBSTITUTE A NULL VALUE WITH A GIVEN VALUE BY USING ifnull() function.


Prog13- Prog14-
Prog15- WAQ to display the name ,price and dop from the item table and incase of any null entries in the dop
column replace them with the current date.(Also give a column alias to the dop column as “New Date”) Item table

Added a new row (last one)

It is not necessary that dt of dop and the new


value should match.

It is not necessary that the dt of custno and


the new value should match.
9) PUTTING TEXT IN THE QUERY-
Prog18-
Prog16-<itemname><price*100>% <itemname>has<price>price and has<price*100>%

10)WHERE CLAUSE-
Prog17-<itemname> has the price<price*100>% Till now we were putting conditions on which columns you
wanted to see now lets put condition on rows.

We can put conditions on rows using the where clause-


Prog19-WAQ to display the price of item no1.
Rem the order
Select
From
Where
Prog20-WAQ to display the item names whose
RELATIONAL OPERATORS-
price is greater than 20. >, < ,>=,<=,<> OR !=,=

Mysql recognises the above


relational operator and the
results is either True(1) or False(0)
-IN CHARACTER DATA-comparison< means earlier(before) and
> means later in the alphabet. Also works with date and time.
Eg ‘a’<‘b’ and ‘b’>’a’
-ALL DATE,TIME data need apostrophe around them
Prog21-Display the itemnames and itemnos where
price is greater than or equal to 20; Prog22- Display the itemnames and itemno where customer
is not C001;

Prog23- Display the itemnames and itemno where customer


is not C002;
Select itemname,itemno
From item
Where custno!=‘C002’;
LOGICAL OPERATORS-
AND , && They are used to join the conditions in the where clause
OR, ||
NOT
Prog24-WAQ to display all the details from the item table where the itemno is 1 or 2

OR
If both 1 and 2 are present then
both the results will be displayed.

OR

Prog25- WAQ to display all the details from the item table where the itemno is less than 3 and the price is less than 20.

AND

OR
Prog26-WAQ to display the details for itemno1 and 2

If you put the condition with and then the query will not work since there is no record with itemno1 and 2.So even
if the query says ‘and’ you have to understand it is ‘or’. This problem comes when we are referring to the same
column again.
Prog27-WAQ to display itemname, itemno and price for all the items where the itemno is not 5

NOT

Or where itemno!=5;
Or where itemno<>5;

Rem the NOT logical operator comes before the column name
Prog28-WAQ to display all the details for items other than pen

where itemname<>’pen’;
Or
where itemname!=‘pen’;

Prog29-WAQ to display the details from the item table where the item no is 1 or 2 and the price is greater than 19.

Not
And
or
11) CONDITION BASED ON RANGE- BETWEEN
NOT BETWEEN
For conditions based on ranges we make use of between and not between operators-
Prog30-WAQ to display all details from the item table where the item numbers are between 1 and 3

Prog31-WAQ to display all the details for the items not having itemnos between 1 and 3
Prog32-WAQ to display details of items whose price ranges between 10 to 20

12)CONDITION BASED ON LIST IN( ‘ ’ , ‘ ’)


NOT IN( ‘ ’ , ‘ ’)

Prog33-WAQ to display the list of items from Pen, Pencil or book

Or

Prog34-WAQ to display details of items which are not pen and pencil.
Prog35- WAQ to display details for items with numbers 1,3 or 5

Prog36-WAQ to display details for items with numbers not 1,3 or 5

‘A%’starting with the letter ‘A’


‘%e%’containing ‘e’
‘ _ _ _ _’exactly 4 characters
‘_ _ _%’atleast 3 characters

13)CONDITION BASED ON PATTERN MATCHES LIKE ‘% _’


Wild card characters % _
NOT LIKE ‘%_’
Egs-
%The percent(%) character matches any sequence of zero or more characters in a string
Prog37-WAP to display all itemnames starting with the letter ‘P’

Prog38-WAP to display all the itemnames ending with letter ‘k’

Prog39-WAP to display details of items whose names do not begin with the letter ‘p’
Prog40-WAP to display all the item names starting with ‘wx%ab’

Prog41-WAP to display names starting with ‘wx_ab’


14)SEARCHING WITH NULL
is null
is not null
Relational operators(>,
Prog42-WAQ to display the itemnames having exactly 4 characters. < ,=,<=,>=,<>) cannot be used
with null
Prog43-Display the details of all the
items which do not have a custno.
Prog44-WAQ to display the details of items which have 15)SORTING RESULTS- ORDER BY CLAUSE
customer numbers. asc-nulls come on top
desc-nulls come at the end
SELECT
FROM LEARN THE ORDER
WHERE
ORDER BY COL
Prog46-WAP to display list of items in alphabetic
order of their names
Prog45-WAQ to display the details of the items
whose price is not given.

optional
Prog47- WAP to display all the items sorted by itemnames but only for items whose price is more than 20

Sorting is not a permanent change in the database it is just a temporary


change.

Prog48-WAP to display list of items in descending order of their item numbers.


Prog49-WAP to display all details of items in ascending order
of item names , but those with same item names should be
shown in the descending order of price.
Some more egs
Eg1

Eg2
SORTING WITH COLUMN ALIAS
Another
Prog50- eg

MAKING A COPY OF A TABLE


Prog 52-

Prog51- CREATING A VIEW Views are virtual tables


that do not store any
data of their own but
display data stored in
View v1 other tables.
Views are nothing but sql
queries. A view may
contain all or few rows
from the table.
You can use a view to
hide table columns from
Making a newitem table from the item table as a
users by granting them copy.(constraints do not get copied)
access to the view and
not to the table itself.
This helps enhance data
security and integrity.
PRACTICAL PRACTICE
Prog1-Create a database called today

Prog2- Open the database

Prog3- create the dept table in the database called today.

Prog4- Insert all the records in it-


Prog5-Display all the diff department locations from the dept table Prog8-Display the current date

Prog6-View the structure of the dept table

Prog9-Display the dname column as


department name
Prog7- Increase the deptno by 10 while displaying-
Prog10-Display the foll format
<dname> gives<sal> Rs Monthly and <sal*12>Rs yearly annual salary and give the
name to this column as Annual Salary.

Prog11- Display the dept names of deptnos less than 40

Prog12-Display all the deptnos where there is no salary given


Prog13- Display all the deptnos which are not equal to 10 Prog16- Display the deptnos which are 10 and 30

Prog17- Display dept name which belonging to deptno


10 or 20 and are given no salary
Prog14- Display the deptnos where the loc is not Pune

Prog18-Display the dept details where the deptno is


not 10(using the not logical operator)

Prog15- Display all null values of salary column with 0

or
Prog19-wap to display dept details of deptnos ranging from 20 to 40 Prog22-same as 21 but with the not

Prog23- Display all the dnames


Prog20-same with not ranging between 20 and 40 containing the letter ‘E’ in them

Prog21-Display the deptno of departments ACC, Sales, Adv, adm using IN clause.
Prog24-WAP to display dept details
from the dept table whose dnames
are made up of exactly 3 characters
Prog25-WAQ to display all dnames containing the letter ‘a’ .
Prog28-WAQ to display loc sorted in ASC order

Prog26-WAQ to display deptno where no salary is given


Prog29-WAQ to display loc sorted in descending order
and for deptno 1, 2 or 3

Prog27-WAQ to display deptno where salary is given

Prog30-WAQ to display details from the dept table


sorted in ascending order of loc and desc order by
dname
Prog31-Give a column alias to dname as DepName and sort in ascending order using the new name

Prog34-Look for a specific database ‘world’

Prog32-Create a copy of the table dept called deptnew but for deptnos 20 and 30 only

x----------------x
Prog 33- Create a view called v1 from dept having deptno 1 in it. End of practicals
IMPORTANT POINTS AND PRGRAMS FROM THE TOPIC COVERED SO FAR FROM THE TEXT BOOK(11.4+11.7)

Prog1-Write SQL commands to check if a database by the name newdb exists on Mysql.If not then create a new
database by this name.

Show databases like ‘newdb’;


Create database if not exists newdb;

Note-Before issuing a create table command, make sure that its parent database has been opened using
Use<database name> command Prog3-Display species of all pets
from table pet
Note-The order of the selection determines the order of display. Select all species from pet;

Prog2 - Display distinct species of pets from table pet;

Select distinct (species)


From pet;

Note-distinct and all both together cannot be used in the same select query.

Note-To perform calculations may either write expression with select or use table dual(in from clause),which is a
one row.one column dummy table, provided by mysql.

Note-select is a DML command.


Note- column alias name having more than one word, should be enclosed in quotation marks
Prog3 In a table student, WAQ to display name, gender and aggregate/5.Label this computation as percentage.
Select name, gender, aggregate/5 as percentage
From student;

Prog4--Display the name age and marks(aggregate) of students whose age is greater than or equal to 16 from the
table student

Select name,age,aggregate
From student
Where age>=16;

Prog5-WAQ to display all the details from pet table for species cat/dog having gender as male;

Select * from pet precedence


Where (species=‘cat’|| species=‘dog’)&& gender=‘m’; NOT
AND
Note-Pl go through the precedence table of Operators on page 386 OR

x---------------x
STRUCTURED QUERY LANGUAGE-(11.1+11.2)
I) INTRODUCTION TOPIC-11.1 Pg 355
II) SOME MYSQL SQL ELEMENTS- TOPIC -11.2 Pg 355
◦ i literals
◦ ii datatypes
◦ iii nulls
◦ iv comments

To make an
unsigned int in
mysql

Float(10,2)
Double(16,4)

Decimal(10,0)
Char varchar
1.Fixed length string 1.Variable length string
If u give the length of 10 If u give a length of 10
and enter only 5 and enter only 5
characters the remaining characters the remaining
length will be filled up by length is freed off in
spaces. memory
2.Default length is 1 2. It is mandatory to
specify a length else you
get an error

Topic 11.3(Just read it) SQL


command Syntax

x------------x
End of topic
Topic 11.6-INSERTING DATA IN TABLES-
TOPIC-11.5(CREATING TABLES)
DATA INTEGRITY THROUGH CONSTRAINTS
Def- Constraint-A constraint is a condition or check applicable on a field or set of fields. The constraints applied to
maintain data integrity are also known as integrity constraints.
After enabling an integrity constraint all the data entering is checked if it satisfies the constraint or not. If it does
it is allowed to enter else not.
Two Basic types of constraints are-
(i)Column constraints(applicable to one column)
(ii)Table constraints(applicable to groups)

Column Level(In-Line definition) Table Level(out of line definition)


1.Meant for specific, individual columns 1.Meant for a group of columns
2.Is written in the same line of the 2.Is written after all the columns are
column definition. defined but before closing the table
3.Not Null and Default constraints are 3.Composite Key is a table level
column level constraints. constraint.
 Before we create a table we need to open the database
 A table should have at least 1 column
 You can specify constraints while creating a table

1.Primary key(both) constraints


2.Not Null (column)
3.Default(column)
4.Unique(both)
5.FK(both)[works with Table-
level)
6.Composite PK(Table)
7.Check(both)
1) Not null not required for PK
DIFFERENT CONSTRAINTS-
2) 2 constraints put as column level then
1) PRIMARY KEY- (BOTH) drop table stud; no commas needed in the middle of the
two.
This key uniquely identifies every row in a table.
Prog1-Create a table stud with rollno and name as 2 columns and make rollno the PK.
Column Level Table Level
Check the structure of the table stud

Try entering duplicate values in the stud table it will give an error

2) COMPOSITE PRIMARY KEY- (TABLE LEVEL) This constraint does not allow the combinations of the composite
key columns to repeat.
Prog-2 Make a table stud with rollno and name as a composite key

3) NOT NULL CONSTRAINT-(COLUMN LEVEL)


This constraint does not allow the column to have a null value in it.
Prog-3 Make a table stud and give the name column as a not null constraint.
4) DEFAULT CONSTRAINT- (COLUMN LEVEL)
This constraint assigns a default value to the specific column if left blank.
Prog4-Make the stud table with rollno, name and marks column. Give a default constraint to marks as 50

1. Default with PK
works only once
2. 1 col can have only
1 default value
3. If no default and a
not null constraint
then – entry to be
done becomes
mandatory.

Give a default constraint to name as ‘aaa’


Create table stud
(rollno int,
name char(20) default ‘aaa’);

Q what happens if we do not enter a value into a column of a table?


5) UNIQUE CONSTRAINT-BOTH
This constraint does not allow duplicate values into the column like Primary key but allows null values to be
entered(many nulls)
Primary key Unique constraint
1. Does not allow duplicate values to be 1.Like a PK does not allow the column to
entered into the column and also does have duplicate values, but allows null
not allow the column to contain null values.
2. A Table can have only 1 PK 2. A table can have multiple Unique
constraints
3.All PKs are unique 3.All unique are not PK’s

Prog5-WAQ to make the stud table with rollno and name and assign a unique constraint to the name column.
Column level desc stud Table level
What will happen with the following query-
Create table stud This will behave separately
(rollno int, Create table stud
name char(20) unique not null, (rollno int,
marks int); Name char(20),
Don’t put a comma between 2 constraints in column level
Unique(rollno),
Unique(name));
Now the above name column will behave like a PK

Prog 6-WAQ to make the stud table and assign a unique constraint to rollno and name of the stud table.
Column level Table level
When u assign a unique constraint
to more than 1 column as a table
level constraint, then it starts to
behave like a composite key but
allowing nulls.
This method is preferred
(6) CHECK CONSTRAINT- BOTH
This constraint limits the values that can be inserted into a column of a table.(puts checks on cols)
Prog7- Make a stud table with rollno and name and the rollno should be greater than 10;

Column level
Error for rollno =10
Table level
Create table stud error
(rollno int,
Name char(10),
grno int check (grno>rollno));

Error for rollno <10

**check can use all the operators and clauses like


IN, BETWEEN , LIKE(PATTERN MATCHES)

**If the check constraint is to be put onto a column


and the condition itself is made up of the table columns
then prefer to use the table level way of applying constraint.
Prog8-
create table stud
(rollno int,
name char(10),
grno int,
check(grno>rollno));

The 2 columns grno and rollno should be defined


7) FOREIGN KEY CONSTRAINT- (BOTH)(works Table Level)

Def-FK-A Fk is a non key which gets its value from the PK of another table. It enforces referential integrity.

Def Referential Integrity- It is a system of rules that a DBMS uses to ensure that relationship between records in
a table are valid and users don’t accidently delete or update any related data.

Before putting a FK
-Both the tables should be in the same database
-Both cols should have the same(similar) dt.
U cannot assign FK without it being the
-A FK of a child table must refer to the PK or unique of a Parent table
PK or unique key in the parent table
-Names may be different.

After putting the FK


-cannot delete a related record from the PK which has a related record in the FK
-cannot update a related record from the PK which has a related record in the FK
-cannot make an entry in the FK which is not present in the PK
-FK values can contain null
-FK values can repeat Pk FK
Pk or unique Itemno Iname Price Ordno Qty i_no
1 pen 20 1 pen 1
Prog9-
Item1 table Order1 table
Prog9-
1)First create the table item1 with pk or unique on itemno and add 2 rows
in it as given
2)Now create the order1 table with PK on ordno and Fk on
i_no. PK Order1 FK
table

Links FK

Table level
create table order1
(ordno int, Column level
qty int,
i_no int,
primary key(ordno),
foreign key(i_no) references item1(itemno));

Error cause
itemno-3
does not
exist in
the
item table
*FK works only as a table level constraint
*If given as column level, it will not display an error message but will not check the referential integrity.
FOREIGN KEY

STUDENT TEACHER
Pk FK
Rollno name Tid rollno
1 aaa 11 1
2 naa 12 1
13 2
Prog10- Create both the tables above and make a FK at rollno of teacher table such that if u delete or modify a
PK value ,it should get modified or deleted in the FK .
Now update an entry in the rollno column of the student table, you will automatically see the change in the
teacher table. CASCADE is called a referencing action
On delete cascade Other referencing actions-
On update cascade RESTRICT-rejects the operation
NO ACTION-not allow deletion or updation of
the PK as long as there is a related record in the
FK. (same as not writing)
SET NULL-will set null in the FK

*no action and restrict are almost identical just


that no action first checks for the related
records and then if there is a related record it
restricts the change else allows it. Whereas
restrict always restricts the action.
You can also link a FK to a column in the same table and this is called
Both have changed from 1 Self referencing.
to 11 automatically
1 (1)
Extra
2 (1,2)
3 (1,2,3)
4 (1,2,3,4)
Emp table Extra
Will give an error for 3(mgrno) From this
since 3 is not present in the slide write
PK(empno) only the
note

Note- if u give 2 constraints as column level then no comma


If u give 2 constraints as table level then comma between
them.
eg
FOREIGN KEY AND DATABASE ENGINE-
Mysql is capable of creating databases in many diff database engines that offer diff features.
The default database engine is ISAM but it does not support FOREIGN KEY. So if u find that your Fk is not working
then u need to change the database engine to InnoDb database engine using the foll command-

Alter table <tablename>


ENGINE=innodb;

Prog11-First check the database engine using the command:-


Database engine
show create table <table name>;
Topic 11.5.1C ASSIGNING NAMES TO CONSTRAINTS-
By default, Mysql assigns a unique name to each constraint defined by you as SYS_Cn where n is an integer that
makes the constraint name unique. Eg SYS_C003217.
But we can ourselves name a constraint created by us.

Syntax :- CONSTRAINT<name of constraint><definition of constraint>


We can name constraints only in a table level method and not in a column level. So the default and the not null
constraint cannot be named.
(b) Naming a unique constraint
(a)Naming Primary key- Prog13-
Prog12-
(c)Naming check constraint-
Prog14

(d)Naming foreign key-


Create table orders whose itemno is a foreign key to the item tables itemno. Name the FK as F1.Also when the
itemno from the item table is deleted, the entry should be removed from the Foreign tables.
Prog15

x-----------------x
End of topic
Prog16-
Pg 368

Prog17-
Prog18-
Pg 368
Show create table item;

STRUCTURE OF TABLE Emp_id int,


Foreign key(emp_id) references employee(id));
To see the structure of the table:
Desc <itemname>
Or
Show columns from <tablename>
Pg -370 Eg5
Prog19- Pg-370 Eg6

Prog20-
TOPIC- 11.8 MORE DML COMMANDS- 1)insert
2)update
2)UPDATE COMMAND 3)delete

Syntax- update<table name>


set <colname>=<new val>,<colname>=<new val>…
[where]

Prog21- Change the price of pen to 50

Prog22- Increase the price of itemno 1 by 10%


Prog23-WAQ to change the itemname to ‘card’ and dop to the 2020-09-09 for itemnos between 1 and 4.

Where itemno>=1 and itemno<=4;

where itemno in(2,3);

Prog24-Change the itemnames of itemnos 2 and 3 to ‘ppp’


Note- u can also set the value of a particular column to NULL
Update item
Set price =NULL
Where custno=‘C001’;
3)DELETE-
Syntax- delete from <tablename>
[where<condition>]

Prog25-Remove the record with itemno 3

Prog26- Remove all the data from the item table.


Topic 11.9 DDL COMMANDS- Create table
Emp
Drop table <table name> table

Alter table add New cols PK,FK,Check,Unique order of the cols


With all For exisiting cols for new cols
drop constraints
Columns,
Constraints Pk,Fk modify
Alter table <tablename>
Modify <colname> new def;
ds|dt|not null ,default|order of the cols
for exisiting cols
Change
Name of column Alter table <tablename>
Change oldname newname newdef
Alter table <tablename>
ALTER TABLE COMMAND-
Syntax- Add <colname> def;
(i) Add clause-
Prog1- WAQ to add a column job to the emp table with datatype as varchar(20)

NULL
Prog2- Add a column commission to the emp table with default value as 0.

Prog3-Add a new col as doj with a default date as ‘1999-02-02’ Default value has come to 0

Default
value
Prog4-Add a col salary with a not null constraint

If u add a col with a not null constraint and also don’t give it a default value then it takes the value according to the dts
Eg- int 0
Char/varcharspace
Date0000-00-00
Time00:00:00
Prog5-WAP to add a col address with a not null constraint

Prog6-Add a col hiredate to the existing table of data type date

Prog7- Add a PK to the ecode.


Prog8- Add a check constraint to salary where sal<10. Prog10_a Add a new column called loc and make it the first
column in the table emp
Alter table emp
Add loc char(10) first;
Prog9-Add a unique constraint to ename
Prog10_b Add a new column called loc and make it the 2nd last
column in the table emp
Alter table emp
Add loc char(10) after address;
Prog10-Create a table called shop with shopno and empno where empno must be the foreign key to the empno of
the emp table. The table shop should be already created with its two columns. Later add the FK and name it as F2.
Shop shopno emp Empno
Empno(FK) (PK) or
(unique)
Alter table shop
Create table shop Add constraint F2 foreign
(shopno int, key(empno) references
empno int); Emp(empno);

Create table emp


(empno int Primary key);
Prog11-WAQ to add 2 columns col1 and col2 of both int dt to the items table in one query.

Alter table <tablename>


(ii) Modify clause- syntax Modify <colname> new def
Prog1- Change the dt of ename to varchar(30)
Prog2-WAQ to change the data size of ename to varchar(20) (if no data of length more than 20 is into the table)

Prog3-Add a not null constraint to enamewill work if the ename col has no null values

Prog4- Add a default constraint to the job col of the emp table as clerk;

Default value clerk


No change to the previous data has come

To check the default constraint


CHANGE THE ORDER OF THE COLUMNS-
ALTER TABLE <TABLENAME>
MODIFY <COLNAME> NEW DEF FIRST|AFTER <COLNAME>
Prog5-Make salary as the first column in the table

Prog6-Make the salary as the last column

Prog7-WAQ to modify 2 cols in the same query-


Change ds of ename to char(10) and dt of salary to decimal(4,2)
(iii) change clause- syntax alter table <tablename>
change oldname newname new definition;
Prog1-WAQ to change the name of the column address to loc-

Prog2-WAQ to use the change clause , to change the dt of loc to varchar(20)

(iv) Drop clause-


syntax alter table <tablename>
drop column|constraint;

Prog3-WAQ to drop the column ename from the emp table


Alter table emp
or Drop column ename;
Prog4-Drop the PK from the table emp

Note-PK will be removed only if there is not FK attached to it. You do not need the
name of the PK to delete it since there is only 1 pk in a table.
drop primary key cascade;

Prog5-Even if not null and default key have no name then also we can remove them by redefining them.
Remove a not null constraint from ecode col .

Prog6-Drop the FK from the table shop which links its employee number to the empno of the emp table-
Alter table shop
Drop foreign key F1;
DROP TABLE COMMAND-
Prog7- Delete the entire table try with its data.
or

x---------x
End of topic
IMPORTANT POINTS IN THE TB RELATED TO THE TOPIC 11 .9
Prog1-WAQ to add 2 cols name1 and name2 and also give a check constraint to col name2 that
it should contain only ‘aaa’ and ‘bbb’ as names.(in one query)
OR

Prog2-eg 21 pg 390 Note-u can add a col with a


Prog3-eg-22 pg 390 not null constraint only to a
table that contains no null
values so far.
Note-u can change the dt
and ds of cols which
contain data pertaining to
that condition.

No need of bracket ( )
Prog4-Eg23pg391
Prog5-Eg24pg391

Don’t
use the
bracket
with
modify
Prog6-eg25-pg392
Alter commission drop default;
Prog7-eg26-pg392
Prog8-eg27-pg392
Prog9-eg28-pg392

Note-Mysql will OR
reject the FK if its alter table sales Now() is static and
database engine is Modify commission int default 1000; Sysdate() is dynamic
not INNODB.
So your query
involving a FK
constraint may be
rejected also.
Prog10-eg29pg393
Prog11-eg30pg393
Prog12-eg31pg393

Only for default


constraint ,this
syntax does not
work for not
null constraint.

Or
Alter table sales x------------x
Modify commission int; End of lesson
ASSIGNMENTS
MCQ PG 325
New-pg 395
T
New page 411

sports

sports

sports

,dop
or

Not in syllabus

x-----------------x Where doj >=‘2012-01-01’ and doj<=‘2012-12-31’;


End of lesson

You might also like