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

SQL Concepts

The document discusses various SQL concepts including creating tables, data types, inserting and selecting data, constraints, operators, and more. It provides examples of SQL statements to create tables with different data types, insert data, add constraints, select data using where, order by, and other clauses, and explains concepts like joins, aggregation, and regular expressions.

Uploaded by

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

SQL Concepts

The document discusses various SQL concepts including creating tables, data types, inserting and selecting data, constraints, operators, and more. It provides examples of SQL statements to create tables with different data types, insert data, add constraints, select data using where, order by, and other clauses, and explains concepts like joins, aggregation, and regular expressions.

Uploaded by

kamala thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

******************************************

SQL- CONCEPTS

******************************************
//concept 1 how to create table
******************************************
create table table_name{
column1 datatype,
column2 datatype,
column3 datatype,
......
}

//concept 2 String datatypes in mysql


CHAR(size)
VARCHAR(size)
BINARY(size)
VARBINARY(size)
TINYTEXT
TEXT(size)
MEDIUMTEST
LONGTEXT
TINYBLOB
BLOB(size)
MEDIUMBLOB
LONGBLOB
ENUM(var1,var2,var3,....)
SET(var1,var2,var3,....)

//concept 3 Numeric Datatype in mysql


BIT(size)
TINYBIT(size)
INT(size)
INTEGER(size)
SMALLINT(size)
MEDIUMINT(size)
BIGINT(size)
BOOL
BOOLEAN
FLOAT(P)
DOUBLE(size,d)
DECIMAL(size,d)
DEC(size,d)

//concept 4 date and time datatypes in mysql


date 1000-1-1 t0 9999-12-31
datetime(fsp) yyyy-mm-dd hh:mm:ss
timestamp(fsp)
time(fsp) hh:mm:ss
year it will take 4 digit like 2002,2021

//concept 5 create table personal


CREATE TABLE personal{
id int,
name varchar(50),
birth_date DATE,
phone varchar(12),
gender varchar(1)
};

//concept 6 create table product

CREATE TABLE product{


pid int,
pname varchar(50),
pcompany varchar(50),
price int
};

//concept 7 select * from personal ,select * from product

*************************************************************************
//concept 1 how we will insert data in table
*************************************************************************
INSERT INTO table_name(column1,column2,column3,...)
VALUES(value1,value2,value3.....);

//concept 2.1 insert data into personal table


insert into personal(id,name,birth_date,phone,gender)values(1,'alex','1998-02-12','111111111','m');

//concept 2.2 insert another date into personal table


insert into personal(id,name,birth_date,phone,gender)values(3,'xyz','1994-12-11','222222222','m');

*************************************************************************
//concept 1 insert multiple rows in the table.
*************************************************************************

INSERT INTO table_name(column1,column2,column3,column4,....)


VALUES
(value1,value2...),
(value1,value2...),
(value1,value2...),
(value1,value2...);

//concept 2 insert multiple rows in the personal table


INSERT INTO personal(id,name,birth_date,phone,gender)
VALUES
(2,'abcd','2000-02-12','111111111','F'),
(3,'efgh','2001-12-22','222222222','F'),
(4,'ijkl','2002-02-12','3333333333','F'),
(5,'mnop','2003-12-12','4444444444','F'),
(5,'qrst','2004-12-12','',''),//empty value hold null value
(5,'uvwxyz','2005-12-12','',''),//empty value hold null value
//duplicate also allow when you are not using constraint

*************************************************************************
constraint means restriction
*************************************************************************
//concept 1 constaints in database
1.NOTNULL
2.check(age>18)
3.unique
4.default 'xyz'
5.primary key
6.foreign key

//concept 2 how to implement constraint in table

CREATE TABLE table_name


(
id int NOT NULL UNIQUE,
name varchar(50)NOTNULL,
age int NOTNULL CHECK(age>18),
gender varchar(1)NOTNULL,
phone varchar(11) NOTNULL UNIQUE,
city varchar(50)NOTNULL default 'xyz'
);

//concept 3 implement constraint in table

CREATE TABLE student


(
id int NOT NULL UNIQUE,
name varchar(50)NOTNULL,
age int NOTNULL CHECK(age>17),
gender varchar(1)NOTNULL,
phone varchar(11) NOTNULL UNIQUE,
city varchar(50)NOTNULL default 'xyz'
);

//concet 4 insert data into table

insert into student(id,name,age,gender,phone,city)


VALUES
(1,'abcd',26,'M','111111111','jamshedpur')
(1,'efgh',27,'M','222222222','')//default city xyz

insert into student VALUES


(1,'abcd',22,'M','111111111', 'jamshedpur')
(1,'efgh',22,'M','222222222', '')//default city xyz

*************************************************************************
//concept 1 select some column with data from the required table

SELECT column1,column2,column3.....
FROM table_name;

//concept 2 select all column with data from the required table
SELECT *
FROM table_name;

//concept 3 use personal table and select column name,phone

seletc name,phone from personal;

//concet 4 to show all the data use * in after select

select * from personal;

//concept 5 we can also change the name of the column with the keyword as,
select name as Student,phone as Mobile_Number from personal;

//concept 6.1 we can use where clause to filter recode

select column1,column2,column3,column4,......
from table_name
where condition;

//concept 6.2 where comparison operator


1.=
2.<
3.>
4.<=
5.>=
6.!=
7.<>
8.BETWEEN-between a certain range
9.LIKE- search for a pattern
10.IN- to specify multiple possible value for a column

//concept 6.3 we can also use where clause with select

select name from personal where gender='f';


select * from personal where gender='F';

*************************************************************************
AND OR NOT Operator
*************************************************************************

//concept AND OR NOT Operator syntax


we use it betwen two or more column of the table

//concept for AND

select column1,column2,column3,....
from table_name
where condition1 AND condition2 AND Conditon3....

//concept for OR

select column1,column2,column3,....
from table_name
where condition1 OR condition2 OR Conditon3....

//concept for NOT

select column1,column2,column3,....
from table_name
where NOT condition1

*************************************************************************
IN operator
*************************************************************************
//concept 1 IN operator to specify multiple possible value for a column.
we use it where we need to check multiple value/record for a column
SELECT column1,column2,column3...
FROM table_name
where column_name IN (value1,value2,....)

//concept 2 IN-operator is sort hand of the OR-operator


the same query we can write with or operator but it is lengthy or comple we use in operator to make it sort.
SELECT column1,column2,column3...
FROM table_name
where condition1 or condition2..

//concept 3 NOT IN operator


SELECT column1,column2,column3...
FROM table_name
where column_name NOTIN (value1,value2,....)

*************************************************************************
BETWEEN, NOT BETWEEN operator
*************************************************************************
//concept between and not between operator

//syntax for between


SELECT Column1,Column2,Column3..
FROM table_name
where column_name BETWEEN value1 AND Value2;

//syntax for Not between


SELECT Column1,Column2,Column3..
FROM table_name
where column_name NOT BETWEEN value1 AND Value2;

*************************************************************************
LIKE operator and wildcard characters
*************************************************************************
//concept 1 like operator and wildcard characters

we use two wild cards charecters '%' (percentage) and '_' (under score)

%-represent zero or one or multiple characters.


_-represent single characters
concept..
1. LIKE "a%"-start with a
2. LIKE "%a"-end with a
3. LIKE "%am%"-Have am in any position
4. LIKE "a%m"-start with a and end with m
5. LIKE "_a%"- a in the second position
6. LIKE "__a%"- a in the third position
7. LIKE "_oy"- o in the second position and y in the third position

//syntax for LIKe operator

SELECT column1,column2,column3...
FROM table_name
WHERE column_name LIKE pattern

//syntax for not LIKe operator

SELECT column1,column2,column3...
FROM table_name
WHERE column_name LIKE pattern

//exapmle 1.1 with case insensitive

select * from student where name like "r%"; // it will display record from name column where value start with r or
R.

//exampl 1.2 with case sensitive

select * from student where BINARY name like "r%";//it will display record from name column where value start
with only r because of binary keyword.

//exampl 1.3 with case sensitive

select * from student where BINARY name like "R%";//it will display record from name column where value start
with only R because of binary keyword.

//exampl 1.4 with case sensitive

select * from student where name like "r%";//it will display record from name column where value start with either
r or R because i removed the binary keyword.

*************************************************************************
Regular Expression
*************************************************************************
//concept 1 REGEXP Regular Expression

how we will use regular Expression.


definition ->Sing Pattern Description

1. ^ ->'^rm' ->begining of string


2. $ ->'rm$' ->End of String
3. [...]->'[abc]' ->any charecters listd between square breaket
4. ^[] ->'^[rms]' ->begining with any charecters listed between square brekets.
5.[a-z]-> '[a-h]e' ->match with in the range
6. p1|p2|p3-> 'tom'|'dick'|'harry' ->matches any of the pattern p1,p2 or p3.
7. 'e[ih]'; -- here e followed by either i like "ei" or h like "eh"
8. 'e[a-d]'; --here e followed by any charecter between given range
9. 'wo[ru]ld';--here "world" and "would"
like ea,eb,ec,ed
10. regexp '[a-z][aeiou]t$';

example: GREAT & WHAT;


here end with t and before t should be a vowel

Symbol which is offence use in reguler expression


^,$,|,[],-
above five symbol offence used in regexp

//syntax for regexp.


SELECT colimn1,column2,column3.....
FROM table_name
WHERE column_name REGEXP pattern.

*************************************************************************
Order by and Distinct
*************************************************************************
//sort in accending order ASC

SELECT column1,column2,column3....
FROM table_name
ORDER BY column1,column2,...ASC; //default

//sort in decending order ASC


SELECT column1,column2,column3....
FROM table_name
ORDER BY column1,column2,...ASC;

//sort in accending order with where clause

SELECT column1,column2,column3...
FROM table_name
WHERE condition1,condition2
ORDER BY column_name1,column_name2,column_name3.....ASC;

//sort in desending order with where clause

SELECT column1,column2,column3...
FROM table_name
WHERE condition1,condition2
ORDER BY column_name1,column_name2,column_name3.....DESC;

//concept 3.1 DISTINCT keyword to select distinct value for a column

SELECT DISTINT column1,column2,column3...


FORM table_name;
//Example
SELECT DISTINCT city
FROM student
//concept 3.3 DISTINCT keyword to select distinct value for a column

SELECT DISTINT column1,column2,column3...


FORM table_name
ORDER BY column1,column2.....
//Example
SELECT DISTINCT city
FROM student
ORDER BY city ASC;

//concept 3.3 DISTINCT keyword to select distinct value for a column

SELECT DISTINT column1,column2,column3...


FORM table_name
where condition1,condition2,....
ORDER BY column1,column2.....
//Example
SELECT DISTINCT city
FROM student
ORDER BY city ASC;

*************************************************************************
IS NULL and IS NOT NULL
*************************************************************************
//IS NULL and IS NOT NULL

//concept 1 is NULL some i left some column value we can check it

SELECT column1,column2,column3...
FROM table_name
WHERE column IS NULL;

//example
SELECT *
FROM student
WHERE city IS NULL;

//concept 2 IS NOT NULL some i left some column value we can check it

SELECT column1,column2,column3...
FROM table_name
WHERE column IS NOT NULL;

//example
SELECT *
FROM student
WHERE city IS NOT NULL;

*************************************************************************
LIMIT and offset
*************************************************************************
//Limit and offset
as we know we select * from table name to show recode it will give you all the record.
if we need to show few recode of all recode then we can also do this with the help of LIMIT keyword.

//concept 1 with LIMIT syntax


SELECT column1,column2,column3....
FROM table_name
WHERE condition
LIMIT number;

//example
SELECT name
FROM student
LIMIT 3;

//Example
SELECT name
FROM student
WHERE age>17
LIMIT 3;

//Example
SELECT name
FROM student
WHERE age>17
ORDER BY name
LIMIT 3;

//concept 3 OFFSET with LIMIT keyword

SELECT column1,column2,column3....
FROM table_name
WHERE condition
LIMIT offset,number;

//example
SELECT name
FROM student
LIMIT 2,3;(it will start after row 2 and three recode will display)

//Example
SELECT name
FROM student
WHERE age>17
LIMIT 1,2;(it will start after row 1 and 2 recode will display)

//Example
SELECT name
FROM student
WHERE age>17
ORDER BY name
LIMIT 4,2;(it will start ater row 4 and 2 recode will display )

*************************************************************************
COUNT sum min max avg function
*************************************************************************
//count sum min max avg function to perform operation recode.it will return a single row

we will create a employee table to perform this operation.

//create employee table

create table employee


(
id int not null unique,
name varchar(50) not null,
age int not null,
gender varchar(1),
salary varchar(10)
);

//insert in employee table

insert into employee


(id,name,percentage,age,gender,salary)values
(7,'ABCD',89,22,"M",'100000'),
(8,'EFGH',90,24,"F",'25000'),
(9,'IJKL',21,88,"M",'15000'),
(10,'MNOP',26,75,"M",'80000'),

//concept 1 count(column_name) it will count number of rows


SELECT count(column_name)
FROM table_name

//example
SELECT count(name)
FROM employee;

//example
SELECT count(*)
FROM employee;

//example
SELECT count(DISTINCT city)
FROM employee;

//example we can also give some alias name to the column


SELECT count(DISTINCT city) as number_of_city
FROM employee;

//concept 2 max(column_name) it will return maximum value of this column.


SELECT MAX(column_name)
FROM table_name

//example
SELECT MAX(percentage)
FROM employee;//but i dont know which employee get maximum number we can know by providing column_nam
e after max_function.
//example
SELECT MAX(percentage),name//but it will not working
FROM employee;

//concept 3 min(column_name) it will return minimum value of this column.


SELECT MIN(column_name)
FROM table_name

//example
SELECT MIN(percentage)
FROM employee;//but i dont know which employee get minimum number we can know by providing column_name
after min_function.

//example
SELECT MIN(percentage),name//but it will not working
FROM employee;

//concept 4 sum(column_name) it will return sum of the value of this col.


SELECT sum(solumn_name)
FROM table_name

//example
SELECT sum(percentage) as total_marks
FROM employee;

//concept 5 avg(column_name) it will return avg of the value of this col.


SELECT AVG(column_name) as alias_name(if you want you can take)
FROM table_name

//example
SELECT AVG(percentage) as AVERAGE
FROM employee;

create table employee


(
id int not null unique,
name varchar(50) not null,
age int not null,
gender varchar(1),
salary varchar(10)
);

*************************************************************************
Update table record or date or value
*************************************************************************
//Update table record or date or value

//concept 1 update syntax

UPDATE table_name
SET column1=value1,column2=value2,column3=value3....
WHERE condition;

//use table employee


//example concept 1
UPDATE employee
SET city="Jamshedpur"
WHERE city='Rourkela';

//example concept 2
UPDATE employee
SET city="Ranchi"
WHERE city='Bokaro';

//example concept 3
UPDATE employee
SET city="Dhanbad", salary=15000
WHERE id=7 OR id=8;

//example concept 3
UPDATE employee
SET name="ANIL",gender="M"
WHERE id=2

//example concept 4 we can update multiple recode at once bu repeating query

UPDATE employee//1
SET city="Jamshedpur",salary=43000
WHERE id=7;
UPDATE employee//2
SET city="Patna",salary=80000
WHERE id=8;
UPDATE employee//3
SET city="Dhanbad",salary=30000
WHERE id=9;

//concept we can also use the IN_Operator

UPDATE employee//3
SET percentage=60 city='jamshedpur'
WHERE id IN(1,2,4,5,7);

*************************************************************************
COMMIT and ROLLBACK
*************************************************************************
//concept of commit and rollback
this keyword work with insert,update and delete commond

RollBack. we use this commond when we need to rollback data.


COMMIT. we use this commond when we need to save date/recode or changes.// permanent

1. i want to update a student recode rehan ,but unfortunatly i make changes at different place then i need to revert/ro
llback it
for this i will use ROLLBACK commond. it will rollback all the recode you change .
2. if you do not want to rollback all the recode then you have to use COMMIT commond.

//important concept
NOTE:- if you update the table and commit then it will not able to rollback. Rollback only possible if the record is n
ot commited.
once you commit can't able to rollback.

//example
select * from employee;

commit;//it means permanently save

UPDATE employee
SET name="Anil",age=26
WHERE id=3;

ROLLBACK;

//example
select * from employee;

//when i use rollback this common will not rollback because it is already commit

UPDATE employee
SET name="sohan",age=27
WHERE id=3;
commit;

//when i use rollback this common will rollback because it is after commit
UPDATE employee
SET name="Rohan",age=25
WHERE id=3;
ROLLBACK;

*************************************************************************
DELETE Record
*************************************************************************
//delete common we use to delete table Record/rows/values not table it self.

//concept 1 delete a Record from table syntax


DELETE FROM table_name
where condition;

//example
DELETE FROM employee
WHERE id=6; //if you not use where clouse it will delete all the .

//concept 2 if you do not use where clouse it will delete all the Record.
DELETE FROM employee; //all the Record will remove from the table.

*************************************************************************
PRIMARY AND FOREIGN KEY
*************************************************************************
//primary key
1. primary key always have an unique data
2. a primary key can not have null value
3. A table can contain only one PRIMARY key constraints

//concept 1.1 create table with PRIMARY key

//student table

CREATE TABLE student


(
id int NOT NULL AUTO_INCREAMENT
name varchar(50) NOT NULL
age int NOT NULL
city varchar(50) NOT NULL

PRIMARY KEY (id)


);

//city table
CREATE TABLE CITY(
cid int NOT NULL AUTO_INCREAMENT
cname varchar(50) NOT NULL
PRIMARY KEY (cid)
);

//concept 1.2 create table with primary key

//student table
CREATE TABLE student
(
id int PRIMARY KEY NOT NULL AUTO_INCREAMENT
name varchar(50) NOT NULL
age int NOT NULL
city varchar(50) NOT NULL
);

//insert into table


INSERT INTO student(id,name,age,city)
VALUES
(1,'Anil',28,2),
(2,'Rohan',18,1),
(3,'Sohan',23,4),
(4,'Sunil',28,1),
(5,'Amit',28,2),
(6,'Sumit',28,4);

//city table
CREATE TABLE CITY
(
cid int PRIMARY KEY NOT NULL AUTO_INCREAMENT
cname varchar(50) NOT NULL
);

INSERT INTO city(cid,cname)


VALUES
(1,'Jamshedpur'),
(2,'Delhi'),
(3,'Rourkela'),
(4,'Kharagpur'),

//concept Suppose if i alreadt have a table and i want to set PRIMARY key then how will i do that. for this i will ha
ve to alter table like that:

//syntax
ALTER TABLE student
ADD PRIMARY KEY (id);

//concept of forigne key


1. a foreign key is a key which is used to link two tables togethers
2. a foreign key in one table used to point a primary key in another table

//concept how I will create a FOREIGN KEY

//example 1.1
CREATE TABLE student
(
id int NOT NULL AUTO_INCREAMENT
name varchar(50) NOT NULL
age int NOT NULL
city varchar(50) NOT NULL
PRIMARY key (id)
FOREIGN KEY (city) REFERENCES CITY(cid)
);

CREATE TABLE Children(

id int NOT NULL AUTO_INCREMENT,


name varchar(50)NOT NULL,
age int NOT NULL,
city varchar(50) NOT NULL,
PRIMARY key (id),
FOREIGN KEY (city) REFERENCES City(cid)
);

//example 1.2
CREATE TABLE student
(
id int PRIMARY key NOT NULL AUTO_INCREAMENT
name varchar(50) NOT NULL
age int NOT NULL
city varchar(50) NOT NULL
FOREIGN KEY (city) REFERENCES CITY(cid)
);

//concept if we have an existing table if we want to set a FOREIGN KEY the how we will i do that.

ALTER TABLE student


ADD FOREIGN KEY (city) REFERNCES CITY (cid);
*************************************************************************
INNER JOIN
*************************************************************************
//Inner join we use innner join to join multiple tables
inner join also called join we can write join insted of inner join
1.inner join
2.left join
3.right join
4.cross join

//concept 1-inner join, if you have two table and you wants common data from both table then you have to use inner
join.

//syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

//example 1.1
SELECT * from children INNER JOIN city ON children.city=city.cid;

//example 1.2
SELECT name,age,cname as City_name from children INNER JOIN city on children.city=city.cid;

//Intresting concept we can also use alise for table (means sort name for table)
SELECT * FROM children ch INNER JOIN city ci
ON ch.city=ci.cid;

//concept use column name insted of * symbole


SELCET ch.name,ch.age,ci.cname
FROM children ch INNNER JOIN city ci
ON ch.city=ci.cid;

//concept where clause with INNER join, it is working

SELECT ch.name,ch.age,ci.cname
FROM children ch INNER JOIN city ci
ON ch.city=ci.cid
where ci.cname='jamshedpur';

//concept 1.1 use ORDER BY clause with INNER join

SELECT ch.name,ch.age,ci.cname
FROM children ch INNER JOIN city ci
ON ch.city=ci.cid
where ci.cname='Jamshedpur'
ORDER BY ch.name ASC;

//concept 1.2 use ORDER BY clause with Inner join we can also use IN operator

SELECT ch.name,ch.age,ci.cname
FROM children ch INNER JOIN city ci
ON ch.city=ci.cid
where ci.cname IN('Jamshedpur',"Rourkela")
ORDER BY ch.name ASC;

*************************************************************************
LEFT AND RIGHT JOIN
*************************************************************************
//Left and Right join
//concept 1 left join all Record from left table and common data from the right table.

//syntax
SELECT *
FROM table1
LEFT JOIN table2
ON table1.column_name(foreignkey)=table2.column_name(primarykey)

//example 1.1 with full table name


SELECT *
FROM children
LEFT JOIN city
ON children.city=city.cid;

//example 1.2 with full table name we can also use where clause
SELECT *
FROM children
LEFT JOIN city
ON children.city=city.cid;
WHERE children.age>20;

//example 1.2 with full table name we can also use ORDER Clause clause
SELECT *
FROM children
LEFT JOIN city
ON children.city=city.cid;
WHERE children.age>20;
ORDER BY name;

//example 1.2 with alias name of the table


SELECT *
FROM children ch
LEFT JOIN city ci
ON ch.city=ci.cid;

//concept for RIGHT JOIN

//concept 1 right join all recode from right table and common data from the left table.

//syntax
SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column_name(foreignkey)=table2.column_name(primarykey)

//example 1.1 with full table name


SELECT *
FROM children
RIGHT JOIN city
ON children.city=city.cid;

//example 1.2 with full table name we can also use where clause

SELECT *
FROM children
RIGHT JOIN city
ON children.city=city.cid;
WHERE children.age>20;

//example 1.2 with full table name we can also use ORDER Clause clause

SELECT *
FROM children
RIGHT JOIN city
ON children.city=city.cid;
WHERE children.age>20;
ORDER BY name;

//example 1.2 with alias name of the table


SELECT *
FROM children ch
RIGHT JOIN city ci
ON ch.city=ci.cid;

*************************************************************************
CROSS JOIN
*************************************************************************
//concept of cross join it will join each row of the first table with
//every single row of the second table.
basically cross join make all possible combination between two table.

we can also put common(,) insted of cross join.

//syntax
SELECT column1,column2,column3...
FROM table1,
CROSS JOIN table2;

//syntax
SELECT column1,column2,column3...
FROM table1, table2;//it is also working same way just use common in place of cross join

//example 1.1
SELECT *
FROM children
CROSS JOIN city;

//example 1.2
SELECT ch.name,ci.cname
FROM children ch
CROSS JOIN city ci;

*************************************************************************
Join Multiple Table by Using INNER JOIN
*************************************************************************
//join multiple table we can also join multiple table by using inner join keyword again again...

//synax
SELECT column1,column2,column3.....
FROM table1
INNER JOIN table2 //this table2 is joined with first table
ON table1.column=table2.column

INNER JOIN table3 //this table3 is joined with first table


ON table1.column=table3.column

INNER JOIN table4 //this table4 is joined with first table


ON table1.column=table4.column
....

in this way we can join multiple table

//create table to perform multiple join operation

//collage name table


CREATE TABLE College_name
(
id INT NOT NULL PRIMARY KEY,
name varchar(50) NOT NULL,
c_course INT NOT NULL,
c_city INT NOT NULL,

FOREIGN KEY (c_course) REFERENCES College_course(cr_id),


FOREIGN KEY (c_city) REFERENCES College_city(c_id)
);

// insert into college table

insert into College_name(id,name,c_course,c_city)


values
(1,'NIT Rourkela',1,1),
(2,'IIT KGP',2,2),
(3,'NIT Jamsedpur',3,1),
(4,'IIT Delhi',2,3),
(5,'Delhi University ',1,3);

//college course table

CREATE TABLE College_course


(
cr_id int NOT NULL PRIMARY KEY ,
course varchar(50)NOT NULL
)
//insert into course table

INSERT INTO College_course(cr_id,course)


values
(1,'B.tech'),
(2,'M.tech'),
(3,'Phd');

//Update table
Update college_course
SET course="B.Tech"
Where cr_id=1;

//colloge citty table


CREATE TABLE College_city
(
c_id NOT NULL PRIMARY KEY ,
city varchar(50) NOT NULL
);

//insert into city table


INSERT INTO College_city(c_id,city)
values
(1,"Jamshedppur"),
(2,"Kharagpur"),
(3,"Delhi");

//Example of the innner join of the Multiple Table

//inner join 1.1 of the two table College_name and College_city

//Select All column of the both table

SELECT * FROM College_name INNER JOIN College_city


ON College_name.c_city=College_city.c_id;

//select some column from both table


SELECT Cg.id,Cg.name,Cy.city
FROM College_name Cg INNER JOIN College_city Cy
ON Cg.c_city=Cy.c_id;

//inner join 1.2 of the two table College_name and College_course

//Select All column of the both table

SELECT * FROM College_name INNER JOIN College_course


ON College_name.c_course=College_course.cr_id;

//select some column from both table

SELECT C.id,C.name,T.city
FROM College_name C INNER JOIN College_city T
ON C.c_course=T.c_id;

// Inner join Multiple College_name,College_city,College_course

//example 1.1

SELECT * FROM College_name


INNER JOIN College_city
ON College_name.c_city=College_city.c_id
INNER JOIN College_course
ON College_name.c_course=College_course.cr_id;

//Example 1.2 with alias name of the table

SELECT * FROM College_name C


INNER JOIN College_city T
ON C.c_city=T.c_id
INNER JOIN College_course S
ON C.c_course=S.cr_id;

//Example 1.3 select some column from all table

SELECT C.id,C.name,T.city,S.course FROM College_name C


INNER JOIN College_city T
ON C.c_city=T.c_id
INNER JOIN College_course S
ON C.c_course=S.cr_id

//Example 1.3 select some column from all table and also use where clouse

SELECT C.id,C.name,T.city,S.course FROM College_name C


INNER JOIN College_city T
ON C.c_city=T.c_id
INNER JOIN College_course S
ON C.c_course=S.cr_id
WhERE T.city="Delhi";

*************************************************************************
GROUP BY and HAVING Clause
*************************************************************************
//Group by and Having clause

CONCEPT -> (GROUP BY):

--group by clause we use with select and agregate function.


--to group rows by common column values.
--group by is used to group rows based on common column values.
--and it is compulsory you have to use aggregate function with it.

CONCEPT -> (HAVING) it is similar to where clause but it is used to perform conditon on the Result which will co
me out from the group by clause.Having clause come after group by clause.
//Syntax 1.1 with group by clause

SELECT Column1,Column2,Column3......,Aggregate(column1,column2,..)
FROM Table_name
Where Condition
Group By Column_name1,Column2....

//Syntax 1.2 with group clause with inner join

SELECT column1,column2,column3....Aggregate(column1,column2,...)
FROM table1
INNER JOIN Table2
ON table1.column=table2.column
Where Condition
GROUP BY Column1,column2,...

//Syntax 1.3 Group By Clause

SELECT column1,Column2,Column3...Aggregate(column1,column2,..)
FROM table1
INNER JOIN table2
ON Table1.column=Table2.column
WHERE Condition
Group BY Column1,column2....
Order By column1,column2...ASC / DESC

//Select common with Group by


//EXample 1.1
SELECT c_city,Count(c_city)
FROM College_name
GROUP BY c_name;

//Example 1.2 number of student comes from each city


SELECT T.c_id,T.city,Count(C.c_city) as Totale_student
FROM College_name C
INNER JOIN College_city T
ON C.c_city=T.c_id
GROUP BY c_city;

//Example 1.2 number of student comes from each city Order BY Count
SELECT T.c_id,T.city,Count(C.c_city) as Totale_student
FROM College_name C
INNER JOIN College_city T
ON C.c_city=T.c_id
GROUP BY c_city
ORDER BY Count(C.c_city);

//Concept having 1.1 clause it is used on the result come from group by clasue

SELECT column1,column2,column3...Aggaregate(column1,column2...)
FROM table_name
Group BY column1,column2,...
HAVING Condition1,condition2,....
//Concept having 1.2 clause it is used on the result come from group by clasue

SELECT column1,column2,column3...Aggaregate(column1,column2...)
FROM table_name
Where condition1,condition2....
Group BY column1,column2,...
HAVING Condition1,condition2,....

//Concept having 1.3 clause it is used on the result come from group by clasue

SELECT column1,column2,column3...Aggaregate(column1,column2...)
FROM table_name
Where condition1,condition2....
Group BY column1,column2,...
HAVING Condition1,condition2,....
ORDER BY Column1,column2.....

//Example 1.1
SELECT *,count(c_city)
FROM College_name
GROUP BY c_city
HAVING c_city>1;

//Example 1.2
SELECT C.name,T.city,count(C.c_city) as STUDENT
FROM College_name C
INNER JOIN College_city T
ON C.c_city=T.c_id
GROUP BY c_city
HAVING count(C.c_city)>1;

//Example 1.3
SELECT C.name,T.city,count(C.c_city) as STUDENT
FROM College_name C
INNER JOIN College_city T
ON C.c_city=T.c_id
GROUP BY c_city
HAVING count(C.c_city)>1;
ORDER BY name;

*************************************************************************
SUBQUERY and Exists and not exist
*************************************************************************

//Subquery or nested query and Exists and not exist

//Subquery ,Query inside an other query it will work with all others common like select insert delete update also.

//Syntex
SELECT column1,column2,column3....
FROM table1
WHERE column=
(SELECT column1,column2.. FROM table2 Where Condition1,Condition2....)
//Example 1.1 it return name where this course is running
SELECT name FROM College_name WHERE c_course=2;//here we do not know that what course 2 is represented
but by using subquery concept we can solve this problem .

//Example 1.2 here we solve above problem by using subquery concept.


SELECT name from college_name where c_course=(Select cr_id from college_course where course="M.B.B.S");

// Example 1.3 with OR operator in subquery

/*it will not work because subquery will return multiple value for this we will use IN operator insted of equal (=) wit
h where clause in the first query.*/
//incorrect
SELECT name FROM College_name WHERE c_course = (SELECT cr_id FROM College_course WHERE course
="M.B.B.S" OR course="B.Tech");
//correct
SELECT name FROM College_name WHERE c_course IN (SELECT cr_id FROM College_course WHERE cours
e="M.B.B.S" OR course="B.Tech");
//Example 1.4 IN operator in subquery
SELECT name FROM College_name WHERE c_course IN (SELECT cr_id FROM College_course WHERE cours
e IN("M.B.B.S","B.Tech"));

//concept of EXISTS and NOT EXISTS


we us exists and not exists common with subquery

//syntax 1
if subquery table2 return any single row then table1 will display the result.
SELECT column1,column2,column3,..
FROM table1
WHERE
EXISTS (SELECT column1,column2.. FROM Table2 WHERE Condition )

//syntax 2
if subquery table2 not return any row then table1 will display the result.
SELECT column1,column2,column3,..
FROM table1
WHERE
NOT EXISTS (SELECT column1,column2.. FROM Table2 WHERE Condition )

//EXample 1.1
SELECT name FROM College_name WHERE EXISTS (SELECT cr_id FROM College_course WHERE course="
MBA");
it will show all name of the first table because subquery condition is true.
//EXample 1.2
SELECT name FROM College_name WHERE NOTEXISTS (SELECT cr_id FROM College_course WHERE cour
se="M.Tech");
it will show all name of the first table because subquery condtion is true

*************************************************************************
IF and CASE---used to display result
*************************************************************************
//If,Case is used to display result based on the condition
NOTE:-
1.IF
if we need to show whether a student is fail or pass then we will use if.
if will take three parameter.if(Condition,TrueResult,FalseResult)
2.CASE
we need to show division for each student like first,second,third, then we will use case

we can also use CASE clause with UPDATE clause to update multiple record at once.

//syntax 1 for if clause


SELECT column1,column2,....
IF(condition,true result,false result) as alias_name
FROM table_name;

//syntax 2
SELECT column1,column2,....
IF(condition,true result,false result) as alias_name
FROM table_name;
where condition1,condition2,..
.
.
.
//example
SELECT id,name,percentage
IF(percentage>33,"Pass","Fail") as result
FROM employee;

//syntax for CASE clause

SELECT column1,column2,column3,.....
CASE
when condition1 then result1
when condition2 then result2
when condition3 then result3
ELSE result4 as alias_name
END as alias_name
FROM table_name

//Example not working but without alias name working

SELECT id,name,percentage,
CASE
WHEN percentage>80 AND percentage<=100 then "merit"
WHEN percentage>60 AND percentage<=80 then "First division"
WHEN percentage>45 AND percentage<=60 then "Second division"
WHEN percentage>33 AND percentage<=45 then "third division"
WHEN percentage<33 then "Fail"
ELSE "NOT Correct % "
END as Grade
FROM employee;

//example working but if i put alias name it will not work

SELECT id,name,percentage,
CASE
WHEN percentage>=80 AND percentage<=100 then "merit"
WHEN percentage>=60 AND percentage<80 then "First division"
WHEN percentage>=45 AND percentage<60 then "Second division"
WHEN percentage>=33 AND percentage<45 then "third division"
WHEN percentage<33 then "Fail"
ELSE "NOT Correct % "
END
FROM employee;

//Update multiple record at once

UPDATE employee set


percentage=
(case id
when 9 then 40
when 10 then 45
END)
WHERE id IN(9,10);

*************************************************************************
Arthmetic function
*************************************************************************
//Arthmetic function is used to perform mathmetical operation with column of the table.
we have many arithmetic function
1.CEIL
2.FLOOR
3.ROUND
4.ABS
5.POW
6.sqrt
7.rand
8.pi
9.sign

//example 1
select 4+5 as total;
select 4-5 as total;
select 4*5 as total;
select 4/5 as total;
select 4%5 as total;
select 4 ADD 5 as total;
select 4 SUB 5 as total;
select 4 MUL 5 as total;
select 4 DIV 5 as total;
select 4 MOD 5 as total;

//concept of CEIL

1.select ceil(3.8) as Result; //result=4


//concept of ceil
2.select floor(3.8) as Result; //result=3
//concept of ceil
3.select round(3.8) as Result; //result =4
//concept of ceil
4.select abs(-3.8) as Result; //result=3.8
//concept of ceil
5.select sqrt(100) as Result; //result=10
//concept of ceil
6.select pow(10,2) as Result; //result=100
//concept of ceil
7.select rand() as Result;//result=0.483045034580

//important concept of the ROUND and RAND function

select rand()*100 as result; //it will given value in decimal

select ROUND(rand()*100) as result; //now it will give round value

//if you need value from 1 to 5 how you will get


select FLOOR(1+ ROUND()*5);

//if you need value from 7 to 20 how you will get


select floor(7+round()*20);

//example 2.1

select id,name,(percentage+10) as new_percentage


FROM employee;
//example 2.2
select id,name,percentage,rand()
FROM employee;

//example 2.3

select id,name,percentage
FROM employee ORDER BY rand();

//concept of ceil
8.select pi() as Result;//result=3.1415

//concept of ceil
9.select sign(-38) as Result;//result=-1
select sign(38) as Result;//result=1
select sign(0) as Result;//result=0

*************************************************************************
STRING function
*************************************************************************

//string function
we have many string function we will see one by one
1. UPPER()/UCASE ()
2. LOWER()/LCASE ()
3. LENGTH()
4. CHAR_LENGTH()
5. CONCAT()
6. CONCAT_WS()
7. LTRIM()
8. RTRIM()
9. TRIM()
10.POSITION()
11.LOCATE()it will take three parameter and one parameter is opetional
12.INSTR()

//concet 1 upper
SELECT UPPEER(name) as Name from employee;

//concept 2 lower
SELECT LOWER(name) as Name FROM Employee;

//concept 3 length
SELECT name,length(name) FROM employee//here length will be in bytes

//concept 4 char_length
SELECT name,char_length(name) FROM employee;

//concept 5 concat(name,city)
SELECT concat(name,city) from employee;
SELECT concat(name," ",city) from employee;
SELECT concat(name,"_",city) from employee;

//concept 6 concat_ws(seprate,value1,valeu2)
SELECT concat_ws('_',name,city,gendder) from employee
output-> name_city_gender will be

//concept 7 trim('string') it will trim the string from both side


SELECT trim(' hello world ');//trim from both side
SELECT rtrim('hello world ');//trim in right
SELECT ltrim(' hello world');//trim in left

//concept 8 position('find',"string ") it will search string in the given string


SELECT position('good' IN "asfahn is an engineer and also is a good man")
it will return the index number of the good.

//concept 9 locate('find',"string",start) start is a opetional parameter.


SELECT locate("good",'good morning to the good persion',5);

//concept 10 instr('string','find');
SELECT instr("good morning to the friends","morning");

//String Function
some more string function
1. SUBSTRING()/SUBSTR()
2. MID()
3. SUBSTRING_INDEX()
4. LEFT()
5. RIGHT()
6. LPAD()
7. RPAD()
8. SPACE()
9. REVERSE()
10.REPEAT()
11.REPLACE()
12.STRCMP()
13.FIELD()
14.FIND_IN_SET()
15.FORMAT()
16.HEX(str)

//concept 1 substring(string,start,length) it will return the string from the given point/index/start_point
here start and length parameter is opetional

SELECT substring("good morning friend",5);


SELECT substring("good morning friend",5,6);

//concept 2 MID('string',start,length) it is also work in the same as substring work


select MID('good morning',2,6);

//concept 3 substring_index(string,delimeter,number)
it will give the string until the specifies delemeter
substring_index("www.google.com",".",1);
substring_index("www.google.com",".",2);
substring_index("www.google.com","o",1);
substring_index("www.google.com","g",2);

//concept 3 LEFT("string",index) it will return string of the left side based on given index
SELECT LEFT("Hello world Good Morning",4);
SELECT LEFT("Hello world Good Morning",10);

//concept 4 RIGHT("string",idnex) it will return string of the right side based on given index
SELECT RIGHT("Hello world Good Morning",4);
SELECT RIGHT("Hello world Good Morning",10);

//concept 5 LPAD("String",length,charecter) it will increase the length of the string by adding padding to it.
SELECT LPAD("Good",10,'*');

//concept 6 Space(1000) it will create space


SELECT space(20) as name;

//concept 7 REVERSE(STring) it give the reverse string


SELECT reverse("Good Morning") as MSG;

//concept 8 REPLACE(String,find,replace) it will replace string


SELECT REPLACE("hello world good morning",'morning','night') ;
output-> hello world good night

//concept 9 REPEAT(String,number) it repeat string based on given number


SELECT REPEAT("Good morning",3);

//concept 10 STRCMP(string1,string2)it will return 0 or 1 or -1


SELECT STRCMP("good Morning","Good Morning") output->0
SELECT STRCMP("good Morning","Good ") output->1
SELECT STRCMP("good","Good Morning") output->-1

//concept 11 FIELD(search,str1,str2,str3,str4,str5,....)
SELECT FIELD('hello','good','morning',"to","the","friend","hello");
//concept 12 FIND_IN_SET(search,"string");
SELECT FIND_IN_SET("good","hello friend good morning");//it will not work
SELECT FIND_IN_SET("good","hello,friend,good,morning");//it will work

//concept 13 formate(floating_value,DigitAfterDecimal)
SELECT FORMATE(23.344909,1);
SELECT FORMATE(23.3449080,6);
SELECT FORMATE(23.3449090,3);
SELECT FORMATE(23.3448980,4);

//concept 14 hex(string) it convert string into hex_decimal number


SELECT hex("hello world");

*************************************************************************
DATE function
*************************************************************************
//list of date function
1.CURDATE()
2.CURRENT_DATE()
3.SYSDATE()
4.NOW()
5.LAST_DATE()
6.DAY()
7.DAYNAME()
8.DAYOFMONTH()
9.DAYOFWEEK()
10.DAYOFYEAR()
11.WEEK()
12.WEEKDAY()
13.WEEKOFYEAR()
14.YEAR()
15.YEARWEEK()
16.EXTRACT()
list of parameter with extract function
1.microsecon
2.second
3.minute
4.hour
5.day
6.WEEK
7.month
8.quater
9.year
10.Second_microsecond
11.minute_microsecond
12.minut_second
13.hour_microsecond
14.hour_second
15.hour_minute
16.day_microsecond
17.day_second
18.day_minute
19.day_hour
20.year_month

//concept 1 curdate() it will return current date


SELECT CRUDATE() as DATE;

//concept 2 CURRENT_DATE() it will also return CURRENT date


SELECT CURRENT_DATE() as DATE;

//concept 3 SYSDATE() it will return date and time also


SELECT SYSDATE() as DATE_TIME;

//concept 4 NOW() it will return date and time also


SELECT NOW() as DATE_TIME;

//concept 5 LAST_DATE() it will return last date;


SELECT LAST_DATE() as LAST_DATE;

//concept 6 DAY() it will return day


SELECT day("1990-02-22") as DAY;

//concept extract(use parameter,"datetime") it will do all the operation by changing parameter.like day,month year m
inute second.

SELECT extract(month from "1998-04-21") as MONTH;


SELECT extract(quater from "1998-04-21") as MONTH;
SELECT extract(year from "1998-04-21") as MONTH;
SELECT extract(second from "1998-04-21") as MONTH;
SELECT extract(minute_second from "1998-04-21") as MONTH;
SELECT extract(year_month from "1998-04-21") as MONTH;
SELECT extract(microsecond from "1998-04-21 12:24:34:33") as MONTH;

*************************************************************************
DATE function
*************************************************************************
/list of date function
some more function of the date
1.DATE_ADD()
2.ADDDATE()
3.MAKEDATE()
4.DATE_SUB()
5.SUBDATE()
6.DATEDIFF()
7.TO_DAYS()
8.FROM_DAYS()
9.PERIOD_ADD()
10.PERIOD_DIFF()
11.DATE_FORMATE()
12.STR_TO_DATE()
//List of ADDUNIT
1.microsecon
2.second
3.minute
4.hour
5.day
6.WEEK
7.month
8.quater
9.year
10.Second_microsecond
11.minute_microsecond
12.minut_second
13.hour_microsecond
14.hour_second
15.hour_minute
16.day_microsecond
17.day_second
18.day_minute
19.day_hour
20.year_month

DATE
day->d(1-31),e(01-31),D(st,nd,rd,),j(001-265)
month->M(Januaary),b(jan to dec),m(00-12),c(0-12)
Year->%Y,%y
WEEK->%a(mon),%W(Monday),w(0-6)

TIME
hour->%h,%H,%g,%G
MINUTE->%i;
SECOND->%s(00-59)
MICROSECOND->%f(000000 to 999999);
MERIDIAN->%p
/*
concept 1 ADDDATE('date' interval number) it add day in the given date.
ADDDATE('date' interval number days)
ADDDATE('date' interval number month)
ADDDATE('date' interval number year)*/

SELECT ADDDATE("1998-02-12",INTERVAL 10 day);


SELECT ADDDATE("1998-02-12",INTERVAL 2 month);
SELECT ADDDATE("1998-02-12",INTERVAL 5 year);
SELECT ADDDATE("1998-02-12",INTERVAL 5 WEEK);
SELECT ADDDATE("1998-02-12",INTERVAL 5 QUATER);
SELECT ADDDATE("1998-02-12",INTERVAL 24 HOUR);
SELECT ADDDATE("1998-02-12",INTERVAL 1000 MINUTE);
SELECT ADDDATE("1998-02-12",INTERVAL 1000 MINUTE);

//concept you have to do by you self whenever you free

//Concept date_formate("date",'formate') it will return on the basis of the formate you specify there

SELECT date_format('1998-02-12','%Y');
SELECT date_format('1998-02-12','%Y/%M/%s');
SELECT date_format('1998-02-12','%Y-%b-%s');
SELECT date_format('1998-02-12','%d-%b-%Y');
SELECT date_format('1998-02-12 23:55:23:2334','%d-%b-%Y %h:%i');
SELECT date_format('1998-02-12 23:55:23:2334','%d-%b-%Y %h:%i:%s');
SELECT date_format('1998-02-12 23:55:23:2334','%d-%b-%Y %h:%i:%s:%f');
SELECT date_format('1998-02-12 23:55:23:23','%d-%b-%Y %h:%i:%s:%f %p');

//concept STR_TO_DATE('UserReadableDate','SQL FORMATE')


it is used to convert user readable date into sql formate
it will convert user readable date into sql formate date
SELET STR_TO_DATE('july 10 2020','%a %d %Y')

*************************************************************************
TIME function
*************************************************************************
//time fucntion
1.CURTIME()
2.CURRENT_TIMESTAMP()
3.LOCALTIME()
4.LOCALTIMESTAMP()
5.TIMESTAMP()
6.TIME()
7.TIMEDIFF()
8.HOUR()
9.MINUTE()
10.SECOND()
11.MICROSECOND()
12.ADDTIME()
13.SUBTIME()
14.MAKETIME()
15.TIME_FORMATE()
16.SEC_TO_TIME()
17.TIME_TO_SEC()

//this concept is similar to date fucntion you just memorize fucntion name then sart using it.

*************************************************************************
ALTER COMMAND
*************************************************************************

//Alter commond is a immportant common we use to alter table.


we hava many alter commond we will see one by one.
1. add column in table
2. changing data type of a column
3. Change column name
4. Adding constraints to a column
5. changing column position
6. Delete column
7. Rename Table

IMPORTANT ALTER COMMAND


--------------------------------------
Add column in the table :
alter table student add result varchar(20);

Change the field size:


alter table student modify result varchar(10);
Change the position of the column :
alter table student modify result varchar(10) after address;

Drop a perticuler column of the table:


alter table student drop column result;
or
alter table student drop result;

Change the name of the column :


alter table student change result myresult varchar(20);

check the constraint associated with the column:


given code:
select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE
_NAME
from information_schema.KEY_COLUMN_USAGE
where TABLE_NAME = 'stu';

my code:
select column_name,constraint_name,referenced_column_name,referenced_table_name from information_schema.k
ey_column_usage where table_name='stu';

Add the constraints to the column


1.Add primary key:
alter table student add primary key(sid)
alter table student add constraint sid_pk primary key(sid)
Remove primary key:
alter table student drop primary key;
alter table student drop sid_pk;

2.Add default key:


alter table stu change subject subject varchar(20) default 'java';
alter table stu alter subject set default 'python';
Remove: default key:
alter table student alter subject drop default;

3.Add foreign key:


alter table student add constraint sid_cid_fk foreign key(cid) references course(cid);
alter table student add constraint stu_cour_fk foreign key(cid) references course(ci);
Remove: foreign key
alter table student drop foreign key;//not work
ALTER TABLE student DROP FOREIGN KEY stu_cour_fk;//work

4.Add not null key:(not sure please prove)


alter table stu change marks marks int not null;
Remove:
alter table stu modify marks int;

5.Add check key:(not sure please prove)


a)alter table stu add check(marks>30)
b)alter table stu add constraint stu_ck_1 check(marks>30) ;
Remove:
a)alter table stu drop check const_value;// after check constraint value required work
b)alter table stu drop constraint const_vakue;//work
6.Add unique key (not sure please prove)

alter table student add unique(sid);


alter table student add constraint uni_key unique(sid);
Remove:
alter table stu drop unique constr_value;
alter table stu drop constraint constr_value;

Add Composit key:


alter table student add primary key(sid,subject);
alter table student drop primary key;

Change the name of the table:


alter table stu rename as student;

//concept 1 add column


ALTER table table_name
ADD column_name datatype;

// concept 2 Modify column/changing column data type


ALTER table table_name
MODIFY column_name datatype;

//conept 3 Delete a column


ALTER table table_name
DROP column_name datatype;

//concept 4 Rename column


ALTER TABLE table_name
CHANGE column_name NEW_column_name datatype;

//concept 5 Rename table


ALTER TABLE table_name RENAME new_table_name;

//example 1.1 add columne emial to the employee table

ALTER TABLE employee


add email varchar(255);

//exampl 1.2 change position of the column email


ALTER TABLE employee
MODIFY email int AFTER name;

//example 1.3 change datatype of the column email


ALTER TABLE employee
modify email int(255);

//example 1.4 change constrant of the column email


/*ALTER TABLE employee wrong way to do this
MODIFY UNIQUE email;*/
ALTER TABLE employee
ADD unique(Email)

//example 1.5 change name of the column email to email_id


/*ALTER TABLE employee wrong way to do this
CHANGE email,email_id;*/
ALTER TABLE emoloyee
CHANGE emial,email_id varchar(255);

//example 1.6 delete email column of the table


/*ALTER TABLE employee wrong way to do this
DROP emial_id ;*/
ALTER TABLE emoloyee
DROP COLUMN email_id;

//example 1.7 change name of the table


ALTER TABLE employee
RENAME employees;

//impotant concept we should understand

some times you come across where you have seen ,when you use AUTOINCREMENT in your table then it will inc
rement by it self.
when you delete any record then id value show bad impact.
when you insert new record it will continue from that index.
so need to solve this problem by using alter commond

//change index of the id when you delete any recode


syntax
ALTER TABLE table_name
AUTO_INCREMENT (id= anynumber from where you want to continue.)

ALTER TABLE employee


AUTO_INCREMENT=4;

*************************************************************************
DROP and TRUNCATE COMMAND
*************************************************************************
//drop and truncate function is used to remove table and table data

//concept 1 drop table


it will remove table data and also remove table it self.

//syntax
DROP table student;

//concept 2 truncate table


it will remove table data only table will not be remove we can insert data in this table again.

//syntax
TRUNCATE table student;

*************************************************************************
VIEW COMMAND
*************************************************************************
//view commond
NOTE: why we need to use view ,the resion is that
when we need to use a complex query again n again like to join multiple table or, join three table it's a time taking pr
ocess to write again again
thats why we will create view and past that query into view and when you need just call it by view name.

//syntax
CREATE VIEW view_name
AS
SELECT column1,column2,column3....
FROM table_name
WHERE condition1,condition2,condition3,...
Group By column_name,
ORDER BY column_name;

ALTER VIEW view_name


AS
SELECT column1,column2,column3....
FROM table_name
WHERE condition1,condition2,condition3,...
Group By column_name,
ORDER BY column_name;
//example create view
CREATE VIEW MYVIEW AS
SELECT C.name,s.course,T.city from college_name C
INNER join college_course S
ON C.c_course=S.cr_id
INNER join college_city T
ON C.c_city=T.c_id

//example ALTER view


CREATE VIEW MYVIEW AS
SELECT C.name,s.course,T.city from college_name C
INNER join college_course S
ON C.c_course=S.cr_id;

//we can also use create or Replace insted of alter keyword


//example ALTER view
CREATE OR Replace VIEW MYVIEW AS
SELECT C.name,s.course,T.city from college_name C
INNER join college_course S
ON C.c_course=S.cr_id;

//if you need to rename view then what you will do


we can do this also
by using following syntax

//syntax
RENAME table view_name
TO new_view_name

//example
RENAME table My_view To Your_view;
//if we need to drop view how you will do that
we can do that with the help of following syntax.

//syntax
DROP view view_name;

//Example
DROP view My_view;

there are some advatage and disadvantage of the view


advantage;-
1.simplify complex query
2.provide extra layer of security

disadvantage
1.performance decrease.
2.dependency on table

*************************************************************************
INDEX COMMAND
*************************************************************************
//index commond we use to increase the seraching in the table
but we offence use it on the big table .

//how we will create index ,


we can create index by using the below syntax

//syntax
CREATE INDEX index_name
ON table_name(column1,column2,column3,....);

//how we will drop/delete index .


it is simple you can just use follow the below syntax.

DROP INDEX index_name


ON table_name;

//guidline of index
when you create index you should remember some tips.
1. you should not select a column for index which is alredy a primay column or unique.
2. you we select that column which is mostly use form searching

3.index we can apply on that column which is used for join in multiple table.
4.we shoid to that column which has many null values.
5. we should not apply index on small table

//example 1.1
SELECT * FROM student;
where dob>"1997-12-30";

//example 1.2

CREATE INDEX my_index


ON student(dob);
SELECT * FROM student
where dob>"1997-12-30";

we can create index in multiple table


CREATE INDEX my_index
ON student(dob,age,phone);

//we can also see how many index are in an table


syntax

show index from table_name

//example
show index from student;

//if we need to remove/drop index how you will do that


DROP index my_index ON student;

You might also like