If we want to retrieve the results in descending order of AGE, we can use ORDER BY
AGE DESC.
SELECT * FROM STUDENT ORDER BY AGE;
SELECT * FROM STUDENT
WHERE ROLL_NO>2;
SELECT ROLL_NO, NAME FROM STUDENT
WHERE ROLL_NO>2;
COUNT: Count function is used to count the number of rows in a relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;
SUM: SUM function is used to add the values of an attribute in a relation. e.g;
SELECT SUM(AGE) FROM STUDENT;
Average: AVG
MAX, MIN
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
-----------------------------------------------------------------------------------
------------
DDL:
CREATE : to create objects in database
ALTER : alters the structure of database
DROP : delete objects from database
RENAME : rename an objects
create table department
(dept_name char(20),
building char(15),
budget numeric(12,2));
ALTER TABLE table_name
DROP column_name datatype;
DROP TABLE table_name;
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
---------------------------------------------------------
DML:
SELECT: retrieve data from the database
INSERT: insert data into a table
UPDATE: update existing data within a table
DELETE: deletes all records from a table, space for the records remain
select instructor.name
from instructor
where instructor.dept_name = 'History';
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
DELETE TABLE Customers;
-----------------------------------------------------------------------------------
----
TCL:Transaction control language-
COMMIT: Commit command is used to permanently save any transaction
into the database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction so
that you can rollback to that point whenever necessary.
DCL:data control language-
GRANT: allow specified users to perform specified tasks.
REVOKE: cancel previously granted or denied permissions.
-----------------------------------------------------------------------------------
----
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
ROLLBACK TO SP1;
//goes back to sp1
RELEASE SAVEPOINT SAVEPOINT_NAME
//savepoint released
----------------------------------------------------------
Views:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
ORDER BY NAME;
SELECT * FROM DetailsView;
--------------------------------------------------------------
NOT NULL: This constraint tells that we cannot store a null value in a column. That
is, if a column is specified as NOT NULL then we will not be able to store null in
this particular column any more.
UNIQUE: This constraint when specified with a column, tells that all the values in
the column must be unique. That is, the values in any row of a column must not be
repeated.
PRIMARY KEY: A primary key is a field which can uniquely identify each row in a
table. And this constraint is used to specify a field in a table as primary key.
FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a
another table. And this constraint is used to specify a field as Foreign key.
CHECK: This constraint helps to validate the values of a column to meet a
particular condition. That is, it helps to ensure that the value stored in a column
meets a specific condition.
DEFAULT: This constraint specifies a default value for the column when no value is
specified by the user.
CREATE TABLE Orders
(
O_ID int NOT NULL UNIQUE,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);
-----------------------------------------------------------------------------------
------------
Grant Privileges To a Role
GRANT create table, create view
TO manager;
Grant succeeded.
Grant a Role To Users
GRANT manager TO SAM, STARK;
Grant succeeded.
Revoke Privilege from a Role
REVOKE create table FROM manager;
Drop a Role
DROP ROLE manager;
-----------------------------------------------------------------------------------
--------
Sequence:
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;
CREATE TABLE students
(
ID number(10),
NAME char(20)
);
INSERT into students VALUES
(sequence_1.nextval,'Shubham');
INSERT into students VALUES
(sequence_1.nextval,'Aman');
-----------------------------------------------------------------------------------
-----------
NOT: not select
SELECT * FROM Customers
WHERE NOT Country = 'Spain';
SELECT * FROM Customers
WHERE CustomerID NOT BETWEEN 10 AND 60;
Select customers that does not start with the letter 'A':
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'A%';
ends with a: '%a'
Select customers that are not from Paris or London:
SELECT * FROM Customers
WHERE City NOT IN ('Paris', 'London');
Select customers with a CustomerId not greater than 50:
SELECT * FROM Customers
WHERE NOT CustomerID > 50;
------------------------------------------------------------------
Whenever you see unique in a question immediately think of using 'distinct'.
COUNT(distinct r_no)
We usually use 'group by' with an aggregate function like :COUNT, SUM, AVG, MAX or
MIN etc..
matlab group by use karne se saare rows with same values ek row ban jayege. this
one row shows some aggregate value like sum saare price wale column ka jiska value
usa tha(group by country kia to)
https://www.youtube.com/watch?
v=f2XRInRi9Gs&list=PLKVxK2jv1oA9Ow28rg__JaBWjJQtoPyu6&index=31
check 8:45
ek aur cheez
group by me jo lika hai uske sath select wale me sirf vo wala row value aa sakta
hai with some aggregate
eg. select ename, deptno, count(empno) from emp group by ename,deptno
isme ename select me dala to group by me b dalna he padega
-----------------------------------------------------------------------------------
-------
substring:
select rows which start and end with vowels
select ename from emp where substr(ename,1(first letter se start),1(length kitna
chaiye substring me)) in ('a','e',i,o,u) and substr(ename,-1,1) IN (a,e,i,'o','u');
-------------------------------------------------------------
find number of a in a sentence
select length('blah blah')-length((replace('blah blah','a','')) from dual;
//replace a with empty and find difference of lenth from orignal string and new
string
no of words in a sentence:
select length('blah blah')-length((replace('blah blah','is',''))/length('is') from
dual;
-------------------------------------------------------
date formatting:
select TO_CHAR(sysdate,'YEAR'(ya fir YYYY ya fir YY depending on format. 'Q' is for
quater, 'MON' is month, 'MM' month ka no, 'DAY''DD')) from dual;
or
select Year(sysdate);
year or month or day etc...
--------------------------------------------------------
not equal to sign: <>
----------------------------------
order by eid desc;
order by eid;(ascending)
--------------------------------
replace null wih zero if present in result table:
select NVL(Sum(fees),0) from abc;
sum of fees display hoga but null ke badle 0
--------------------------------------
aggregate functions me where nahi ayega HAVING ayega
aggregate is sum,max,min,count,avg
having and where are same
eg select.....having max(amount) is not null;
having group by ke baad aata and where group by ke Pehle
eg. select.... where job='manager' group by deptno having count(empno)>2;
-------------------------------------------
select depno, count(*) from emp where job='Manager' group by deptno;
count * will count kitne depno hai as it is grouped by
-----------------------------------------------
has a in name: ename like '%A%'
-----------------------------------
case: treat at as a column heading when using select. you can also use it with
update and set
select ename,
case
when sal<100 then 'hike 200'
when sal<200 then 'hike 400'
else 'no hike'
END AS HIKE(ek column ban jayega hike naam ka jaha hike 200 etc print hoga)
from emp;
update karna hai to:
update emptable set sal=
case..(then sal*1.1, etc instead of printing a msg)..end;
UPDATE salary SET sex =
CASE sex
WHEN 'm' THEN 'f'
ELSE 'm'
END;
another eg:
SELECT x,y,z,
case WHEN (x+y) > z AND (x+z) > y AND (y+z) > x THEN 'Yes' ELSE 'No' end AS
triangle
FROM table1
https://leetcode.com/problems/triangle-judgement/description/
-------------------------------------
primary key cant be null and you cant have multiple primary keys in table.
foreign key is connected to a primary key
foreign key values can repeat, primary key values cant
to delete primary key it should not refer anything in any other table through
foreign keys
-----------------------------------------------------
no of rows you get after join: summation of(no of records of a number in A same
with B*No of records of a number in B same with A)
(dont count null in formula)
Left Join Pehle inner join kardega fir left ke jitney records bache unhe daaldega.
same for right
Out join is left join and right join ke saare values
(out join me agar dono table me null hai to dono ka alag alag ayega)
eg. A:10,10,10,20 B:10,10,30
Inner join: 3*2=6- (10,10) ke 6 pairs
Left Join: 6+1=7- (10,10) ke 6 pairs and ek (20,null)
Right Join: 6+1=7
Full Outer Join: 6+1+1=8
Left Join Pehle inner join kardega fir left ke jitney records bache unhe daaldega.
same for right
https://www.youtube.com/watch?v=zzauQ50n9uM
eg. A:10,10,10,20,40,null B:10,10,10,20,40,null
Inner join: 3*3+1*1+1*1=11
Left Join: 12
Right Join: 12
Outer Join: 14
**remember for join syntax: Shit Fucking Join On What Gandu Hai
Select From Join On Where Group Having
join 3 tables:
emp is connected to library and library is also connected to book. to book and emp
ko connect karna hai to:
select ename, bookname, author from emp e join library l on e.empno=l.empid join
books b on b.bookid=l.bookid where....;
-----------------------------------------
check if null or not: 'col1 is null' or 'col1 is not null'
------------------------------------------------------
alias:
select empno, count(empid) cnt from emp e join lib l on e.empno=l.empid group by
empno order by cnt desc.
yaha par order by count karna tha to count(empid) ke baad usko ek alias de dia cnt
naam ka
--------------------------------------------------------
subquery:(multiple select statements)
select * from emp
where deptno
IN (select deptno from dept where dname='sales' OR dname='research');
q. find employee who have salary higher than manager
select ename,sal from emp e where sal>(select sal from emp m where e.mgr=m.empno);
//use alias
q. second highest salary
select max(sal) from emp where sal<(select max(sal) from emp)
q. third highest:
select max(sal) from emp where sal<(select max(sal) from emp where sal<(select
max(sal) from emp))
q. nth highest salary
select * from (select sal, dense_rank() over (order by sal desc) R from emp) where
R=15 ;
https://www.youtube.com/watch?
v=EQbhKjBmW88&list=PLKVxK2jv1oA9Ow28rg__JaBWjJQtoPyu6&index=44
see from 12:00
What is the difference between rank () and Dense_rank ()? RANK() assigns the same
rank to rows with equal values, leaving gaps. DENSE_RANK() assigns the same rank to
equal values without gaps, resulting in consecutive ranks.
-----------------------------------------------
order of execution: from where group having select order
fwghso faltu wala goo hatao sumo o
-------------------------------------------------
dulicates nikalo:
select abc... from table1 group by abc..(saare columns);
find rows having more than one entry:
select abc... from table1 group by abc..(saare) having count(*)>1;
------------------------------------------------------
char length: q. check is length of content greater than 15
SELECT tweet_id from Tweets WHERE CHAR_LENGTH(content)>15;
------------------------------------------------
There is no natively implemented Outer Join in MySQL.
But we can implement OUTER JOIN in MySQL by taking a LEFT JOIN and RIGHT JOIN
union.
If column names of two tables are identical, we can use the USING clause instead of
the ON clause.
eg.
SELECT T.employee_id
FROM
(SELECT * FROM Employees LEFT JOIN Salaries USING(employee_id)
UNION
SELECT * FROM Employees RIGHT JOIN Salaries USING(employee_id))
AS T
WHERE T.salary IS NULL OR T.name IS NULL
ORDER BY employee_id;
---------------------------------------------------------------
use of not in:
SELECT employee_id FROM Employees WHERE employee_id NOT IN (SELECT employee_id FROM
Salaries)
UNION
SELECT employee_id FROM Salaries WHERE employee_id NOT IN (SELECT employee_id FROM
Employees)
ORDER BY 1 ASC