0 ratings0% found this document useful (0 votes) 46 views26 pagesMysql Syntax
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Y Dela bare *
DBMS Creates
> Pelehonal dababares
Pete stored om tebles
My soe
Oracle
pastgve $eL
ME SOL Serve”
Sev wed te werk on relahonal dbs,
82 ~ Sdouetwred Cuery Lamsuose
eused tp nberact
eCRUD opevahons ;
SEQUEL
Crected by 184
Pelabese shuetwre
bB
TableD
[ae]
cath relahonal catcher. E
Create
Read
Upelate
Dekte
» gtoachwred Eng hah Query
tallechon 9 veleted date wm an eecesible Foronal i
amd.
mamtang database -
:
> Woen-velahonal dalebases (ae34v)
Dele not steed oy debies
Mongo DB
‘a
E
F
Coresrammens Congres)
Lamguase
Table @)(toy)
Creatas ony fast clatebese :
CeeaTe paregase dbname } Creahny
peop DATABASE db-neme > —— Pelebng
use db-name; ; am use
CeeaTe TABLE +tablename C : creabmd thie
Column name! datatype Constraint :
colvrnn—name 2 datatype Cons brawn
ae '
£5: ceeate DaAtmpase College ;
Use College +
CREATE TABLE Student C (td | Nawme
(dA INT peimary FEY, PT:
Name VARCHAR (50),
age INT Nor Nuce
: :
To cveale ¢ ro table from an emshns thle
CREATE TABLE table name
SELECT A, Cole + (Select vequired column )
columns
Fpom exabns- bls ome 7—
insert INTO table name mut value unto table
VALUES ( value, Value ee)
Secect * FROM feble-name Duplo teble - View ell tf
View ell tl vans
& inkkeer Wr shdent Vacues C1, Tasos be
INSET INTO Choe lt “Gohan”, 25)
fohan", 25) 2
Vautes (2,
Sevect * FROM Stidont ;
| Inseet NTO tnble-name (col 1, cole)
dake by ‘
| eee cere ee, 12
| belle me new teble ons
: : FROM exubng tbe name
ae date bypes Where Pe:
Delmer tte Cype 2 waluen thal com be Stored im 2 column,
°aiAar fam hove chevecters 0 fixed lenge,
eVARCURR com Store characters mph gwen length
cne 3 the’ Puxed Length io yeserved im memory
and con “PE wdedotveniy. ik Lege
crmoed by CHAR
viecHAR The vemaming Space
Storing Othey date.
peo be
© INT
e TINY INT
© BIGINT : to oY
bt values, x |
Dieyrame con, store Xb Wanetly. N7
BiIT0) port
girl) > 00,01, 10,"9
FLOAT = Peomal rombey (prearsin to 23 4gchs )
,
sPouste Penmel mmbey Cpreeniig 24 te 53 dads© Booceanl Ow |
© DATE
© Yene
YYYY— mM ~ DD
Yeay ™ A-dagik format
° Sugned and Unsigned
TINIAN UNtiaNeD (oto 255)
TANT (128 to 124)
Type 9 SQL commands :
Dp
3. DML
4, Ber
Se ee
Dale Debriten Language
creste, alter, rename, Iruncate, drep.
~ Pale Query Language
Select
~ Pele Manipulaben Lamguane
antert, Update , Delete
stnpeutean Conkre) Lemngentye
Petiaiiege lor cern ih grt
~ Dale Conbrel Lampurge
Cua Revoee permisin fo wer. *— .
CREATE DATABASE
eee
IF Nor Exists
db-name; ele evnev anf
tons Y Ub abd,
db-name + ae 7
SHOW DATABASES :
peop DATABASE IF Exists
SHOW TABLES :
&$: CREATE DATABASE JF Nor exists colleges
OROP PATABASE Ie Exists department 2
DROP TABLE teble- name
:
&: DRop TABLE Shdent »
CREATE TABLE Student (
Fallno INT *PeamAey bey
name VAR cHAe(sd)
»
Select « Feom Shdént > *
WseeT INTO Tablename
Coolwmnt > column 3°)
VALUES
order to onion
Ceh—vi_, cl2 -vr) xt hpte fron
Ceolt-Ve, Cole Ve) ; eres
WMsegt INTO Shdent eae
Cellno , none) Pall-no | name
VaAtues
(34,% Kiran’),
(37, * phon),
(35, * Loshinn >Foren bey & fovnanry, key a
frmery key:
FF column / Sek a wlumns on @ table Ahab. oniquely ‘derhly
tan you. There only one promary boy and Uk thauld
wot be nul (a cmigue id )
Treg bey:
A colemn [set 4 columns om 2 table “he
Primary ey a smoher cable. There om be rks braigg |
keys. Con awe clupheale ov NULL valves
b velers te the
Constr aunts see
Used to speuyy rales fr date in 2 teble ,
e Nor Nate columns cannot have © nud uabies 4
« UNidue All values m colemn are difkerent
hess PRIMARE REY makes a vclemn neque & riot rll
L yelue pk = Not Nut toni @Qve
1h cle same orb 4% Gwen rlbipla hemes 'm 4 Cimgus. cohen,
only me vou willl be efpeckd-qeente TABLE tomp! C nine groans |
w INT,
name VARCHAR (So),
age iNT Mer Nue
peimary kEY (id name) Cambunahen 4 columns of name acts
F oer aeey
eFOREION key Prevent achens that would destroy Tonle bebveon
Tables. (foregn begs Pons uorious berbled)
Create TABLE tempe (
Gust id NT,
FOREIGN Key Cuust-id) references Customerlid )
perAautt Sed the deluelt value Q < Column
Salary wit peFAULT 25000
ceente TABLE emp
aq iNT “
Blane N renal Te. 25000
Dy
Weert NTO emp Cid)
VALUES
Co) ;
CHECK 1% Comm Wmnat values allowed im ¢ folumn
CREATE TABLE Cty C
iq INT PRIMARY kEY
Gly VARCHARC 50), comtyeint name
2 IN,
CONstRMAIT “age check’ CHECK Cage>oi8 AND Gily= “Pelhi')
=CREATE TABLE neileb(
age WNT CHECK Cage >=\¢)
ye
> CREATE DATABASE College »
> Use college:
tos |cheten| 65
> CREATE tABLE Student ( sent
onl mark! jade
aellno INT PRIMARY KEY, aii a se a
name Vpactine (80), creda | 9 14 ™
2
we [Phot] 96
marks IAlt Not AluLL, (oe bemandeel fa
grade Varcuar (1),
diky vrectar (20),
I
> INseetT wito Stident
Crell-ne, nave, marts, Grade, ty )
NALUES
JA> ern
(et, “anil”, 78, °C", Caleta)
(102, “bhumika” 93, 4"
Mumbai”)
(ict, “ Chetem", 65,489 ,
Mambai”) e
(04, “Alm”, 16, %A", ° Delle”) sarin
(105, *emarnuel” Jp, 4e") “Delhi” )y 1A
(106, fava’, #2,° BS Dell") 5
peelect | 8 UsAl to) Slates pour Rasaay,
tinter » SELECT colt, cole
FROM toble race ». selectall :
To
SELECT © From 4tuble-name ;
> SELECT Name, marks
FROM Student ;
erect Distinct aby
Te selec each acouence % ev
age ahies ( #Shortists all daienke
cakeoua tn the table stuelenk .)
Mura bas
Delb:
secect chy
Fem shdent;
Wheve clause | . Ta debve some hae
Ryrtan > SELECT edt, cole
FRom = te ble_-name
WitERe Condhond 5
S€LecT +
FROM Strident
wees “marks > 80 5
SELECT &
Rom Shadent
WHEE tty =" Mumbar"s
SELECT © *
room Student
Were mah >so AND cy = Mumba."Q@revators im Where
Arthomehe eperabrss $/-/¥///%
* Cempanisen cperaters : af te/>of>z/e/4-
# Aogical aperabeys 3 AND on NaT. Int BETWEEN
ace ANY LIKE
6 Blue cpembors : & (bbewe AND) — | (bl-tve Oe)
e AND to checle bath tendihans 1) be tme
SevectT #*
Feo shdent .
witeze Morks >Go And tly > Delhi” >
7& Matches amy yale om dre bot
S€cectT *
FROM Student
WHERE City IN C!delbs", ‘Mumbac") 2
* BetwWeenl selects for 2 grien venge
Secect * .
we
FeoM Student dnl
witeee meres Between 86 AnD qo;
¢ On te check fr are 9 dle tombbont & be dome
Fon aden ow
Wheee oo mevks > 40 OR Uby = Delhi’: ah
vir an AC
le wat x ‘reo shark Like gna ode” ott ofBk. Orage Be gm sondihin + vote ee
select *
Feo Student
were Coley Not th C*Delhi”, ‘Mumban') s
Limit cia Sets am wppeat liek on So eal x
temples Cour) © be velwned.
tywrex » Secect Colr, colZ call
FROM = table-name
Limit rwmber z
4
Sevect *
Feom Student —? Only 3 aows is rehomed atmost
Lol
Limit 32
SEcecT +
ae —9 Only & rows under. the Specifed
witeee marks > 90 2 ea Seedy )
UPA T gee 7 et
To sovk im ascondong (ASC) o7 |
deacendiny Cpese) order
SevecT colt, cole
FROM table-vome /
ORDER BY tol-name(s) ASC?SELECT ®
from student ) Detorls y 3 &p
co obtained
Stovees
Orper By wavks bese
Limit 3+
Aggregate Pune hens Perborm # talulahen om « seg
Values and vehan 2 songle Value
COUNT ()
MAXLD
MIN ©
Sum C)
AVG C)
Serect max (marks )
rami chedene (Get maxeurnum cee)
SELECT RYG Cmarv ks)
ee ce: Chet average g marks )
Grrowp by clause Grovp vous that have th Same
values unto Sumammaey voles -
It Collects dake Fram amathple. records
amd qronp dis result by one or move colamn
Used along cath fore Aggregate feinchso
SErectT ob, covet (ntome ) F
FROM strdenk > ‘Comb mumber 9 Shadews
Geour oy Cty 7 oagevect Cty, avg (mors 2
FROM Student prdbtecamns 444 rssls 4
Gpour BY ati Chednk on cau “oy
ORDER BY avg(marks) /
SELECT grade, coum (red) vo) ’
Fei shadow ne Number % shod eon! | a
| : h
| Grove BY grade une e
| dev a
| oppee BY qvade J “8 ee
k
| Having clause | Sinmlay to WHERE ; apphes Some
condikion on vers.
Uhed when we cam Arpad condihan after rergi
wal“
D, SeLect Pete (ere) , oy ‘ bl
a
FROM Student - roel” 9) shed =
ORouP BY ont Paes here wana
Hayate, max (marks) >40,; vy above 4
Orne order
GELECT Columnls)
FROM = table-name
Were tondshon
Geour &Y 2
ORDER BY columns) AscyTable related queries
Uppate
UPDATE +tuble-name
set Colt -vall, col2 = vale
WHERE Cendikon :
€5: uppate student
set grade 2°0 *
wheee grade = "A"
ZI
Safe rode x
SET S@L_-SAFE- UPDATES =
uporte Student
SET grade= "8"
Ss:
Where marks BETWEE!
UppaTe Student
sét Marks= 8
weeee toll-no = 1052
uppaTte Strdent
SET moves = marks +15
- +o. update exulng rout.
ye gale 9 chenged © 0
Cdeacbiate sage mode)
1s achvale
Oo;
> & arabe bonndy bed
N £0 AND 104
i a shaded
9 Caen yen ee
re Brureasint the Stove 4
Shrdem ey |— bi yiee ua a ee oe
DALETE 1 to delele caus hong vous
PEreTe FROM table name
WHEeee condshon +
€5: DELETE From Shndent
WHERE mayk 2 337
7h Delebng amextr delnls 9
Shoelombs cath necks 292,
reece | child ee
> Create THBLE dept C Prevent table's precy keg
iq nr Peimary bey at cs Yorega key y
| name veecuar (50) chile treble
s
7 cREATE TABLE teacher
ed Wr peimary FEY,
name VARCHAR (SO) ,
dept-id alt,
ForeIGn key Cdept-ed) REFERENes eept cd)”
PN UPPATE CASCADE,
ON DELETE cAscHDE
%*
Concadving hy Fe
On Delete cascade
When we create 2 FE wth dha ophen, A deletes tte "ebro
ous bo the Chile table cshon the referenced wuss ig
deleted wm the parent table eihich has 2 porormny key
On updale Carcade
When we crake Fe wing updale exseade , the reboroncing,
Toot ame updated & Ake chide table cshom the relerenced
vou S upelated o dhe parent ble cihich has 4 pomany
Eh: CREATE TABLE Shedenk C
@ INT Pemapy rey,
Courseid INT,
PoRe(onAl ker ( Covase-te) REFERENCES Course (ed)
ON peLeTe CASCADE,
ON UPDATE CASCADE
Izso
ALTER be change the schema
ADD column :
iter TABLE tebletname,
App coLumn Column-name, dabatype tensbraink 2
£3: Arter Trace student ALTER TABLE Shuclent
Ap column ae iT + nop COLMA age
alt Alot Aluce DEFAULT IF
DROP Column:
ALTER TABLE aD eitornes
Dror COLUMN column_-nwome 3
&. ALTER TRBLE Student
DeoPp COLUMN age +
Rename tnble:
ALTER TABLE toble-rame,
RENAME TO new—table names
£5. ALTER TABLE Strdent
Rename To Stu?
CHENG Column
ALteR TABLE tuble-name,
CHANGE COLUMN old-name new-name new-daletipe nenttenitrat
£5: puter TABLE Shenk
CHanoe age Ste-age INTaf MoDIFY Column ( mockpy datatype [constraint )
ALTER TMBLE tablename
MODIFY col-name new-daletyne new - comsbrant ;
ds ALTER TRBLE Student
MoviFY age VarcHAR (2) ;
TRUNCATE te delete table's dota
Teunicate TABLE tble-name »
©5\TRUNcrpe TABLE Student 2 "
Chomge column name ‘name’ to ‘Fullname!
ALTEe TABLE Student
CHANGE name full-name vaecnne (60) ;
Delete all the shdents who sSeored marks less dha 0
DELETE FROM Shadent
WHere marks 4 S02
Delole fhe column fev grades
AuTeR TABLE Shdent
peop COLUMN gyredes:— |
Toms m SOL
Jom 2 wed fo combne yous Pom bwe oy move tables
yased on 2 velakd column behseen them
' name] sali
Types cy orm (Yen deagranme)® Jo
eet ee
Arnotigern * Polos vesrdo that Mave wahheny velees om
beth thle.
mie i ees
SELECT Columncs) X
From table A see f eds Py
INNER JOIN tableB
ON table A, Col-nemme = tebleB, col_name }
- 3 ail la :
a Steud | =; Told [name | come
eee)
*ALIAS: Mtemale name s=
Secect « Fea
FROM Shdent AS Ss
INNER JOIN Course AS C
nw
ON Setd = bd,
Left gow
ane
Relurw ell records Prom lot Hible Amd maalcmns dak
Crom agnh kbe
Sytene
secect column (3)
Feom tableA
eect FON able B
ON tableA.cdnm = tableB cl-n™ 4
Regn an, |
Dekarns all revevds Prom agit Feble and methyl veverls
From Beye table -
Syntax:
SELECT Colemnes)
From tblef
RigHt TON ‘bleB :
ON table colonm = fable B. Colones.
dren 2) vedrar where. dhete Be meth m ee
ow right feb: LEFT TOIN UNION RIGHT JOIN
rym dere li
a A ray saery
SELEecT ©
From Stodent As a
Lett Jon Course AS b
dsON @.id = bid
union
becect + FROM 'Shdent AS
RIGHT Jom Gouwe As B
ON aid= Grid ;
Left excluwefem — Righh excluawe gom
SELECT *
Feom tmbleA AS 4%
Riqur goin) He B ASS
ON Achl= b. ol
WHERE ae Col 1S NOLL 2
if SELECT « 7
S prom table as @ g
LEFT JOIN tables 236 3
ON Bitte b.cly |
{rneee bal 16 NULL,
SAF govn
aAn~~y~
l-ne rebaler pom bub the 4able ww dGorned cute hel?
Syn tons Creither inne? rev ouler)
Sevect colwmn (5)
20M table “4 4
JON table 45 b
ON A. tolenm = b. col-00 5setgjorr
oy
b
ae wet 7 “
hte aunt omg
(or roan
SELECT Rename AS managey-nanre , bname
From employee AS A
Join ‘employee AS b
ON acd = b managerid 3
4 4a
Umon
It we wed b combme Te vesull-seh g ta 0” meme
SELECT Stelement. Corey Ong ut vecorde .
To we ibe
w Every SELECT Should have seme ro Ocal
* Columns rust have sumer dake byneo
+ Columm in every SELECT should be vy Same order
Sanden :
SELECT columns)
UNION
From tableA
SELECT column(s) FROM tableB
Orion all
SOL sabgueres
guy *
A Subquery or Cnnerquerg %F & nested | query cathin
arethey SQL query:
z
Awolver tro select Statement . CD
Spine: trade
Sacect Columnls) Y sevect
From fable name Ui) From
WHEZE Col-name operator Oh wHere
Ceubguery D2 G wnimerweent! +
|
-_
fs: am ane
Ge names all shdmbs eho scored move than cing
nants Fond overage
Wi) Kad marks > vege
SELECT nome, marks 7
reom fhadent
amere mocks > (SELECT Avorl marks) FRom Stedont )
Fond dhe names 9 all Shidemls wrt — oven wall rumbes
CY dnd even voll umbeoo
Ci) and the mame 9) Shadembs vith even rallney
SELECT 70llne, name
FROM Shadent
Where rll ao NC
SELECT Pllro
Feom Stedent
WHEere ellro%h 2 > 0)
an oo
Lond the moe marty — Prorn the Shrefe 9° Delhs
Uy Fond shadents a Det ; ‘
Ci Pend Ahecw mae masks>
SELECT Max (marks)
FROM ( Sevect #
From thedout
WHEeE tly = “pei ") AS temp y
mw
seve Anns table for
Delbe thedenks,
Ep. Setect (SELEET MAXC marks) FROM Shodent), name
FROM Stredent ;
Mys@L ews
Boview vo 2 vurbal dele besed on die veault -cek 4
an $4 Statemant .
CREATE VIEW wes! AS SELecT *
mM vests
SELECT roll no, name ee
peom stdents
A view Abuags Shows up te-dale dak. The db emgme
vecveates the view, every hme a use queries tk.y of veabos, mden
CREATE 1Ndex der. name
ON table name ( Colom, colar -- oe
SHow woex | ‘
From tkbleneme 2
© AeANr/ eEVOcE
+ Addung pavmary keg.
ALTER TABLE +4ble-rreme
App primary key C tol-name) 7
Coeor) primaey key Cte chop)
Addung rwthple Pk
x CALTER TABLE +able-name
+
ge ADD CONSTRNAIT cont-name Primary key (col-1 ol);