Uploaded by Aaditya Sabharwal

MYSQL

advertisement
*SQL(Structured Query Language):
SQL is a simple query language used to create,manipulate and update data
bases.
*Types of Commands:
i)DDL(Data Definition Language)
ii)DML(Data Manipulation Language)
iii)TCL(Transaction Control Language)
*Commands:
i)Create Table Command(DDL)
ii)Insert Command(DML)
iii)select Command(DML)
iv)Update Command(DML)
v)Delete Command(DML)
vi)Drop Table Command(DDL)
vii)Alter Table Command(DDL)
viii)Commit Command(TCL)
*Data Types of MYSQL:
i)int or integer
ii)float or decimal
iii)char or varchar:
This data is used to store a string/character
type value in it.
Ex:
Name char(50),
Srishti #50 bytes
Ex:
Name varchar(50),
Srishti #7 bytes
vi)date:
This data type is used to store a date
in YYYY-MM-DD format.
*MYSQL Commands:
i)To display pre-existing databases:
show databases;
ii)To create a new Database:
create database NCSCHOOL;
iii)To access the Database:
use ncschool;
iv)To display the tables in a Database:
show tables;
*Create Table Command:
The create table command is used to create
a table in the database.
Syntax:
create table table_name
(
colname1 dtype(size) constraint,
colname2 dtype(size) constraint,
.
.
.
colnameN dtype(size) constraint
);
*Constraints:
The constraints are used to apply
conditions on column of a table.
*Types of Constraints:
i)Not Null:
This constraint enforces a column
not to have empty value in it.
ii)Unique:
This constraint enforces a column
not to have duplicate values in it.
iii)Primary Key:
This constraint is similar to unique
constraint as it also donot allow
duplicate value for a column. The
difference between unique and Primary
key constraint is:
Primary key constraint can be
applied to one column only whereas
unique constraint can be applied
to multiple columns.
Column with primary key constraint
can not have empty value in it
whereas column with unique constraint
can have empty value in it.
iv)Check:
This constraint is used to set a limit/range for a
column.
v)Default:
This constraint is used to set a default value for a column.
Q.WAC to create a table "Employee" with following Details:
Field_name DataType COnstraint
Eno int Primary Key
Ename varchar(50) Not Null
Desig varchar(50)
Gender char(1)
Age int
Sal float default=10000.00
DOB date
City varchar(50)
create table Employee
(
Eno int Primary Key,
Ename varchar(50) Not Null,
Desig varchar(50),
Gender char(1),
Age int,
Sal float default=10000.00,
DOB date,
City varchar(50)
);
Note:
to show structure of a table:
desc table_name;
Ex:
desc EMP;
*Insert Command:
The insert command is used to add a row in a relation.
Syntax:
insert into table_name
values(val1,val2,val3,..........,valN);
Ex:
insert into Student
l values(1,"Prince",18,.......,"2010-04-22");
*Select Command:
The select command is used to display the data on the output screen.
Syntax:
select col1,col2,.....,colN
from table_name;
or
select * (*)------->for full table
from table_name;
*Eliminating Redundant data:
The "DISTINCT"keyword is used to eliminate redundant data from select query.
Ex:
select DISTINCT(col_name)
from table_name;
#Q.WAC for following:
i)to display unique city from the table student?
select DISTINCT(City)
from Student;
ii)to display distinct stream from table Student?
select DISTINCT(Stream)
from Student;
*where clause:
The where clause is used to apply conditions on select query.
Syntax:
select col1,col2,....,colN
from table_name
where Condition;
*Types of Condition of where clause:
i)Condition based on Relational Operators:
=,>,<,>=,<=,!=
#Q.WAC for following:
i)to display all the details of the Students who are from
"Chennai"?
Ans:
select *
from Student
where City="Chennai";
ii)to display all the details of the male Students?
Ans:
select *
from Student
where Gender="M";
iii)to display Rno,Name and Marks of the Students who are
born after "2001-10-10"?
Ans:
select Rno,Name,Mark
from Student
where DOB>"2001-10-10";
ii)Conditions based on Logical Operators:
or,and,not
Q.WAC for following:
i)to display all the details of the employees who are either
from "Delhi" or "Mumbai"?
Ans:
select *
from EMP
where City="Delhi" or City="Mumbai";
ii)to display all the details of the employees who are from
"Chennai" and earning more than 50000?
Ans:
select *
from EMP
where City="Chennai" and Sal>50000;
iii)to display Eno,Ename and Sal of all the employees having
Desig as either "Manager" or "Clerk"?
Ans:
select Eno,Ename,Sal
from EMP
where Desig="Manager" or Desig="Clerk";
iv)to display all the details of the whose Age is
more than 25 and belongs to "Delhi"?
Ans:
select *
from EMP
where Age>25 and City="Delhi";
v)to display all the details of the emmployees who are not from
"Delhi"?
Ans:
select *
from EMP
where City!="Delhi";
or
select *
from EMP
where not City="Delhi";
*Condition based on ranges:
The "BETWEEN" keyword is used to select data within a
specific range. The lower and upper limit of range both
are included.
Q.WAC for following:
i)to display all the details of the employees having Sal in
range 30000 to 50000?
Ans:
select *
from EMP
where Sal between 30000 and 50000;
ii)to display all the details of the employee having Age in
range 25 to 29?
Ans:
select *
from EMP
where Age between 25 and 29;
iii)to display all the details of the employees having Sal
not in range 30000 to 50000?
Ans:
select *
from EMP
where not Sal between 30000 and 50000;
iv)to display all the details of the employees having DOB between
"1994-10-10" to "1996-01-20"?
Ans:
select *
from EMP
where DOB between "1994-10-10" and "1996-01-20";
*Conditions based on List:
The "IN" keyword is used to select a list of data from select
query.
#Q.WAC for following:
i)to display all the details of the employees who are either
from Delhi or Mumbai or Chennai?
Ans:
select *
from EMP
t where City IN("Delhi","Mumbai","Chennai");
ii)to display all the details of the employees having Desig
either Manager or Clerk or Analyst?
Ans:
select *
from EMP
where Desig IN("Manager","Clerk","Analyst");t
iii)to display all the details of the employees who Age is
either 25 or 27 or 29?
Ans:
select *
from EMP
where Age In(25,27,29);
iv)to display all the details of the employees who City Other
than Delhi or Mumbai or Chennai?
Ans:
select *
from EMP
where City Not In("Delhi","Mumbai","Chennai");
*Condition based on Pattern Matches:
The "LIKE" keyword is used to apply conditions on string matching
characters using patterns.
There are 2 wildcard character:
i)(_): This denotes a single character
ii)(%): This denotes a sub string.
Q.WAC for following:
i)to display all the details of the employee whose name starts with letter
"S"?
Ans:
select *
from EMP
where Ename like "S%";
ii)to display all the details of the employee whose name starts with letter
"S" and name contains 5 letters in it?
Ans:
select *
from EMP
where Ename like "S_ _ _ _";
iii)to display all the details of the employees whose name ends with letter "i"?
Ans:
select *
from EMP
where Ename like "%i";
iv)to display all the details of the employees whose name contains exactly 5 letters in it?
Ans:
select *
from EMP
where Ename like "_ _ _ _ _";
v)to display all the details of the employees whose name starts with K and ends with l?
Ans:
select *
from EMP
where Ename like "K%l";
vi)to display all the details of the employees whose name contains atleast 4 letters?
Ans:
select *
from EMP
where Ename like "_ _ _ _%";
vii)to display all the details of the employees whose name third last letter is "r"?
Ans:
select *
from EMP
where Ename like "%r_ _";
viii)to display all the details of the employees whose name starts with A and ends with i and
contains 5 letters in it?
Ans:
select *
from EMP
where Ename like "A_ _ _i";
ix)to display all the details of the employees whose name whose DOB is on data 25?
Ans:
select *
from EMP
where DOB like "25%";
*order by clause:
The order by clause is used to sort the selected data either in Ascending or Descending order.
Syntax:
select col1,col2,....,colN
from table_name
where Condition
order by colname ASC/DESC;
#Q.WAC for following:
i)to display all the details of the employees in descending order of thier Sal?
Ans:
select *
from EMP
order by Sal DESC;
ii)to display all the details of the employees who are either from "Delhi" or "Mumbai"
in Ascending order of thier name?
Ans:
select *
from EMP
where City="Delhi" or City="Mumbai"
order by Ename ASC:
iii)to display all the details of the female employee in descending order of their DOB?
Ans:
select *
from EMP
where Sex="F"
order by DOB DESC;
*MYSQL FUNCTIONS:
i)STRING FUNCTION
ii)NUMERIC FUNCTION
iii)DATE AND TIME FUNCTION
iv)AGGREGAT/E FUNCTION
*STRING FUNCTIONS:
i)LENGTH():
This function returns the length of a string passed to it.
Syntax:
LENGTH("STRING")
Ex:
select LENGTH("Prince Singh"); #12
ii)CONCAT():
This method is used to concatenate two or more strings.
Syntax:
concat(str1,str2,str3....)
Ex:
select Concat("Prince","@","XII","A");
output:
Prince@XIIA
iii)LCASE()/LOWER():
This method converts a string passed to it in lowercase form.
Syntax:
LCASE("STR")
Ex:
select Lcase("PrInCe");
Output:
prince
iv)UCASE()/UPPER():
This method converts a string passed to it in lowercase form.
Syntax:
UCASE("STR")
Ex:
select Ucase("PrInCe");
Output:
PRINCE
v)SUBSTR():
This method is used to return a sub-string from a string.
Syntax:
select SUBSTR(string,start_value,no_of_chars)
Ex:
select SUBSTR("CORPORATE",3,4);
Output:
RPOR
vi)LEFT():
This method is used to return n characters from leftmost side of the
string.
Syntax:
Left(string,no_of_chars)
Ex:
select Left("Prince",3);
Output:
Pri
vii)RIGHT():
This method is used to return n characters from rightmost side of the
string.
Syntax:
Right(string,no_of_chars)
Ex:
select Right("Prince",3);
Output:
nce
viii)MID():
This method is same as SUBSTR().
ix)REPEAT():
This method is used to read a string as many time as the user wants.
Syntax:
repeat(string,num)
Ex:
select repeat("Prince",3);
Output:
PrincePrincePrince
x)instr():
This method returns the position of the first occurence of a sub string
in a string.
Syntax:
instr(string,substring)
Ex:
select INSTR("CORPORATE","OR"); #2
select INSTR("CORPORATE","OR",4,9); #5
xi)Replace():
This method is used to replace a value in a string with another value.
Syntax:
replace(string,s)
Ex:
select replace("MALAYALAM",'A','X');
Output:
MXLXYXLXM
*Numeric Functions:
i)sqrt():
This method returns the square root of a number.
Syntax:
sqrt(num)
Ex:
select sqrt(9);
Output:
3.0
ii)POW():
This method returns a number raised to the power exponent.
Syntax:
pow(base,exp)
Ex:
select pow(5,2);
Output:
25
iii)MOD():
This method returns the remainder by dividing first number from second.
Syntax:
mod(num1,num2)
Ex:
select mod(10,3); #1
iv)truncate():
This method is used to truncate a number upto n decimal points.
Syntax:
truncate(num,int)
Ex:
select truncate(174.638,2); #174.63
select truncate(174.638,1); #174.6
select truncate(174.638,3); #174.638
select truncate(174.638,4); #174.638
select truncate(174.638,0); #174
select truncate(174.638,-1); #170
select truncate(174.638,-2); #100
select truncate(174.638,-3); #0
v)round():
This method is used to round off a number upto n decimal points.
Syntax:
round(num,int)
Ex:
select round(174.638,2); #174.64
select round(174.638,1); #174.6
select round(174.638,3); #174.638
select round(174.638,4); #174.638
select round(174.638,0); #175
select round(174.638,-1); #170
select round(174.638,-2); #200
select round(174.638,-3); #0
*Date And Time Functions in MySQL:
i)CUR_DATE()/CURRENT_DATE():
This method returns the current date of the System.
Ex:
select CURDATE();
Output:
2023-09-09
ii)NOW():
This method returns the current date and time of the system.
Ex:
select NOW();
Output:
2023-09-09 15:34:25
iii)CURTIME():
This method returns the current time of the system.
Ex:
select CURTIME();
Output:
15:34:25
iv)DATE():
This method is used to return the date from date and time format.
Ex:
select DATE("1996-10-12 09:45:10");
Output:
1996-10-12
v)DAY():
This method returns the day portion from the date value passed to it.
Ex:
select DAY("2018-07-16");
Output:
16
vi)DAYNAME():
This method returns a weekday name for a date.
Ex:
select DAYNAME("2023-09-09");
Output:
Saturday
vii)DAYOFMONTH():
This method returns the day portion of a date value.
Ex:
select DAYOFMONTH("2023-09-16");
Output:
16
viii)DAYOFYEAR():
This method returns the day of the year i.e 1-365 from a date passed to
it.
Ex:
select DAYOFYEAR("2023-09-09");
Output:
252
ix)MONTHNAME():
This method returns the name of the month from a passed date.
Ex:
select MONTHNAME("2023-09-09");
Output:
September
x)MONTH():
This method returns the month portion of the date passed to it.
Ex:
select MONTH("2023-09-09");
Output:
9
xi)YEAR():
This method returns the year portion of the date passed to it.
Ex:
select YEAR("2023-09-09");
Output:
2023
IV)Aggregate Functions:
i)Sum():
This method return the sum of all the value of a column passed to it.
ii)avg():
This method returns the average of all the values of a column passeed to it.
iii)min():
This method returns the minimum value from a column.
iv)max():
This method returns the maximum value from a column.
v)count():
This method counts the total number of non-null values from a column.
#Q.WAC for following:
i)to display the sum of salary of all the employees?
Ans:
select sum(sal)
from EMP;
ii)to display the average comm of all the employee
who are either from Delhi or Mumbai?
Ans:
select avg(comm)
from EMP
where City="Delhi" or City="Mumbai";
iii)to display the min and max Age of the empoyees
having desig as either Manager or Clerk or
Analyst?
Ans:
select min(age),max(age)
from EMP
where Desig In("Manager","Clerk","Analyst");
iv)to count the number of Ename of the employees whose
Ename starts with letter "A"?
Ans:
select count(Ename)
from EMP
where Ename like "A%";
v)to display the number of employees having Sal in
range 40000 to 50000?
Ans:
select count(*)
from EMP
where Sal between 40000 and 50000;
*Group By Clause:
The group by clause is used to create groups using select query.
Syntax:
select col1,col2,.....,colN
from table_name
where condition
order by col_name ASC/DESC
group by col_name;
EMP
Eno Ename Sal City
101 ABC 2000 Delhi
102 PQR 1000 Chennai
103 MNO 1500 Delhi
104 XYZ 2000 Delhi
105 HIG 1000 Mumbai
106 UVW 1500 Chennai
select sum(sal)
from EMP;
Output:
9000
select sum(sal)
from EMP
where City="Delhi";
Output:
5500
select sum(sal)
from EMP
where City="Chennai" or City="Mumbai";
Output:
3500
select City,sum(sal)
from EMP
group by City;
Output:
Delhi 5500
Chennai 2500
Mumbai 1000
Q.WAC for following:
i)to display sum of sal for each city from the table EMP?
Ans:
select City,sum(sal)
from EMP
group by City;
ii)to display maximum age of the employee for each Desig/Desig-wise
from the table EMP who are from "Delhi"?
Ans:
select Desig,max(Age)
from EMP
where City="Delhi"
group by Desig;
iii)to display min and max sal for each desig of the employee who
are either from "Delhi" or "Mumbai" or "Chennai"?
Ans:
select Desig,min(sal),max(sal)
from EMP
where City In("Delhi","Mumbai","Chennai")
group by Desig;
iv)to display number of employees for each city having sal in range
40000 to 50000 from the table EMP?
Ans:
select City,count(*)
from EMP
where Sal between 40000 and 50000
group by City;
*Having Clause:
The having clause is used to apply conditions on grouped data.
Syntax:
select col1,col2,....,colN
from table_name
where Condition
order by col_name ASC/DESC
group by col_name
having condition;
#Q.WAC for following:
i)to display sum of sal for each city from the table employee
whose sal sum is more than 4000?
Ans:
select City,sum(sal)
from EMP
group by City
having sum(sal)>4000;
ii)to display number of employee for each desig of the female employee
from the table EMP whose count is more than 2?
Ans:
select Desig,count(*)
from EMP
where Gender="F"
group by Desig
having count(*)>2;
*Update Command:
The update command is used to change/modify the data inside
a relation.
Syntax:
update table_name
SET <to be changed>
where Condition;
#Q.WAC for following:
i)to increase the sal of all the employees by 1000?
Ans:
update EMP
SET Sal=Sal+1000;
ii)to decrease the Sal of all the employees by 5000 who are
from Delhi?
Ans:
update EMP
set Sal=Sal+5000
where City="Delhi";
iii)to increase the Sal of all the employees by 10% who are
having Desig as Clerk or Manager?
Ans:
update EMP
set Sal=Sal+(Sal*0.10)
where Desig="Clerk" or Desig="Manager";
iv)to change the Desig as Analyst and increase sal by 10000 of
the employees who Eno is 105?
Ans:
update EMP
set Desig="Analyst",Sal=Sal+10000
where Eno=105;
*Delete Command:
The delete command is used to delete rows from a relation.
Syntax:
delete from table_name
where Condition;
#Q.WAC for following:
i)to delete all the records from table EMP?
Ans:
delete from EMP;
ii)to delete all the records of the employees who
city is "Delhi";
Ans:
delete from EMP
where City="Delhi";
*Drop Table Command:
The drop table command is used to delete the table from
the database.
Syntax:
drop table table_name;
Ex:
drop table EMP;
*Alter Table Command:
The alter table command is used to modify the structure of a table.
There are 4 attributes of alter table command:
i)ADD
ii)MODIFY
iii)CHANGE
iv)DROP
i)ADD:
The ADD attribute of alter table command is used to add a new column
in a table.
Syntax:
alter table table_name
ADD(new_colname dtype(size) constraint);
Ex:
Alter table EMP
ADD(AdhaarNo int unique);
ii)MODIFY:
The modify attribute is used to change then data type and constraint
of a pre-existing column.
Syntax:
alter table table_name
MODIFY old_colname new_dtype(size) new_constraint;
Ex:
Alter table EMP
Modify Sal float check Sal>10000;
iii)CHANGE:
This attribute is used to change the name of a pre-existing column.
Syntax:
Alter table table_name
change old_colname,new_colname dtype(size) constraint;
Ex:
Alter table EMP
change Eno,EmpNo int Primary Key;
iv)DROP:
The drop attribute is used to delete a column from a table.
Syntax:
Alter table table_name
drop col_name;
Ex:
Alter table EMP
drop Comm;
*Commit:
The commit command is used to save the database;
Syntax:
commit;
Download