Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Thanks To Visit: Most Welcome

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Thanks to Visit

Most Welcome

SPT999
Create database mydatabase;

Show databases;

Drop database mydatabase;

use mydatabase;

Create table mytable(col dtype,col2 dtype);

Show tables;
Desc mytable;

Drop table mytable;


Insert into mytable values();

Select * from mytable;

Select name from mytable

Select name as User_Name from mytable

Select name as “Emp Name” from mytable

Select name,age from mytabl;


Select name from mytabl where age =25;

Select name,age from mytable where salary=25000


= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL
this operator may be written as !=

BETWEEN Between a certain range


LIKE Search for a pattern
IN To specify multiple possible values for a
column
SELECT * FROM Products
WHERE Price BETWEEN 100 AND 20;

SELECT * FROM Customers


WHERE City LIKE ‘K%';

SELECT * FROM Customers


WHERE City IN (‘Kanpur','Lucknow');
ALTER TABLE table_name
ADD column_name datatype;

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

alter table mytable change age EmpAge int;

alter table my rename to mytable;


Write a query to add a column bonus and add bonus as per the
percentage of salary.
Update xyz set col1=‘value’ , col2=‘value’
Where city=‘Kanpur’

Truncate table mytable;

Delete from xyz where condition;

Delete from xyz;

Delete can be roll back; it is slower than truncate;


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Age int
);

ALTER TABLE Persons


MODIFY Age int NOT NULL;
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

SELECT COUNT(first_name), city


FROM employee
GROUP BY city;
Order by count(first_name) desc
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
The HAVING clause was added to SQL because
the WHERE keyword cannot be used with aggregate functions.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
1: Query to print number of employees in particular city.

2: Query to print number of employees in particular city that are less than 3

3: Query to print name and city of employees in particular city that are less
than 3

4: write a query to find out maximum salary of a city that will be accumulate
by addition of salary of employees group by city.
select city,count(city) from employee group by
city having count(city)<3;

select first_name,city from employee where city in (select city from employee
group by city having count(city)<3);
Write a query to find out records which have post clerk and city Kanpur.

Write a query to find out records which have post clerk or city Kanpur.

Write a query to find out records where city is not Kanpur.

Write a query to find records where contact is null , not null.

select first_name from employee where


post='clerk' and city='kanpur'

select first_name from employee where


post='clerk' or city='kanpur'

select first_name from employee where city


not in ('kanpur');

select first_name from employee where


contact is not null;
Subquery

select first_name,salary from employee where


salary=(select max(salary) from employee);
1: Write a query to find out first_name, last_name,
post, salary of all the employees whose post is same
as the post of employee whose emp_id is ‘B001’

2: Write a query to find out first_name, salary of all


the employees whose salary is maximum salary of
Dehradun’s employees.

3: Write a query to find out first_name, and


last_name in a single column with salary
select first_name,last_name,post,salary from employee where
post=(select post from employee where emp_id='B001');

select first_Name,salary from employee where salary>(select


max(salary) from employee where city='dehradun');

select concat(first_name,' ',last_name),salary as Employee from


employee;
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LEN Returns the length of a string (in characters)
GTH

CONCAT Adds two or more expressions together


CONCAT_WS Adds two or more expressions together with a separator
FIELD Returns the index position of a value in a list of values
MySQL
FIND_IN_SET Returns the position of a string within a list of strings
String FORMAT Formats a number to a format like "#,###,###.##", rounded to a
specified number of decimal places
Functions INSERT Inserts a string within a string at the specified position and for
a certain number of characters

INSTR Returns the position of the first occurrence of a string in


another string

LCASE Converts a string to lower-case


LEFT Extracts a number of characters from a string (starting from
left)

LENGTH Returns the length of a string (in bytes)


LENGTH Returns the length of a string (in bytes)

LOCATE Returns the position of the first occurrence of a substring in


a string

LOWER Converts a string to lower-case

LPAD Left-pads a string with another string, to a certain length

LTRIM Removes leading spaces from a string

MID Extracts a substring from a string (starting at any position)

POSITION Returns the position of the first occurrence of a substring in


a string

REPEAT Repeats a string as many times as specified

REPLACE Replaces all occurrences of a substring within a string, with


a new substring

REVERSE Reverses a string and returns the result

RIGHT Extracts a number of characters from a string (starting


from right)

RPAD Right-pads a string with another string, to a certain length


RTRIM Removes trailing spaces from a string

SPACE Returns a string of the specified number of space characters

STRCMP Compares two strings

SUBSTR Extracts a substring from a string (starting at any position)

SUBSTRING Extracts a substring from a string (starting at any position)

SUBSTRING_INDEX Returns a substring of a string before a specified number of delimiter


occurs

TRIM Removes leading and trailing spaces from a string

UCASE Converts a string to upper-case

UPPER Converts a string to upper-case


ABS Returns the absolute value of a number

ACOS Returns the arc cosine of a number


ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of one or two
numbers
ATAN2 Returns the arc tangent of two numbers

AVG Returns the average value of an


expression
CEIL Returns the smallest integer value that is
>= to a number
CEILING Returns the smallest integer value that is
>= to a number
Maths COS Returns the cosine of a number
Functions COT Returns the cotangent of a number
COUNT Returns the number of records returned
by a select query
DEGREES Converts a value in radians to degrees

DIV Used for integer division


EXP Returns e raised to the power of a
specified number
FLOOR Returns the largest integer value that is
<= to a number
GREATEST Returns the greatest value of the list of
arguments
LEAST Returns the smallest value of the list of
arguments
LN Returns the natural logarithm of a
number
LOG Returns the natural logarithm of a
number, or the logarithm of a number to
a specified base
LOG10 Returns the natural logarithm of a
number to base 10
LOG2 Returns the natural logarithm of a
number to base 2
MAX Returns the maximum value in a set of
values
MIN Returns the minimum value in a set of
values
MOD Returns the remainder of a number
divided by another number
PI Returns the value of PI
POW Returns the value of a number raised to
the power of another number
POWER Returns the value of a number raised to
the power of another number
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number
of decimal places
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number
TRUNCATE Truncates a number to the specified
number of decimal places
ADDDATE Adds a time/date interval to a date
and then returns the date
ADDTIME Adds a time interval to a
time/datetime and then returns the
time/datetime
CURDATE Returns the current date
CURRENT_DATE Returns the current date
CURRENT_TIME Returns the current time
CURRENT_TIMESTAMP Returns the current date and time
CURTIME Returns the current time
DATE Extracts the date part from a

Date DATEDIFF
datetime expression
Returns the number of days between
Functions DATE_ADD
two date values
Adds a time/date interval to a date
and then returns the date
DATE_FORMAT Formats a date
DATE_SUB Subtracts a time/date interval from a
date and then returns the date
DAY Returns the day of the month for a
given date
DAYNAME Returns the weekday name for a
given date
DAYOFMONTH Returns the day of the month for a
given date
DAYOFWEEK Returns the weekday index for a
given date
DAYOFYEAR Returns the day of the year for a
given date

EXTRACT Extracts a part from a given date


FROM_DAYS Returns a date from a numeric
datevalue
HOUR Returns the hour part for a given
date
LAST_DAY Extracts the last day of the
month for a given date

LOCALTIME Returns the current date and


time
LOCALTIMESTAMP Returns the current date and
time
MAKEDATE Creates and returns a date based
on a year and a number of days
value
MAKETIME Creates and returns a time based
on an hour, minute, and second
value
MICROSECOND Returns the microsecond part of
a time/datetime

MINUTE Returns the minute part of a


time/datetime

MONTH Returns the month part for a


given date
MONTHNAME Returns the name of the month
for a given date

NOW Returns the current date and


time
QUARTER Returns the quarter of the year
for a given date value
SECOND Returns the seconds part of a time/datetime

SEC_TO_TIME Returns a time value based on the specified seconds

STR_TO_DATE Returns a date based on a string and a format

SUBDATE Subtracts a time/date interval from a date and then


returns the date
SUBTIME Subtracts a time interval from a datetime and then
returns the time/datetime
SYSDATE Returns the current date and time
TIME Extracts the time part from a given time/datetime

TIME_FORMAT Formats a time by a specified format


TIME_TO_SEC Converts a time value into seconds
TIMEDIFF Returns the difference between two time/datetime
expressions
TIMESTAMP Returns a datetime value based on a date or datetime
value
TO_DAYS Returns the number of days between a date and date
"0000-00-00"
WEEK Returns the week number for a given date

WEEKDAY Returns the weekday number for a given date

WEEKOFYEAR Returns the week number for a given date

YEAR Returns the year part for a given date


YEARWEEK Returns the year and week number for a given date
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2,
... ASC|DESC;

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Select curdate();

Select current_date();

Select sysdate();
Select now();
select curtime();
create table new2(name varchar(20),dob date,tob time,dtob datetime);

insert into new2 values('2020-05-03','5:5:45','2020-05-4 3:4:5');

select year(curdate())-year(dob)-2022,month(curdate())-
month(dob),day(curdate())-day(dob) from new2;

select datediff(curdate(),dob)/365 as
year,mod(datediff(curdate(),dob),365)/30 as month,
mod(mod(datediff(curdate(),dob),365)/30,30) as day from new2;

select dayname(dob) from new2;

select monthname(dob) from new2;


create table new(emp_id int not null
auto_increment primary key,name
varchar(20));

create table new2(sr int not null


auto_increment primary key,emp_id
int,foreign key(emp_id) references
new(emp_id));
Joining
Joining is the process of combining Two or more tables to
collect records from Multiple tables.

It produces cross product of multiple tables with some


conditions.

Natural Join.
Self Join.
Inner join
Left
Right
cross
Natural Join

SELECT s1.col_name, s2.col_nam


FROM table1 s1
Natural join table2 s2
Student Project
RollN StuName Marks PrN Project RollN
1 Singh 450 1 E-Com 2
2 Vikas 550 2 Social-Med 3
3 Arjun 365 3 Travel-Age 1

Select * from student, project

RollN StuName Marks PrN Project RollN


1 Singh 450 1 E-Com 2
1 Singh 450 2 Social-Med 3
1 Singh 450 3 Travel-Age 1
2 Vikas 550 1 E-Com 2
2 Vikas 550 2 Social-Med 3
2 Vikas 550 3 Travel-Age 1

3 Arjun 365 1 E-Com 2


3 Arjun 365 2 Social-Med 3
3 Arjun 365 3 Travel-Age 1
RollN StuName Marks PrN Project RollN
1 Singh 450 1 E-Com 2
1 Singh 450 2 Social-Med 3
1 Singh 450 3 Travel-Age 1
2 Vikas 550 1 E-Com 2
2 Vikas 550 2 Social-Med 3
2 Vikas 550 3 Travel-Age 1

3 Arjun 365 1 E-Com 2


3 Arjun 365 2 Social-Med 3
3 Arjun 365 3 Travel-Age 1

Select * from student , project where student.rolln=project.rolln

RollN StuName Marks PrN Project RollN


1 Singh 450 3 Travel-Age 1
2 Vikas 550 1 E-Com 2
3 Arjun 365 2 Social-Med 3
Select * from student , project where student.rolln=project.rolln

RollN StuName Marks PrN Project RollN


1 Singh 450 3 Travel-Age 1
2 Vikas 550 1 E-Com 2
3 Arjun 365 2 Social-Med 3

Using Natural Join


Select * from student natural join project

RollN StuName Marks PrN Project RollN


1 Singh 450 3 Travel-Age 1
2 Vikas 550 1 E-Com 2
3 Arjun 365 2 Social-Med 3
Self Join

SELECT s1.col_name, s2.col_name...


FROM table1 s1, table1 s2
WHERE s1.common_col_name = s2.common_col_name;

select * from project as p1 ,project as p2


where p1.RollN=p2.Rolln and
p1.prN<>p2.prN;
Project
PrN Project RollN
1 E-Com 2
2 Social-Med 3
3 Travel-Age 1
4 Bloggging 2

Select P1.RollN , P1.Project from Project P1,Project P2 where p1.RollN=p2.RollN and p1.PrN<>p2.PrN

RollN Project RollN


1 E-Com 2
4 Bloggging 2
Inner Join
select * from student inner join project on
student.RollN=project.RollN;

Left Join
select * from student left join project on
student.RollN=project.RollN;

Right Join
select * from student right join project on
student.RollN=project.RollN;
The CROSS JOIN keyword returns all matching records from
both tables whether the other table matches or not.
So, if there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in
"Customers", those rows will be listed as well.
If you add a WHERE clause (if table1 and table2 has a relationship),
the CROSS JOIN will produce the same result as the INNER JOIN clause:
CREATE VIEW view_name AS Note: A view always shows up-to-date
SELECT column1, column2, data! The database engine recreates the
FROM table_name view, every time a user queries it.
WHERE condition;

alter view my as select first_name,post,salary


from employee;

drop view my;


Primary Key:
A Column or set of column to uniquely identify the records

Foreign Key: A column which has a reference of another


table records.
Referential Integrity

1: Insert into parent table do not have any violation.


2: delete into parent table may have a violation.
3: update into parent key may have a violation.

4: Insert into child table may have violation.


5: delete into child table do not have any violation.
6: update into child table may have violation .
Referential Integrity

create table project(pr_id varchar(10),nop int,studentid int,foreign


key(studentid) references student(st_id) on delete cascade)

Foreign key is not the primary key of same table.. Then we can set it null

create table project(pr_id varchar(10),nop int,studentid int,foreign


key(studentid) references student(st_id) on delete set NULL)
Foreign key alter: Add

Alter table table_name add foreign key (column_name) references


another_table_name(column_name)

Foreign key alter: Delete

Alter table table_name drop foreign key constraints_name;

To show constraints name

Show create table table_name;


ER Diagram:
Library Management

School Management

Bank Database Management


Relationship
One to One
One to Many
Many to One
Many to Many

We have to mention this relationship in relationship table


VIKAS SINGH
(9889643709)

vikasspatel9@gmail.com

You might also like