L9 SQL
L9 SQL
Will remove the database along with the tables. You can issue the
command show databases; to see whether the db is removed or not.
Creating table (DDL command)
• Syntax: CREATE TABLE <table_name>(
<col1 datatype (size)>,
<col2 datatype (size)>,
<col3 datatype (size)>);
EG: CREATE TABLE emp(
eno int(2),
ename char(20),
sal double(7,2),
address varchar(20),
DOJ date);
• To view the structure of a table
• Syntax: DESC <table_name>; EG: DESC emp;
OR OR
DESCRIBE <table_name>; DESCRIBE emp;
• To view the how the table was created along with its constraints
• Syntax: SHOW CREATE TABLE <table_name>;
EG: SHOW CREATE TABLE emp;
Data Integrity Through Constraints
• A constraints are validations/check/conditions applied on column(s) of a
table.
• These constraints are applied for maintaining data integrity so also
known as integrity constraints.
• Once an integrity constraint is enabled, all data in the table must
confirm to the rule that it specifies.
• There are 2 types of constraints:
1. Column constraints/in-line constraint (applicable to one column)
2. Table constraints / out-of-line constraint(applicable to group(s) of
column(s))
1. Column constraints (applicable to one column)
• Syntax: CREATE TABLE <table_name>(
<col1 datatype (size)> <col_constraint>,
<col2 datatype (size)> <col_constraint>,
<col3 datatype (size)> <col_constraint>);
UNIQUE
constraint
declared
No two values
can be same so
gives an error
saying
duplicate value
NO Null value
will be
accepted
Trying to insert
null value
PK constraint
declared
• In the above eg eno is declared as PK.
• 2nd insert gives error and column values should be unique. Restricting
duplicate entry.
• 3rd insert gives error for NOT accepting NULL values.
Points to remember:
• Unique constraint and PK constraint both will restrict for duplicate
entry.
• Unique will allow NULL values but PK will restrict for NULL values.
• There can be multiple columns with Unique constraints, BUT there
exits only one column with PK constraint.
• Column with PK must be unique, BUT column with Unique may not be
PK.
Different Constraints
• Default constraint: a default value can be specified for a column using
DEFAULT clause. When user does not enter any value for a col then
automatically default value is inserted in the field.
EG:
DEFAULT
constraint
declared
• Here is the different way of inserting values in the student table.
• When values not entered by user than will insert default values into
the table. Check out the following:
Different Constraints
• Check constraint: this constraint limits values that can be inserted into
the column.
• EG:
• Checking for qty order should be less than equal to stock in hand.
Different Constraints
Foreign Key constraint:
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field (or collection of fields) in one table
that refers to the PRIMARY KEY in another table.
• The table containing the foreign key is called the child table,
and the table containing the Primary key is called the
referenced or parent table.
• Syntax:
CREATE TABLE <tab_name>(
<col1> <datatype> size <constraint>,
<col2> <datatype> size <constraint>,
FOREIGN KEY (<col_of_FK) REFERENCES <Parent_table> (<col_of_PK)
[ON DELETE CASCADE | RESTRICT | SET NULL | NO ACTION
Referential Actions: i.e. (UPDATE OR DELETE on Parent
table)
• CASCADE: Delete or update the row from the parent table and
automatically delete or update the matching rows in the child table.
• RESTRICT : Rejects the delete or update operation for the parent table.
• SET NULL: Delete or update the row from the parent table and set the
foreign key column or columns in the child table to NULL. Remember the
column in FK table should not have NOT NULL constraint.
• NO ACTION: Rejects the delete or update operation for the parent table.
Same as RESTRICT.
Make a DEPTNO for DEPT
• Separated tables and table as Primary Key
establishing a link between
them i.e. establishing
relationship. Assign DEPTNO for EMP
table as Foreign Key.
DEPTNO is common col
DNO is primary key in dept table whose values will be referred into the
emp table in col DNO. Here dept table is parent table and emp table will
be the child table.
Adding records
ERROR
Correction in EG4
Emp_id integer, foreign key(Emp_id) references employee(id));
Creating a table from existing table: CREATE TABLE is a DDL
command
• Syntax: CREATE TABLE <new_table_name> as
( SELECT <col(s) > from <old_table_name>
[WHERE <condition>]);
In the above egs class column has NOT NULL constraint declared so cannot add
only roll and name.
• Sec column’s value is automatically inserted as null.
Inserting data in tables: INSERT is DML command
III. Inserting NULL values:
Types of commands:
•DDL (Create table, Alter table, Drop table)
•DML (Insert , Update, Delete and SELECT)
•TCL (Commit, Rollback, Savepoint)
1. WAQ to create database namely STD11. create database std11;
2. WAQ to view all databases. Show databases;
3. WAQ to access the above database use std11;
4. WAQ to create a table emp with the following specifications:
ENO int Primary
Create table emp(eno int primary key,
ename varchar(15) Not Null Ename varchar(15) Not null,
job char(10) Job char(10), hiredate date,
Hiredate date Sal float(7,2) default 0,
Comm float(6,2),
sal float(7,2) default value 0 Dno int);
comm float(6,2)
dno int
5. WAQ to insert at least 10 tuples in the Table: emp
Insert into emp values(10,’bond’,’manager’,’2021-1-16’,6700.00,null,20);
6. WAQ to display eno, job from emp table.
Select eno,job from emp;
By using round
brackets
Performing calculations on MYSQL
• Look at the select statement comm+100 will add 100 to comm whose job is salesman.
• Note this query will only display data.
• All arithmetic operators can be used like(+,-,*,/, % i.e. remainder).
• But if value is NULL then result is also NULL.
• Note NO arithmetic operation can happen on NULL.
Column Aliases
• Giving a temporary name to a column is called column alias.
• EG
11. WAQ to display sal and 10% bonus of sal for the employees working in
dept 10.
Select sal, sal*0.1 as bonus from emp Where dno=10;
Select sal, sal+(sal*0.1) as ‘bonus’ from emp Where dno=10;
Handling null values
• Empty values are represented as Nulls in a table.
• No comparison or arithmetic operations can be perform on null. If performed
result is NULL.
• To replace/substitute a null value with some other value IFNULL() function is
used.
• Syntax: SELECT col1, col2…. ifNULL(col_with_null_val, “substitute_val”) FROM
<table_name> WHERE <condn>;
EG:WAQ to display ename, comm and substitute value for null to “NO comm to
be given” for comm col from emp table.
ANS: select ename, comm, ifnull(comm,"NO comm to be given") from emp;
o/p of the above query
Putting text in the query output
Find the o/p of the given below query
select ename, 'is getting salary',sal+(ifnull(comm,0)) as 'total sal' from
emp;
Given column alias to text column
Sum of 2 Cols alias ie giving temporary
Putting text heading to col
cols
No calculation
can happen on
nulls and results
to null
Relational operators
• Following are the relational operators
= , > , <, >=, <=, <>/ != (not equal to)
<> and != both operators are not equal to.
In character data type comparison < means earlier in the alphabet and > means
after the alphabet. EG ‘e’<‘f’ and ‘g’>’f’.
NOTE char, varchar, date datatypes, when compare must be in single/double
quotes as given in eg.
EG: select * from emp where ename=‘Smith’;
select * from emp where hiredate=‘1991-12-18’;
select * from emp where hiredate>‘1991-12-18’;
select * from emp where ename<>‘Smith’;
Where clause
• Syntax:
SELECT <col1_name>, <col2_name>,….
FROM <table_name>
WHERE <condition>;
11. WAQ to display clerk employees.
Select * from emp where job=‘clerk’;
EG WAQ to displays employees who are getting comm from emp table
Select * from emp where comm is not null;
Logical Operators
All logical operators are used to search a record in where condition. Following are
the logical operators:
• MySQL logical AND operator compares two expressions and returns true if both
of the expressions/conditions are true else returns false. Means it returns the
table with satisfied rows and cols else empty set is shown.
• MySQL OR operator compares two expressions and returns TRUE if either of
the expressions is TRUE else returns false. Means it returns the table with
satisfied rows and cols else empty set is shown.
• MySQL NOT operator reverses or negates the input. Means it returns the table
with satisfied rows and cols else empty set is shown.
15. WAQ to display the clerk employees of dept 10.
Logical
operator and
Logical
operator &&
16.WAQ to display salesman employees who salary is more than 1000.
Select * from emp where job=‘salesman’ and sal>1000;
17. WAQ to display female clerks.
Select * from emp where job=‘clerk’ && gender=‘f’;
18.WAQ to display Bina’s record.
Select * from emp where ename=‘Bina’;
19. WAQ to display whose salary is more than 1200 and in 30 dept.
Select * from emp where sal>1200 and dno=30;
20. WAQ to display employees whose eno is between 8500 and 8900
(inclusive both values).
Select * from emp where eno>=8500 and eno<=8900;
21. WAQ to display the employees either clerk or working in dept 10.
Logical
operator OR
Logical
operator ||
22. WAQ to display employees who are salesman/manager and having
dept as 20.
Select * from emp where (job=‘salesman’ or job=‘manager’) and dno=20;
23. WAQ to display employees who are salesman and not getting comm
from emp table.
Select * from emp where job=‘salesman’ and comm is null;
Logical
operator NOT
Logical operator !
NOTE its mandatory
to put condn in ( )
brackets
Condition based on ranges
• The operator BETWEEN <lower_range> AND <upper_range> is used to display
the records.
• The operator NOT BETWEEN <lower_range> AND <upperr_range> will display
rows not satisfying the BETWEEN condition.
• NOTE: <lower_range> and <upper_range> are included in the range.
• NOTE: BETWEEN…AND comes with pair. (&& is logical operator cannot be
used with BETWEEN operator)
25. WAQ to display the employees earning between 2500 and 3500 (inclusive
of both values)
Select * from emp where sal BETWEEN 2500 AND 3500;
26. WAQ to display the employees who do not earn between 2500 and 3500
(inclusive of both values)
Select * from emp where sal NOT BETWEEN 2500 AND 3500
27. WAQ to display employee name whose emp no is between 8000 and 8900.
Select ename from emp where eno between 8000 and 8900;
28. WAQ to display employees who have join between year 1990 and 1995.
Select * from emp where hiredate between ‘1990-01-01’ and ‘1995-12-31’;
Select * from emp where year(hiredate) between 1990 and 1995;
29. WAQ to display employees who have join between year 1990-6-01 and 1995-6-
30.
Select * from emp where hiredate between ‘1990-06-01’ and ‘1995-06-30’;
30. WAQ to display employee name and salary of those employees who don’t have
their salary between in the range of 2500-3500.
Select ename,sal from emp where sal not between 2500 and 3500;
Condition based on a list (IN, NOT IN operator)
• IN operator is used to specify the list of values. Will selects values that match
in the specified list.
• NOT IN operator is exactly reverse of IN operator. Will display the records
which do not match as specified in the list.
31. WAQ to display employees having destination clerk, salesman or analyst
from emp table
Select * form emp where job IN (‘clerk’, ‘salesman’, ‘analyst’);
33. WAQ to display emp names not starting with letter ‘a’
Select ename from emp where ename NOT LIKE ‘a%’;
34. WAQ to display emp names ending with letter ‘a’
Select ename from emp where ename LIKE ‘%a’;
35. WAQ to display emp names not ending with letter ‘a’
Select ename from emp where ename NOT LIKE ‘%a’;
36. WAQ to display emp names who have letter ‘a’ in them.
Select ename from emp where ename LIKE ‘%a%’;
37. WAQ to display emp names who do not have letter ‘a’ in them.
Select ename from emp where ename NOT LIKE ‘%a%’;
38. WAQ to display emp names whose name is exactly 4 letter names.
Select ename from emp where ename like ‘_ _ _ _’;
39. WAQ to display emp names who has 2nd letter as ‘a’ in their names
Select ename from emp where ename like ‘_a%’;
40. WAQ to display emp names who has 1st letter ‘b’ and last letter ‘a’ in
them.
Select ename from emp where ename like ‘b%a’;
Sorting results-ORDER BY clause
• ORDER BY <col_name> [ASC] clause is used to sort the data in ascending order by
specifying col_name
• ORDER BY <col_name> DESC is used to display the data in descending order.
• Syntax: SELECT <col1_name>, <col2_name>….
FROM <table_name> WHERE <condition>
ORDER BY <col_name> [DESC];
44. WAQ to display the employees having sal more than 3500 in the alphabetical
order of their job.
Select * from emp where sal>3500 order by job;
45. List the employees in the descending order of their employee nos.
Select * from emp order by eno desc;
46. List the employees in the descending order of their employee nos. whose salary is
between 3000-4500
Select * from emp
where sal between 3000 and 4500
Order by eno desc;
More DML commands
• DML(Data Manipulation Language) when any changes made inside the
table is called DML commands. Following are DML commands:
1) INSERT INTO <table_name>
2) UPDATE <table_name> SET <col_name> = <new_val>
[WHERE <condition>];
3) DELETE FROM <table_name> WHERE <condition>;
49. WAQ to double the salary of salesman and clerk from emp table.
UPDATE emp SET sal=sal*2
WHERE job = ‘salesman’ or job=‘clerk’;
50. WAQ to give 500.00 comm to all clerks from emp table.
Update emp set comm=500.00 where job=‘clerk’;
51. WAQ to set comm as Null values to clerks from emp table.
Update emp set comm=null where job =‘clerk’;
53. WAQ to change the name of Anoop to Anup from emp table.
Update emp set ename=‘Anup’ where ename=‘Anoop’;
Syntax : DELETE FROM <table_name> [WHERE <condition>];
54. WAQ to delete Anoop’s record from emp table.
DELETE FROM emp WHERE ename= ‘anoop’;
55. WAQ to delete the records who do not earn comm from emp table.
DELETE FROM emp WHERE comm is NULL;
56. WAQ to delete the employees whose eno is greater than 8700 from
emp table.
DELETE FROM emp
WHERE eno>8700;
57. WAQ to delete the employees whose job is clerk or salesman from emp table.
DELETE FROM emp
WHERE job = ‘salesman’ or job=‘clerk’;
59. WAQ to delete all records from emp whose sal is less than 1000.
Delete from emp where sal <1000;
60. WAQ to delete all records whose sal range between 800 – 1500.
Delete from emp where sal between 800 and 1500;
More on DDL commands
• DDL(Data Defination Language) when any changes made to the structure of a
table is called DDL commands. Following are DDL commands:
1) CREATE TABLE <table_name>
2) ALTER TABLE <table_name>
3) DROP TABLE <table_name>
Note: you can add one or more columns. If adding more columns then columns names to
be typed in round brackets ( … ) else type ADD two time as given in another syntax.
Note: adding constraints is not mandatory.
61. WAQ to make a copy of emp table as EMPL.
CREATE table EMPL AS SELECT * FROM emp;
(NOTE: all values (if any) from emp table will also get copied in EMPL table)
(NOTE :default value Policy_no 0 will get added to empl table and NULL to loan_type)
64. Add a new column to empl table GRADE with char(10) and NOT NULL
constraint.
NOTE: col added with NOT NULL constraint will add nothing to col.
65. WAQ Add a new column to empl table GRADE with char(10) and DEFAULT value as
‘A1’ constraint.
66. Add a new column to empl table DOB with date datatype with NOT NULL
constraint.
(NOTE: by default 0000-00-00 i.e. YYYY-MM-DD date)
66. WAQ to add primary key to eno of EMPL Table.
ALTER TABLE empl ADD PRIMARY KEY(eno);
Issue command
DESC empl; and see
column Key PRI is
added
67. WAQ to add Unique constraint to column DNAME in DEPT table
Issue command
DESC dept; and see
column Key UNI is
added
68. Add FK to table Orders to column ITEM_NO referencing table ITEMS
who has IT_No as Primary key.
Create table Items(IT_No int primary key,
Item_name char(20), ….. …..);
NOTE: Items and Orders table was already created. Then only can be
altered.
• Syntax for modifying column definition : i.e.
1) Modifying datatype i.e. changing datatype from int to char/varchar
(NOTE: changing char to int is possible only if table is empty)
(NOTE: Any datatype to char/varchar is possible)
2) Modifying the column by adding PK and Unique
3) Modifying the datatype size.
(NOTE: size of datatype can be increase/decreased BUT can be decreased
only if the data is upto the length specified)
4) Modifying the column order like first col can be moved to last
permanently.
1 int ‘a1’ char ‘1’
‘1’ char Not possible to convert to int can convert to int
ALTER TABLE <table_name>
MODIFY (<col_name> <new_datatype(new_size)> [FIRST| AFTER <col_name]);
69. WAQ to change the datatype from char(8) to char(20)
ALTER TABLE <table_name>
MODIFY (<col_name> <new_datatype(new_size)> [FIRST| AFTER <col_name]);
70. WAQ to change the datatype from char(20) to varchar(25)
ALTER TABLE <table_name>
MODIFY (<col_name> <new_datatype(new_size)> [FIRST| AFTER <col_name]);
70. WAQ to change the datatype from varchar(25) to varchar(5)
Col cannot be
modified as there is
data in sname column.
So giving error.
Col can be modified
only if there is no data
or length specified
upto to the col’s value
• Column’s datatype size can be modified only if the length of data
matched to the value of the column.
• EG ‘superman’ has length 8 so can be modified up to 8.
• Note:if the col is empty then can be modified i.e. decreased or
increased.
71. Add PK to column sname of student table using modify clause.
72. Add unique constraint to column sname of student table using modify clause.
OR
71(i) Add PK to column sname of student table
Alter table student ADD primary key(sname);
72(i). Add unique constraint to column sname of student table
Alter table student ADD unique(sname);
73. WAQ to make eno col as last column
Default value 0
added to ph col
using modify
clause
• Syntax for change column’s
heading/title i.e.
1. Change clause is used to change
col’s heading and datatype size.
ALTER TABLE <table_name>
CHANGE [COLUMN] <old_col_name>
<new_ col_name > datatype(new_size);
NOTE you must know to foreign key constraint’s name before deleting/
dropping it.
To see the foreign key constraint’s name issue a command
SHOW CREATE TABLE <table_name>;
81. WAQ to drop primary key by giving cascade option from dept table.
ALTER TABLE dept
DROP PRIMARY KEY CASCADE;
#The cascade option drops any foreign key that reference the Primary Key.
82. WAQ to delete the unique
constraint of col stud_name from
stud_info table.
Syntax: ALTER TABLE <table_name>
DROP CONTRIANT <uni_cons_name>;