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

L9 SQL

The document discusses SQL and its elements. SQL was developed in the 1970s and is a non-procedural query language that allows users to tell a database what data to retrieve without specifying how. SQL includes elements like data types, literals, comments, and integrity constraints. It also describes how to create databases and tables in SQL.

Uploaded by

Hari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

L9 SQL

The document discusses SQL and its elements. SQL was developed in the 1970s and is a non-procedural query language that allows users to tell a database what data to retrieve without specifying how. SQL includes elements like data types, literals, comments, and integrity constraints. It also describes how to create databases and tables in SQL.

Uploaded by

Hari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 128

Lesson -9

Structured Query Language


(SQL)
Introduction
• SQL was developed in 1970s in an IBM Laboratory.
• SQL is also referred as SEQUEL in 4th generation non-procedural language.
• SQL is divided into :

• In procedural query language, user instructs the system to perform a series of


operations to produce the desired results. Here users tells what data to be
retrieved from database and how to retrieve it.
• In Non-procedural query language, user instructs the system to produce the
desired result without telling the step by step process. Here users tells what
data to be retrieved from database but doesn’t tell how to retrieve it.
• For example – Let’s take a real world example to understand the procedural
language, you are asking your younger brother to make a cup of tea, if you are
just telling him to make a tea and not telling the process then it is a non-
procedural language, however if you are telling the step by step process like
switch on the stove, boil the water, add milk etc. then it is a procedural
language.
• So, SQL is non-procedural language and that is what makes it simple, it makes
an RDBMS (Relational DataBase Management System) possible.
• SQL being non-procedural language, enable the following:
1. Creating/ modifying a db’s structure
2. Changing security settings for system
3. Permitting users for working on dbs and tables
4. Querying db
5. Inserting/Modifying/deleting the db contents
Some MYSQL elements are:
1. Literals:
• Literal values such as strings/numbers/ NULLS/ Date and time etc.
• Numeric Literal are NOT enclosed with quotation marks and also DO NOT
have comma in between them (Like 1,000 should be typed as 1000).
• A numeric literal can be integer literal i.e. without any decimal or real literal
i.e. in decimal form. Real literal has maximum of 53 digits of precision.
• String Literal is also called as character literal.
Some MYSQL elements are:
2. Datatypes :
• Means to identify the type of data and associated operations for handling it.
• You can do operations of data values depending on what datatype it is. Like addition /
subtraction etc can be done one numeric datatypes and concatenation on string datatypes.
• Following are different datatypes, mysql offers:
i) Numeric datatypes: ( INT, FLOAT(M,D), DOUBLE(M,D) , DECIMAL(M,D) )
INT: default is 11 digits. Can be signed or unsigned i.e. can have + or – sign.
FLOAT(M,D): here M is no. of digits and D is no. of decimals. EG: FLOAT(10,2) where 2 is the
number of decimals in the total number of digits(including decimal). Precision can be up to 24.
DOUBLE(M,D): same as FLOAT but if (M,D) not specified default it takes 16,4 where 4 is the no.
of decimals, BUT again if NOT specified precision can go up to 53 digits.
DECIMAL(M,D): An unpacked floating-point that cannot be unsigned. In unpacked decimals,
each decimal corresponds to one byte. If M,D not specified it takes 10,0 as default.
Remember the data entered is 45.56 will not give an error but will round up the data to 46 & will
get inserted data into a table.
Some MYSQL elements are:
ii) Date and Time datatypes:
DATE: A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31.
EG: 21st Jan, 2021 is stored as ‘2021-1-21’.
DATETIME: A date and time combo in YYYY-MM-DD HH:MM:SS format,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. EG: 21st Jan, 2021
afternoon 1:30 is stored as ‘2021-1-21 13:30:00’.
TIMESTAMP: is stored in format as (YYYYMMDDHHMMSS)
TIME: stores time HH:MM:SS format.
Remember all date and time data while entering to be entered in single or double
quotes.
Some MYSQL elements are:
iii) String/Text datatypes: Remember string/text data while entering to be
entered in single or double quotes.
CHAR(M): VARCHAR(M):
1. A fixed-length string datatype between 1 and 255 1. A variable-length string datatype.
char length. 2. The number of characters in the data element becomes
2. It occupies fixed number of bytes for every data its field length.
element they store.
3. EG: char(n) , if a value is shorter than length n, then 3. EG: varchar(n) , if a value is shorter than length n, NO
blank or white spaces are added, but the size of value blank or white spaces are added.
remains n bytes.
4. EG: char(5) , if a value is ‘RAM’ then is occupies 4. EG: varchar(5) , if a value is ‘RAM’ then is occupies 3
‘RAM__’ so 2 blanks are added to complete 5 bytes. bytes and if a value is ‘SITA’ then is occupies 4 bytes
5. if length not specified than default is 1. 5. if length not specified than gives an ERROR. Must define
6. EG: create table t1( the length
name char(5), --will take 5 bytes 6. EG: create table t1(
surname char); --will take 1 byte by name varchar(5), --will take 5 bytes
default surname varchar); --will give an ERROR length
not specified
Some MYSQL elements are:
iii) String/Text datatypes: Remember string/text data while entering to be
entered in single or double quotes.
BLOB or TEXT:
- a field with maximum of 65535 characters.
-BLOB (Binary Large OBjects) and TEXT both datatypes used to store large data
like images or big text files.
-Difference between 2 is that sorts and comparison on stored data are case
sensitive on BLOB and are not in TEXT type.
-No need to specify the length with BLOB and TEXT.
NULL Values (means empty or nothing)
• If a column in row has no value means it has null value.
• Null data can appeared in any datatype.
• Null values cannot be inserted where, PK and NOT NULL constraints
are declared on columns.
• Any arithmetic expression or comparison on NULL results to NULL.
• Remember zero (0) and NULL is different.
NULL + 10 results to NULL
BUT 0+10 results to 10
Comments
Comment is a text that is not executed; it is only for documentation purpose.
Different types of comments are:

• Multi-line comment: /* this is


multi – line comment */

• In between the line comment: -- (followed by space)


• Single line comment: # is the single line comment

[NOTE: SQL is NOT case-sensitive]


Creating Databases
• Syntax: CREATE DATABASE [IF NOT EXISTS] <database_name>;

EG1: CREATE DATABASE db1;

EG2: CREATE DATABASE IF NOT EXISTS db1;

Here db1 is the name of database. [IF NOT EXISTS] is optional.


Opening Databases
• Syntax: USE <database_name>;
EG: USE db1;

To see the list of existing databases:


EG: SHOW DATABASES;
OR
EG: SHOW DATABASES LIKE <database_name>;
EG: SHOW DATABASES LIKE ‘test’;
Anything in string
is case sensitive

All databases are stored in


small case
Removing the database
• Syntax: DROP DATABASE <db_name>;
EG: DROP DATABASE db1;

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 list of a table


• Syntax: SHOW TABLES;

• To view the columns of a table


• Syntax: SHOW COLUMNS FROM <table_name>;
EG: SHOW COLUMNS FROM 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>);

EG: CREATE TABLE emp(


eno int(2) PRIMARY KEY,
ename char(20) NOT NULL,
sal double(7,5),
address varchar(20),
DOJ date);
Different Constraints
• Unique constraint: ensures that no two rows have same value.
EG:

UNIQUE
constraint
declared
No two values
can be same so
gives an error
saying
duplicate value

Allows null entry

can more than


NOTE : there
two NULL values
Different Constraints
• NOT NULL constraint: Restricts for the NULL value
EG:

NO Null value
will be
accepted
Trying to insert
null value

• In the above eg trying to insert null value.


• As the column declared with NOT NULL constraint, so cannot insert
null value.
Different Constraints
• Primary Key constraint: a column declared as the primary key will have
unique values and cannot allow NULL values.
EG:

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:

CHECK constraint declared by putting validations on all columns


• 1st check on roll>0, restricting the entry for less than 0.
• 2nd check on grade to A1 or B1 so restricting the entry ‘C1’ grade.
• 3rd check on marks between 50.00 and 99.00 restricting the entry
for value 5.00
More on check constraints

• 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

NOTE: Foreign Key can be assign only if the PK is defined


Creating PK and FK

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

• Dept table has 2 departments 10 and 20.


• Look at 4th insert statement gives error as no such dept exists.
Applying Referential Actions: i.e. (UPDATE OR DELETE on Parent table)

Remember: Referential Action are always declared on child table while


declaring FK
1

Value got updated in


2 child table also i.e. 3
ON UPDATE CASCADE
• Deleting value from PK table
• Value got deleted from child
table also i.e.
• ON DELETE CASCADE
• Applying referential integrity on i.e . ON DELETE SET NULL & ON UPDATE
SET NULL.
• Remember it is not necessary to apply both constraints at a time.
Anyone can also be applied.
Inserting values into parent table and child table
• Updating the dno in parent table
and look at child table the data
in dno column is set null
automatically i.e.
ON UPDATE SET NULL
• Deleting the dno in parent table
and look at child table the data
in dno column is set null
automatically i.e.
ON DELETE SET NULL

Also see the dept table record got


deleted.
• Refer to PAGE 297 for table constraint egs.
• Remember table constraint is also called as out-of-line constraint.
Assigning Names to constraints:
• By default MSQL assigns the unique name to each constraints.
• To view the default name of the constraint issue the following
command:
SHOW CREATE TABLE <table_name>;

• User can also give his own constraint name :


• EG:
• Look at the constraint name defined
• Similarly RESTRICT and NO ACTION will work.
• EG2
• EG3
• EG4 on page 298

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>]);

• EG1: CREATE TABLE new_table as


( SELECT eno, sal from emp );

• EG2: CREATE TABLE new_table as


( SELECT eno, sal, job from emp
WHERE job = ‘Manager’);
• HW
• Create EMPL table on pg 301 and insert the values into it.
Inserting data in tables: INSERT is DML command
I. Syntax: INSERT INTO <table_name> VALUES(<int_val>, ‘<str_val>’ ….);
EG: INSERT INTO stud values(1001, ‘BOND’);
II. Syntax: INSERT INTO <table_name> (<col1,col2>)
VALUES (<int_val>, ‘<str_val>’ ….);
EG: INSERT INTO stud ( roll, name) values(1001, ‘BOND’);
[Note: if stud table has other columns than those cols will be inserted by null
values BUT in-case if the col is declared with NOT NULL then gives an error

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:

NOTE: NULL/null both are same.


here, roll and sec both has null value
Inserting data in tables: INSERT is DML command
III. Inserting date value: default format is ‘YYYY-MM-DD’
Inserting data in tables: INSERT is DML command
IV. Inserting data from another
table
• Note when inserting data from
one table to another both tables
must already exists.
• Structure of table must match if
SELECT * FROM …. When using
query.
• EG7 Page 302
• EG8 Page 303
SELECT command….
• Asking the RDBMS to show desired data in particular format is executed by
SELECT statement.
• Means SELECT command of SQL helps to make queries on the database.
• A query is a command that is issued on a specific database table(s).
• There are many combinations of SELECT statement that can be executed on
table(s).
• It is used to retrieve a subset of rows and columns from one or more tables.
• Syntax:
SELECT <col1_name>, <col2_name>,….
FROM <table_name>
WHERE <condition>;
REVISION

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;

7. WAQ to display dept no, employee name from emp table.


Select dno, ename from emp;

8. WAQ to display all details of emp table.


Select * from emp;
Eliminating redundant data by using DISTINCT keyword.
• By default the column show all the data and even the repeating data.
• EG:

By using round
brackets
Performing calculations on MYSQL

• Dual is a dummy table with one column and


one row having int datatype.
• It can be used for performing calculations.
Scalar expressions with selected cols.

• 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

Also can be written


Given temporary in double/single
name to col as pi quotes

NOTE : if column alias are more than one


word and a space(s) in them must have single
or double quotes
More egs of column alias:
9. WAQ to display different jobs from emp table.
Select distinct jobs from emp;

10. WAQ to display different departments from emp table.


Select distinct dno from emp;

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’;

12. WAQ working in dept no 10.


Select * from emp where dno=10;

13. WAQ to display employees who do not work in 10 dept.


Select * from emp where dno<>10; OR where dno!=10;

14. WAQ to display employees who join after 1991-01-01


Searching NULL value
• As null values cannot be searched using relational operators like =,<> or !=
• IS / IS NOT used to find the null values in the col of a table.
EG WAQ to displays employees who are not getting comm from emp table
Select * from emp where comm is null;

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;

24. WAQ to display president employees or join before year 1990.


Select * from emp where job=‘president’ or hiredate<‘1990-01-01’;
25. WAQ to display the employees other than clerk

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’);

32. WAQ to display employees other than destination clerk, salesman or


analyst from emp table
Select * form emp where job NOT IN (‘clerk’, ‘salesman’, ‘analyst’);
• EG 16 page 314
• EGS on 314

33. WAQ to display details of employees working in dept 10,20 or 30


from emp table. (use condition based on list)

Select * from emp where dno IN(10,20,30);


Select * from emp where dno=10 or dno =20 or dno=30;
Condition based on pattern matches
• SQL offers string-matching operator LIKE / NOT LIKE for comparison on
character strings using patterns. There are 2 wild card characters for
pattern matching :
I) % (percent) used for any substring match
II) _ (underscore) used for any character or number of chars match.

32. WAQ to display emp names starting with letter ‘a’


Select ename from emp where ename LIKE ‘a%’;

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];

41. WAQ to display the employees in ascending order by their salaries.


Select * from emp ORDER BY sal;
Select * from emp ORDER BY sal asc;

42. WAQ to display the employees in descending order by their salaries.


Select * from emp ORDER BY sal DESC;
43. WAQ to display the salesman employees in the descending order of their names.
Select * from emp where job=‘salesman’ order by ename 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>;

As INSERT command we have already discussed lets learn UPDATE


command
Syntax : UPDATE <table_name> SET <col_name> = <new_val>
[WHERE <condition>];
47. WAQ to increase the salaries of all employees by 5% from emp table.
UPDATE emp SET sal=sal+(sal*0.05);

48. WAQ to increase the salary of presidents by 5% from emp table.


UPDATE emp SET sal=sal+(sal*0.05)
WHERE job = ‘president’;

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’;

52. WAQ increase the eno by 1 whose comm is null.


Update emp set eno=eno+1 where comm is null;

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’;

58. WAQ to delete all records from emp.


DELETE FROM emp;

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>

As CREATE TABLE command we have already discussed lets learn ALTER


command
• ALTER command is a DDL command. It used to change the structure/definition of
existing the table. Using this command we can add a column, constraints or
modify datatype and size or change column title etc.
• Syntax for adding new column(s) with constraints if any.
ALTER TABLE <table_name>
ADD (<new_col1> <datatype(size)> [constraint] ,
<new_col2> <datatype(size)> [constraint]);
OR
ALTER TABLE <table_name>
ADD <new_col1> <datatype(size)> [constraint] ,
ADD <new_col2> <datatype(size)> [constraint];

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)

62. WAQ to add new column gender to the EMPL table.


ALTER TABLE empl ADD gender char(1);
(NOTE: if added a column with char datatype without any default value then
NULL will be added to the column gender i.e. that many number of values)
63. WAQ to add new columns: Policy_no int datatype with size 4 default values as 0.
Another column loan_type char(1) check that it should be one of these chars i.e.
‘H’,’C’,’P’ to EMPL table.
ALTER TABLE empl
ADD (Policy_no int(4) DEFAULT 0,
loan_type char(1) check( loan_type IN(‘H’,’C’,’P’)));

(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), ….. …..);

Create table Orders(Or_no int,


Item_No int, …. ….);

ALTER TABLE orders


ADD FOREIGN KEY(Item_No) REFERENCES items(IT_No);

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

ALTER TABLE <table_name>


MODIFY (<col_name> <new_datatype(new_size)> [FIRST| AFTER <col_name]);
73. WAQ to make eno col
as first column

ALTER TABLE <table_name>


MODIFY (<col_name> <new_datatype(new_size)> [FIRST| AFTER <col_name]);
74. WAQ to modify and add default value 0 to ph col from student table.

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);

75. WAQ to change col’s name sname


to stud_name of student table.
76. WAQ to change col name
f_name to father_name and
increase the datatype size to
char(20).
77. WAQ to change
father_name column’s datatype
size from char(20)to char(10).

78. WAQ to change father_name column’s size of to datatype size to char(2).


The below query gives error as data in col has more than the length specified.
• Syntax for alter i.e. adding default values.
1. is used to change to col’s default value.
ALTER TABLE <table_name> ALTER <col_name> SET DEFAULT <default_val>;
76. WAQ change the default value of ph column from 0 to 777 of student table.
• Syntax for RENAME i.e. changing the name of table.
ALTER TABLE <table_name> RENAME TO <new_table_name>;
77. WAQ change the student table’s name to stud_info.

(NOTE: student table does not exists now its stud_info.)


• Syntax for DROP i.e. removing table compnents.
ALTER TABLE <table_name> DROP
PRIMARY KEY [CASADE /SET NULL] | Deletes/remove the PK
[COLUMN] <col_name> | Deletes/remove the specified col
FORIEGN KEY <for_key_name> | Deletes/removes the FK
Deletes/removes the DEFAULT constraint
DEFAULT;
78. WAQ delete the column dob from stud_info table;
79. WAQ delete the column gender and sub from stud_info table;

Deleting 2 columns at a time


80. WAQ delete foreign key from orders table;
Syntax: ALTER TABLE <table_name> DROP FOREIGN KEY <for_key_name>;

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>;

Here col stud_name


has unique
constraint define

Now col stud_name


has NO unique
constraint
83. WAQ to remove not null
constraint from column ph
of student table

Here col ph cannot have


null values i.e. NOT NULL
constraint defined

Now col ph can have


null values i.e. NOT
NULL constraint got
deleted
• Syntax for ALTER i.e. removing table components.
ALTER TABLE <table_name> ALTER <col_name> DROP DEFAULT;
84. WAQ delete/remove default constraint
of column surname from stud_info table;

Default constraint ‘abc’


on col surname is
removed
DROP TABLE command
• DROP TABLE is a DDL command.
• DROP TABLE is used to delete/remove the table from the database.
• Once this command is issued table is no longer recognized & no commands
can be given on similar object.
• Syntax: DROP TABLE [IF EXISTS] <table_name>;
• IF EXISTS clause checks first whether the given table exists in the db or not.

85. WAQ to delete the stud_info table.


DROP TABLE stud_info;
OR
DROP TABLE IF EXISTS stud_info;
• DIFFERENCE BETWEEN ALTER TABLE AND UPDATE COMMAND
• DIFFERENCE BETWEEN DROP TABLE AND DELETE COMMAND

You might also like