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

My SQL Revision Tour commands

Sql commands

Uploaded by

gauravvirani3
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)
3 views

My SQL Revision Tour commands

Sql commands

Uploaded by

gauravvirani3
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/ 9

My SQL Revision Tour

1. Sql command to create database:


Create database <db name>;
2. Sql command to view databases:
Show databases;
3. Sql command to open database:
use <db name>;
4. Sql command to view tables present in a table:
Show tables;
5. Sql command to create table:
Create table <table name>(<column name> [ (<size>)],>(<column name> [ (<size>)]..)
Example:- create table cdetail(pname char(20),city char(20),mobile_no long);
6. Sql command to view structure of a table:
Describe/desc <table name>;
Example:- describe cdetails;
7. Sql Command to rename a column name:
Alter table <table name> change <old column name> <new column name> [data
type];
Example:- alter table student change mame mname varchar(20);
8. Sql Command to modify column details:
Alter table <table name> modify < column name> [data type];
Example:- alter table student modify adharno bigint(10) unique not null;
9. Sql Command to Change the order of Column:
Alter table <table name> modify <column name> <datatype> after <column name>;
alter table song modify column sname varchar(30) after rollno;
10.Sql Command to add new column:
Alter table <table name> add < column name> [data type];
Example:- alter table student add dob date;
11.Sql Command to delete column:
Alter table <table name> drop < column name>;
Example:- alter table student drop mname;

12. Sql Command to insert record in a table:-


Insert into <table name> values(<1stcolumn value>,<2nd Col value>…..);
Example:- insert into student values(12001,'Rajdeep Singh','Sandeep
Singh',null,123456789121,'2001-12-23');
Sql Command to insert record in a specific columns:-
insert into student(adharno,roll_no,t_marks) values(146665432456,126,160);
13. Sql Command to apply constraints:
Create table <table name> (<column name> [ (<size>)] <constraint>,>(<column
name> [ (<size>)] <constraint>..)
Create table student( roll int(5) primary key,name varchar(20),adhar bigint(12),email
varchar(20), unique(adhar,email));
14. Sql Command to apply constraints:
Create table <table name> (<column name> [ (<size>)] <constraint>,>(<column name> [
(<size>)] <constraint>.., constraint <constraint name> foregin key(<col name>) references
<table name>(<column name>) on delete cascade on update cascade);
create table subjects(roll int(5),sub1 varchar(20),sub2 varchar(20),
-> constraint fk_st foreign key(roll) references student(roll) on delete cascade on update
cascade);
15. Sql Command to drop table:-
drop table <table name>;
16.Sql Command to update record:
update <table name> set < column name>=<value>…… where <column
name>=<values>;
Example:- update store set quantity=60 where itemno=2005;
17.Sql Command to display specific columns in a table:
Select <1stcolumn name>,<2ndcoumn name> from <table name>;
Example:- selecty itemname,scode from store;
18.Sql Command to delete all records from a table:
Delete from <table name>;
Example:- delete from store;
19.Sql Command to delete specific record from a table:
Delete from <table name> where <condition>;
Example:- delete from store where itemno=2005;
20.Sql Command to remove table from a database:
Drop table <table name>;
Example:- drop table store;
21.Sql Command to apply primary key constraint in to the column of the table:
alter table <table name> add primary key(<column>;
Example:- alter table st add primary key(roll_no);
22.Sql Command to remove primary key constraint from the table:
alter table <table name> drop primary key;
Example:- alter table st drop primary key;
23. Sql Command to add foreign key constraint from the table:
alter table <table name> add constraint <constraint name> foreign key(<Column
name>) references <reference table name>(<column name>);
Example:- alter table sub add constraint fk_roll foreign key(roll_no) references
student(roll_no);
24.Sql Command to drop foreign key constraint from the table:
ALTER TABLE <table name> DROP FOREIGN KEY <foreign key constraint name>;
Example:- ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;
25.Sql Command to remove column from the table:
alter table <table name> drop column <column name>;
Example:- alter table st drop column mname;
26.Order by command in Sql :
1. Select * from <table name> order by <column name> desc/asc
Example:- select * from student order by marks desc;
2. Order by specific values:-
Select * from <table name> order by field(city,”Bemetara”,”raipur”,”Bilaspur”);
27.Sql command to Display Distinct values of a particular Column.
Syntax:- select distinct <column name> from <table name>;
Example:- select distinct city from student;
28.Sql command to use Group by Clause:
Syntax:- select <column name> from <table name> group by <city>;
Example:- select city,count(*) as 'No of students' from student group by city;
29.Sql command to use Group by Clause with condition:
Syntax:- select <column name> from <table name> group by <city> having <column
name>;
Example:- select city,count(*) as 'No of students' from student group by city having
count(*)>1;
30.SQl command to count no of records:
Syntax:- select count(<coumn name>/*) from <table name>;
31. Sql Command to take backup of Database:
Example:-
Go to bin directory of mysql folder location:-
cmd> cd C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin
cmd> mysqldump -u root -p amit>d:\amit.sql
Sql Command to restore Backup of database:---
Syntax:-- mysql –u <database username> -p <name of database> < <location of the back up file>
Example:---- mysql -u root -p amit<d:\amit.sql

32.Aggrigate functions:-
a) Distinct
b) Avg
c) Count()
Example:- select count(*) as "No. of Students",city from student where city="Bilaspur";

d) Max
e) Min
f) Sum
33.Date related function
a) Month()
b) Year()
c) Day()

Format Description
%a Abbreviated weekday name (Sun to Sat)
%b Abbreviated month name (Jan to Dec)
%c Numeric month name (0 to 12)
%D Day of the month as a numeric value, followed by suffix (1st, 2nd, 3rd, ...)
%d Day of the month as a numeric value (01 to 31)
%e Day of the month as a numeric value (0 to 31)
%f Microseconds (000000 to 999999)
%H Hour (00 to 23)
%h Hour (00 to 12)
%I Hour (00 to 12)
%i Minutes (00 to 59)
%j Day of the year (001 to 366)
%k Hour (0 to 23)
%l Hour (1 to 12)
%M Month name in full (January to December)
%m Month name as a numeric value (00 to 12)
%p AM or PM
%r Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S Seconds (00 to 59)
%s Seconds (00 to 59)
%T Time in 24 hour format (hh:mm:ss)
%U Week where Sunday is the first day of the week (00 to 53)
%u Week where Monday is the first day of the week (00 to 53)
%V Week where Sunday is the first day of the week (01 to 53). Used with %X
%v Week where Monday is the first day of the week (01 to 53). Used with %X
%W Weekday name in full (Sunday to Saturday)
%w Day of the week where Sunday=0 and Saturday=6
%X Year for the week where Sunday is the first day of the week. Used with %V
%x Year for the week where Monday is the first day of the week. Used with %V
%Y Year as a numeric, 4-digit value
%y Year as a numeric, 2-digit value
d) DATE_FORMAT(date,format)
Example:- select date_format(dob,”%d-%m-%y”) from sample;
e) DATEDIFF( date1, date2)
Example:- select datediff(current_date,dob) from student;
Result always in the form of No of days.

34.Sql Command to Use String Concatenation Function:-


Synatx:- concat(string1,string2)
Example :- select concat(year(current_date)-year(dob)," years") as 'Age' from student;
select sname,(concat((year(current_date)-year(dob))," Years")) as 'age' from student;
+-----------------+----------+
| sname | age |
+-----------------+----------+
| ramesh | 20 Years |
| ramesh Tiwari | 15 Years |
| Amit Singh | 17 Years |
| Rajdeep Singh | 19 Years |
| Rajdeep Singh | 18 Years |
| Aditya Dewangan | 18 Years |
+-----------------+----------+
35.Nested Sql Command:
Example:- select sname from student where t_marks=(select max(t_marks)
from student);
36. Sql Joins
INNER JOIN Syntax:-

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example:- select student.roll_no,sname,sub1,sub2 from student inner join subject on
student.roll_no=subject.roll_no;

Natural Join (Intersection):

- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.

Syntax:
SELECT *
FROM table1
NATURAL JOIN table2;

Equi Join:
SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of the
associated tables. An equal sign (=) is used as comparison operator in the where clause
to refer equality.
Syntax:
.SELECT column_list FROM table1, table2.... WHERE table1.column_name =
table2.column_name;
Cartesian product:
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records from two
or more joined tables.

Syntax:-
SELECT table1.column1, table2.column2...

FROM table1, table2 [, table3 ]

Union:-
Select * from <table name1> union select * from <table name2>;

My Sql Connection Code in Python:

1. Insert Operation in Python


import pymysql
db=pymysql.connect("localhost","root","123","rameshwar")
cursor=db.cursor()
eid=input("please enter employee id:")
ename=input("please enter employee name:")
query="insert into emp1 values("+eid+",'"+ename+"');"
try:
cursor.execute(query)
db.commit()
cursor.execute("select * from emp1;")
data=cursor.fetchall()
print(data)
except:
print("Query Error")
db.rollback()
db.close()
2. Select operation:
import pymysql
con=pymysql.connect("localhost","root","123","amit")
cursor=con.cursor()
query="select * from drama"
cursor.execute(query)
ds=cursor.fetchmany(3)
print("Student name\t Roll No")
for i in ds:
print(i[0],"\t\t",i[1])
con.close()
3. Search Operation:
#progrma to insert and show inserted record from database
import pymysql
db=pymysql.connect("localhost","root","123","amit")
try:
cursor=db.cursor()
roll=input("Enter Student Roll No:")
name=input("Enter Name:")
#insert into drama value('ashish',128);
query="insert into drama values('"+name+"',"+roll+");"
cursor.execute(query)
query="select * from drama where sname='"+name+"';"
cursor.execute(query)
res=cursor.fetchall()
db.commit()
print(res)
''' print("Roll No\tName")
for i in res:
print(i[1],"\t",i[0])'''
except:
db.rollback()
print("Check the connection or query")
db.close()
4. Update Operation:-
#program to Update record from table
import pymysql
con=pymysql.connect("localhost","root","123","amit")
cursor=con.cursor()
sname=input("Enter Name:")
qur="select * from drama where sname='"+sname+"';"
cursor.execute(qur)
data=cursor.fetchall()
rec=cursor.rowcount
if rec==0:
print("Record not Available")
else:
for i in data:
print("Student Roll No:",i[1],"\t Student Name:",i[0])
roll=input("Please enter the New Roll No.:")
query="update drama set rollno="+roll+" where sname='"+sname+"';"
cursor.execute(query)
con.commit()
print("Record updated")
qur="select * from drama where sname='"+sname+"';"
cursor.execute(qur)
data=cursor.fetchall()
for i in data:
print("Student Roll No:",i[1],"\t Student Name:",i[0])
con.close()
5. Delete Operation:
#program to Delete record from table
import pymysql
con=pymysql.connect("localhost","root","123","amit")
cursor=con.cursor()
sname=input("Enter Name:")
qur="select * from drama where sname='"+sname+"';"
cursor.execute(qur)
data=cursor.fetchall()
rec=cursor.rowcount
if rec==0:
print("Record not Available")
else:
for i in data:
print("Student Roll No:",i[1],"\t Student Name:",i[0])
query="delete from drama where sname='"+sname+"';"
cursor.execute(query)
con.commit()
print("Record Deleted")
con.close()

You might also like