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

SQL Nootes

The document discusses various SQL commands like CREATE, ALTER, DROP for databases and tables. It also covers SELECT queries with filters, sorting, aggregation and joins. Subqueries, views, set operations and temporary tables are also explained with examples.

Uploaded by

Abhinav Jaiswal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

SQL Nootes

The document discusses various SQL commands like CREATE, ALTER, DROP for databases and tables. It also covers SELECT queries with filters, sorting, aggregation and joins. Subqueries, views, set operations and temporary tables are also explained with examples.

Uploaded by

Abhinav Jaiswal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Session 31 >>>>>>>>>>>>>>>>>>>>>

DDL COMMANDS

1) Create database campusX


2) Drop database campusX
3) Create database if not exist campusX
4) Drop database if exist campusX

5) Create table users (


user_id INTEGER,
name VARCHAR(255)
)

6) Truncate table users

7) Data Integrity - accuracy, completeness, consistency


(constraints, Transaction, Normalization) methods of data integrity

8) Create table users (


user_id integer not null,
email varchar(255) not null)
)

9) Create table users (


user_id integer not null,
email varchar(255) unique not null)
)

10) Create table users (


user_id integer not null,
email varchar(255) not null,
password varchar(255) not null,

constraint user_email_unique UNIQUE (email)


)

11) Create table users(


user_id integer not null primary key,
email varcher(255) not null,
)
12) Create table users (
user_id integer not null auto increament,
email varchar(255) not null,
password varchar(255) not null,

constraint user_email_unique UNIQUE (name,email)


constraint user_pk primary key (user_id, email)
)

13) Create table users (


user_id integer not null ,
email varchar(255) unique not null,
age not null check (age > 6 and age < 25 )
)

14) table date default datetime_stanp

15) Create table customers(


cid integer primary key auto_increatment ,
name varchar(255) not null ,
email varchar(255) not null unique
)
Create table orders(
order_id integer primary key auto_increament ,
cid integer not null,
constraint orders_fk foreign key orders(cid) references
customers(cid)
)

16) Create table customers(


cid integer primary key auto_increatment ,
name varchar(255) not null ,
email varchar(255) not null unique
)
Create table orders(
order_id integer primary key auto_increament ,
cid integer not null,
constraint orders_fk foreign key orders(cid) references
customers(cid)
on update cascade
on delete cascade)
)

17) Alter table ( add column / delete column / modify column )

alter table customers add column password varchar(255) after name

adding multiple column-


alter table customers(
add column pan_number after surname
add coliumn password integer before surname )

18) Alter table customers modify column surname integer

19) Alter table customers add columns age integer not null
Alter table customers add constraints customer _age_check ( age > 13)

20) Alter table customers modify constraints users_age_check check (age>6) not
possible to edit constraints

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Session 32
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

21) Insert into campusx.users ( user_id,email,password)


values (null,'nitish','nitish@gmail.com','12234')

22) Insert into campusx.users(null,'nitish','nitish@gmail.com','12234')

23) Insert into table values


(..............),
(..............),
(..............)

24) Select * from campusX where

25) Select columns, columns from campusx

26) Select os as 'Operating System' , model as '..........' from campusX


27) Select model , sqrt(resolution width* resolution width + resolution height*
resolution height )/screen_size as ppi
from campusX

28) Select model ,'smartphone' as 'type' from campusx --- to make the constant
column

29) Select distinct(brand_name) as 'All Brand' from campusX

30) Select distinct brand_name , operating_system

31) Select * from smartphones where brand_name = 'samsung'

32) Select * from smartphones where price BETWEEN 100000 and 200000

33) Select * from smartphones where price < 250000 and rating > 8000

34) Select * from campusX where processor_brand in/not_in (exionios,snapdragon)

35) Update>>>>> Update smartphones (Generally Alter for columns and


update for rows)
set processor_brand ='dimensity'
where processor_brand='mediatek'

36) Delete>>>>> Delete from campusX


where price> 2000000 and batttery_capacity > 4000

37) Select max/avg/sum/count/count(price) from campusX .smartphones

38) Select count(distinct(price)) as 'count' from campusX

39) Select abs/round/ceil/floor(price - 1000000) as 'temp' from campusX

<<<<<<<<<<<<<<<<<<<<<<<<< Session 33 >>>>>>>>>>>>>>>>>>>>>>>

SORTING DATA

40) Select * from campusX order by screen_size desc limit (x,y) ---- x se start y
rows print krdo

41) Select model_name , front_cam + back_cam as 'total_num_camera' from campusX


order_by total_camera desc

GROUPING DATA ( Having is used for group by inplace of where )

42) Select brand_name, count(*) as 'num_phone',(round(screen_size),2) from campusx


groupby brand_name order_by num_phone

43) Select brand_name,count(*) as 'num_phone' groupby brand_name,processors_brand

44) Select brand_name , count(*) as 'count' from campusX


where has_nfc='True' and has_ir_blaster ='TRUE'
groupby brand_name having count > 20
orderby count desc limit 5

<<<<<<<<<<<<<<<<<< Session 34 >>>>>>>>>>>>>>>>>>>>>(join form temperory table


and to reduce the data redundancy )
45) Left join ( Pehli table ka data pura chahiye second se match ho ya na ho but
chahiye)
select * from membership t1
left join users t2 ( Yaad rakhna wapas se select * nahi krna hota)
on t1.user_id=t2.user_id

46) Cross Join


SELECT * FROM sql_cx_live.users t1
cross join sql_cx_live.groups t2

47) Inner Join


SELECT * FROM sql_cx_live.users t1
join sql_cx_live.groups t2
on t1.user_id = t2.user_id

48) Self Join


select * from users1 t1
join users1 t2
on t1.user_id=t2.emergency_contact

49) More than one column


select * from students t1
left/ right/ join class t2
on t1.class_id=t2.class_id
and t1.enrollment_year=t2.class_year

50) More than 2 tables


select * from order_details t1
join orders t2
on t1.order_id=t2.order_id
join users t3
on t2.user_id=t3.user_id

51) More than 2 table with ( Column filtering )


select t1.order_id,t1.amount,t1.profit,t3.name_id from order_details t1
join orders t2
on t1.order_id=t2.order_id
join users t3
on t2.user_id=t3.user_id

52) Profitable order


select t1.order_id, sum(t2.profit) from flipkart.orders t1
join flipkart.order_detail t2
on t1.order_id=t2.order_id
group by t1.order_id
having sum(t2.profit) > 0

--------- Set Operation in SQL --------------

UNION -- All unique rows

UNION ALL -- Union with duplicate rows

INTERSECT -- Common wale a jayenge

EXCEPT -- Pehli wali table ke woh element aayenge jo 2nd table me nhi h

54) Select * from person1


UNION / UNION ALL / INTERSECT / EXCEPT
Select * from person2

55) FULL OUTER JOIN TRICK (because it is not present in mysql )


select * from membership t1
left join users t2
on t1.user_id=t2.user_id
UNION
select * from membership t1
right join users t2
on t1.user_id=t2.user_id

( F J W G H S D O )

56) Row filtering


Select * from ordeers t1
join users t2
on t1.user_id = t2.user_id
where t2.city = 'Pune' and t2.name = 'Sarita'

<<<<<<<<<<<<<<<<<<<<< Session 35 >>>>>>>>>>>>>>>>>>>>>>>> ( Subquery - Query


ke andar query )

57) Basic Example of Subquery


Select * from movies
where (gross- budget) =( select max(gross- budget) from movies )

58)CTE:-
use flipkart;
with top_directors as (select director
from flipkart.movies
group by director
order by sum(gross) desc
limit 3)

select * from flipkart.movies


where director in (select * from top_directors)

59)Most profitable every year


select * from movies
where (year,gross-budget) in (select year, max(gross-budget)
from movies
group by year)

60)
with top_duos as (select star ,director ,sum(gross)
from movies
group by star , director
order by sum(gross) desc limit 5)

select * from movies


where (star,director,gross) in (select * from top_duos)

61) Corelated Subquery


select * from movies m1
where score > (select avg(score) from movies m2 where
m2.genre=m1.genre
group by genre)
62) select name,f_name,count(*)from users t1
join orders t2 on t1.user_id =t2.user_id
join order_details t3 on t2.order_id=t3.order_id
join food t4 on t3.f_id=t4.f_id
group by t2.user_id,t3.f_id

63) Subquery in select


select name,votes/select sum(votes) from movies))*100 from movies
or
select name, genre,score ,(Select avg(score) from movies m2 where
m2.genre=m1.genre)
from movies m1 (usage of subquery also there)

64) Subquery in from


select r_id,avg_rating from (select r_id,avg(restaurant_rating) as 'avg_rating'
from orders
group by r_id) t1
join restaurants t2
on t1.r_id=t2.r_id

65) Subquery with having


-- Find genres having avg score > avg score of all the movies
select genre ,avg(score )
from movies
group by genre
having avg(score) > (select avg(score) from movies)

66) Independent Subquery

<<<<<<<<<<<<<<<<<<<< Session >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Views ( Virtual table , not present physically on memory / logical table ) ---
Changes in table reflects on view also
Type - Single / Complex ------- On basis of no of joins
- Read only / Update view ------- On basis of if you can update (
Agar view updatable h toh view me change krne se original table me bhi change aa
jayega )
- If you have Aggregate fn / Distinct / Group by/ Having/ union /
Subquery / Certain joins then it will be read only view , you cant make this as
updatable view
- Materialized Views --- It can reduce the execution time / they
store the result ( result store krega so time reduce ho jayega )also so it reduce
the time
Advantage of materialized view fast / disadvantage - have to update
manually whenever you want the updated result kuki woh to store ho gya ab update
nhi hoga apne aap

- Adavntage of Views - To give control on certain data only sara


data dikhane ki jaroorat nahi / do not occupy memory
67)
Create view indigo as
select * from flights
where airline = 'Indigo' -------------- Select * from indigo ( we have created
the subset virtually )

68)
Create view joined_order_data as
Select order_id, amount, r_name , name ,date
from order_details t1
join orders t2
on t1.order_id=t2.order_id
join users t3
on t2.user_id=t3.user_id ------------------ Select * from joined_order_data (
Ab hum isse use kr sakte hai )

69) How to change the view


Alter view indigo
Select * from flights
where airline = 'Indigo_airline'

------------ User Defined Function


Syntax

-- Stored Procedure ( block of sql statements and procedural procedural logic that
is stored in a database ) pehle se likhe huye sql statement and procedure that we
will use

CREATE PROCEDURE 'new_procedure' ()


BEGIN

END

70) Create procedure hello_world ( )


begin
select "hello world" ;
end

-- CALL hello_world ( )

71) Create procedure add_user (IN input_name varchar(255) , IN input_name


VARCHAR(255) ) ---- yeh parameterised stored procedure h isme parameter aayega
and IN is used for input
begin
DECLARE user_count INTEGER ;
SELECT COUNT(*) INTO user_count FROM users WHERE email = input_email;

IF user_count = 0 THEN
INSERT INTO users (name,email) VALUES (input_name ,
input_email );
end

------------------------ TRANSACTIONS -------------------------- ( Database


transaction is a sequence of operation that are perforemed as a single unit of work
in a database management )
transaction only valid for write oeration that is ( insert update delete ) ya toh
pure statement honge ya phir ek bhi nhi hoga
Database transaction three main command
1) Commit - sare execution ke baad commit krna padega to make permanent changes
2) Rollback - wapas jaane ka tarika
3) Savepoint - kisi specific jagah pr pauchne ke liye savepoint use krte h bcoz
rollback me initial pr pauch jayenge if beech me save nhi kiya ha toh so we are
goint to use savepoint at particular stage

AUTOCOMMIT- Bina kisi explicit commit command diye changes ko save krna hi
autocommit h generally yahi hota hai but when you start transaction then autocommit
band ho jata h uss case me
how to turn off autocommit == SET autocommit = 0 now ab aapko khud se commit krna
padega

72)
START TRANSACTION ;
UPDATE person
set BALANCE = 4000 WHERE ID = 1;

UPDATE person
SET balance = 15000 WHERE ID = 4;
COMMIT / ROLLBACK ( rollback ulte direction me hota h )

73) rollback to specified savpoint


START TRANSACTION ;

SAVEPOINT A;
UPDATE person
set BALANCE = 4000 WHERE ID = 1;
SAVEPOINT B;
UPDATE person
SET balance = 15000 WHERE ID = 4;

ROLLBACK B;

74) rollback with commit


START TRANSACTION ;
UPDATE person
set BALANCE = 4000 WHERE ID = 1;
COMMIT;
UPDATE person
SET balance = 15000 WHERE ID = 4;

ROLLBACK ;

---------------- ACID PROPERTIES ----------- ( it is set of properties that ensures


reliable databse transactions ) yeh apne aap implemented h transaction me

1) Atomicity - all or none ( ya toh pure change shonge nahi toh koi nhi hoga )
2) Consistency- transaction only allowed if it must follow certain rules , or
constraint which ensures data integrity
3) Isolation- concurrent transaction do not interfere with each other / sab ek
doosre se isolate honge
4) Durability - agar commit ho gya toh permanent change store ho jayega
String Data Types ---
1) Char - fixed length string

2) Varchar- upper limit specified variable length

3) Text << Mediumtext <<< Longtext

Wildcards --- for pattern matching ( % and _ )

--- Select name from movies like '_____' ---- Exactly 5 characterer
----Select name from movies where name like '%man%' --- kahi bhi man ho

%man --- man pr khatam ho rhi ho

man%---- man se shuru ho

String Functions -----

-Upper(name)
-Lower(name)
-Concat(name,' ',director,' ',star)
-Substr(name,1,5) -- 1 se start krke 5 character dikha de (1 - position h 5- number
of character h)
-Replace (name, man, women) ---- name ke saare men ko women se replace krdo
-Reverse(name)
-char_length(name) vs length(name)
-Insert('hello world' ,7,3,'cccc') ------ hello world me 7th position se 3
character hata ke cccc replace krdo
-Left(name,3) left se 3 character dede
-Repeat(name,3) --- 3 baar name repeat krde
-Trim(name) --- space hata de
-Ltrim/ Rtrim
-Substring_index---- work as split function of python
substring_index('www.campusX.com','.',1) pehle . tk ka character de dega

<<<<<<<<<<<<<<<<<<<<<<<< CASE STUDY >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

1) Create table laptops_backup like laptops ----------- Make backup

2) Insert into laptop_backup ---------- Copy the data


Select * from laptops

3) Select * from information_schema.TABLES


where table_schema='sql_cx_live' --------------same like
df.info
and table_name='laptops'

4) Alter table laptops drop column 'Column_name'

5) Delete from laptops where 'index' in (Select 'index' from laptops where
column_name is null ) -------------- Delete null values

6) Select name , gender, age,count(*) from laptops


group by name,gender,age
----------------------- for getting the duplicates value
having count > 1

7) Select * from duplicates:


delete from duplicates
where id not in ( select min(id) from zomato ----------------------- Removing
the duplicates
group by name,gender ,name)

8) Select distinct ( ) from laptop --------------- to see the


categorical colum / cleaning categoriacal column

9) Update laptops l1
Set Ram = (select replace(ram,'GB','') from laptops l2 where
l2.index=l1.index)

10) Alter table laptops modify column ram integer

11) Update laptops l1


Set price = ( select round( price) from laptops l2 where l2.iden=l1.index)
-------------- to update price column

12) select ops ,


case
when ops like '%mac%' then 'macos'
when ops like '%window%' then 'macos'
else 'other'
end as 'os_brand'
from laptops

13) Update laptops


Set ops = case
when ops like '%mac%' then 'macos'
when ops like '%window%' then 'macos'
else 'other'
end as 'os_brand'
from laptops

14)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy