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

sql-notes-queries-1 (1)

The document provides a comprehensive list of MySQL commands for database and table management, including creating, altering, and dropping databases and tables. It also covers SQL constraints, data manipulation commands, aggregate functions, and methods for transferring data from CSV files. Additionally, it outlines steps for backing up a database using mysqldump and restoring it in a new database.

Uploaded by

nirangini.s
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)
11 views

sql-notes-queries-1 (1)

The document provides a comprehensive list of MySQL commands for database and table management, including creating, altering, and dropping databases and tables. It also covers SQL constraints, data manipulation commands, aggregate functions, and methods for transferring data from CSV files. Additionally, it outlines steps for backing up a database using mysqldump and restoring it in a new database.

Uploaded by

nirangini.s
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

MYSQL COMMANDS

1) CREATE DATABASE IF NOT EXISTS VM;


2) CREATE DATABASE SCHOOL;
3) SHOW DATABASES;
4) USE [DATA BASE NAME];
USE SCHOOL;
TO DISPLAY THE CURRENT DATABASE BEING USED
5) SELECT DATABASE() FROM DUAL; OR SELECT DATABASE();
6) DROP DATABASE [DATABASE NAME];
7) SHOW TABLES;
8) CREATE TABLE TableName (Column1 Datatype1, Column2, Datatype2,…,ColumnN
DatatypeN);
9) CREATE TABLE Emp (ID INT PRIMARY KEY AUTO_INCREMENT, Name
VARCHAR(255), City CHAR(255), DOB DATE NOT NULL);

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified

10) CREATE TABLE A (ID INT UNIQUE, NAME CHAR(20));


11) CREATE TABLE A (ID INT CHECK (ID >100), NAME CHAR(20) ); #CHECK ()
COMPULSORY
12) DESCRIBE TABLE NAME; (OR) DESC TABLE_NAME;

13) INSERT INTO EMP VALUES(101, 'RAMA', 'CHENNAI', '1990-12-25');


14) INSERT INTO EMP VALUES(102, 'UMA', 'DELHI', '1995-2-5'), (103,'BALA', 'BOMBAY',
'2000-1-20'), (105, 'KALA','CHENNAI', '2010-10-15');
15) INSERT INTO EMP (NAME, DOB) VALUES('ARVIND', '2010-10-12'), ('MALA','2005-5-15');

16) ALTER TABLE TableName ADD ColumnName Data_Type;


ALTER TABLE TableName DROP ColumnName;
ALTER TABLE TableName MODIFY COLUMNColumn / CHANGE NameData_Type;

17) ALTER TABLE Emp ADD phone INT NOT NULL;


18) ALTER TABLE Emp ADD phone INT NOT NULL, ADD comm float;
19) ALTER TABLE Emp DROP phone;
20) ALTER TABLE Emp DROP phone, drop comm;

21) ALTER TABLE Emp change phone phone_no int;


22) ALTER TABLE Emp change phone phone_no int , change comm sal float;
23) ALTER TABLE TableName_A RENAME TO TableName_B;
24) ALTER TABLE Emp RENAME TO Employee;
25) ALTER TABLE EMP MODIFY AGE INT NOT NULL;
26) ALTER TABLE EMP MODIFY AGE INT NOT NULL, MODIFY SEX CHAR(1) NOT NULL;

To drop Null in an attribute

27) ALTER TABLE EMP MODIFY AGE INT NULL;


28) ALTER TABLE A ADD UNIQUE(NAME); # CHANGE NAME AS UNIQUE
ALTER TABLE A DROP INDEX ID; # REMOVES THE UNIQUE ID
29) DROP TABLE TableName;
30) DROP Table Emp;

31) SELECT * FROM table_name;


32) SELECT column1, column2,…. FROM table_name;
33) SELECT id, name, phone FROM emp WHERE id = 101;
34) SELECT id, name, phone FROM emp WHERE comm BETWEEN 5000 AND 25000;
35) SELECT * FROM emp WHERE id IN (1001,1004,1008,1012);

SELECT column_name AS alias_name FROM table_name;

36) SELECT ID AS "ROLL", NAME AS "ST_NAME" FROM EMP;


37) SELECT NAME , AGE + 5 AS "NEW AGE " FROM EMP;
38) SELECT NAME , AGE + 5 "NEW AGE " FROM EMP;
39) SELECT ID AS EMP_ID, NAME AS EMP_NAME , CITY, DOB FROM EMP;
40) SELECT DISTINCT NAME FROM TABLE;
41) SELECT ALL SEX, NAME FROM EMP;

LIKE: This operator is used with the WHERE clause to search for a specified pattern in a column
containing the string.
 ‘A%’ – string starts with A
 ‘&A’ – ends with A
 ‘%A%’ – A will be in between the string
 ‘_A%’ – Here the 2nd letter will be A
 ‘%A_’ – The 2nd from the last letter will be A

42) SELECT name FROM emp WHERE name LIKE 'A%';


43) SELECT * FROM emp ORDER BY salary DESC;

44) SELECT * FROM EMP ORDER BY SEX, AGE DESC;

LIMIT: This is used to specify the number of records we want after executing the query. If we want
the top 5 students of a class, then after sorting the results, we can use this LIMIT by specifying 5. So
that it will only fetch the top 5 records.

45) SELECT first_name FROM student ORDER BY marks desc LIMIT 5;

47)We can use having like where clause with aggregate fns. ( We can not use aggregate fns in where
clause) But the conditional fields should have been referred using select clause.
a) select age from emp having max(age);
b) select age from emp having max(age) and age >= 25 and age <=30;
c) select age from emp having max(age) and name like 'r%'; # Error
d) select age from emp having max(age) and id >= 101 and id <= 110; # Error
e) select age, id from emp having max(age) and id >= 101 and id <= 110;
f) select age, id, name from emp having max(age) and id >= 101 and id <= 110 and name like 'R%';
g) select age, id, name from emp having max(age) and id >= 101 and id <= 110 and name like 'K%';
h) Select age, id, name, dob from emp having max(age) and id >= 101 and id <= 110 and name like
'R%';

Combine column values using CONCAT in select


We can use CONCAT function in select commands to combine values from multiple columns and
display it. The following example combines name and date of birth (dob) field (for display only) as
shown below.

48)SELECT ID , CONCAT(name, 'WHOSE DOB ON ', dob) FROM EMP;

49) SELECT ID , CONCAT(name, ' WHOSE DOB ON ', dob) AS 'INFORMATION' FROM EMP;

50) Aggregate Functions


Below is the different aggregate function:
1. SUM: Calculates the sum of values.
SELECT SUM(salary) FROM employee;
2. AVG: Calculates the average set of values Non Null values
SELECT AVG(salary) FROM employee;
3. MIN: Gets the minimum value in a set of values.
SELECT MIN(salary) FROM employee;
4. MAX: Gets the maximum value in a set of values.
SELECT MAX(salary) FROM employee;
5. COUNT(*) : Returns the numbers of rows / tuples in the table
SELECT COUNT(*) FROM EMPLOYEE;
6. COUNT(attribute) : Returns the number of non Null entries of the given attribute
SELECT COUNT(age ) FROM EMPLOYEE;
7. COUNT(DISTINCT attribute) : Returns the number of different non Null entries of the given
attribute
SELECT COUNT (DISTINCT age ) FROM EMPLOYEE;
8. STD : Returns the population standard variance
SELECT STD(age) FROM EMP;
9. VARIANCE() Return the population standard variance
SELECT VARIANCE (age) FROM EMP;
Update

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

51) UPDATE EMPLOYEE SET DOB = '2005-12-12' WHERE CITY IS NULL;


52) UPDATE EMPLOYEE SET ID = 108 , DOB = '2005-12-12' WHERE CITY IS NULL;
53)UPDATE EMPLOYEE SET DOB = '2005-12-12' , CITY = 'CHENNAI' WHERE NAME LIKE
'%A' AND CITY IS NULL;

Creating a new table from an already existing table using CREATE TABLE.
The new table gets the same column definitions. All columns or specific columns can be selected.If
you create a new table using an existing table, the new table will be filled with the existing values
from the old table.

CREATE TABLE new_table_name AS


SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

54) CREATE TABLE TEST AS SELECT ID, NAME, CITY FROM EMPLOYEE ;

55) CREATE TABLE TEST(ROLL INT, NAME CHAR(200), PLACE CHAR(100)) AS


SELECT ID, NAME, CITY FROM EMPLOYEE ;

56) CREATE TABLE TEST(ROLL INT, NAME CHAR(200), PLACE CHAR(100)) AS


SELECT ID, NAME, CITY FROM EMPLOYEE ORDER BY ID LIMIT 5;

This SELECT command can also be used with the INSERT command which is used for adding
records to the existing table.

The INSERT INTO SELECT statement copies data from one table and inserts it into
another table.

The INSERT INTO SELECT statement requires that the data types in source and target
tables matches.

INSERT INTO table2 SELECT * FROM table1 WHERE condition;

INSERT INTO table2 (column1, column2, column3, ...)


SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

Table 2 should have been already created with the respective attributes

CREATE TABLE Employee (ID INT, Name VARCHAR(255),City CHAR(200), DOB DATE);

57) INSERT INTO EMPLOYEE SELECT * FROM EMP;


58) INSERT INTO EMPLOYEE SELECT * FROM EMP WHERE ID > 104;
59) INSERT INTO EMPLOYEE (ID,NAME) SELECT ID, NAME FROM EMP ;

60) String Functions

SUBSTRING: Used to pick a specific character from a string by specifying the position.
1) SELECT SUBSTRING(name,1,5) FROM emp;
(it will fetch character from 1st to 5th position of attribute nameg)
2) INSTR: This returns a position of a string in another string.
SELECT INSTR(‘independence’, ‘pen’);
(it will find the position of ‘pen’ in the word ‘independence’)
SELECT INSTR(NAME,'a') FROM EMP; # Not case sensitive
3)LCASE(string): Returns the lower case of the string. same as Lower(string)

SELECT LCASE('SCHOOL'); (OR) SELECT LOWER('SCHOOL');


SELECT LCASE(NAME ) FROM EMP; (OR) SELECT LOWER(NAME ) FROM EMP;

4)UCASE(string): Returns the Uppercase of the string. same as Upper(string)

SELECT UCASE('SCHOOL'); (OR) SELECT UPPER(‘SCHOOL');


SELECT UCASE(NAME ) FROM EMP; (OR) SELECT UPPER(NAME ) FROM EMP;

Group by - having
61) SELECT SUM(SALARY) FROM EMP GROUP BY SEX;
62) SELECT DEPT, COUNT(*) FROM EMP GROUP BY DEPT HAVING SUM(SALARY) >
20000;
63) SELECT DEPT, COUNT(*) FROM EMP WHERE SEX = 'F' GROUP BY DEPT HAVING
SUM(SALARY) > 20000;

Join
64) SELECT * FROM EMP1, EMP2;
65) SELECT EMP1.ID, EMP1.NAME, EMP1.AGE, EMP1.
66) SELECT EMP1.ID, EMP1.NAME, EMP1.AGE, EMP1.SALARY, EMP2.ID, EMP2.COMM
FROM EMP1, EMP2;
67) SELECT * FROM EMP1, EMP2 WHERE EMP1.ID = EMP2.ID;
68) SELECT EMP1.ID, NAME, AGE, SALARY, EMP2.ID, COMM FROM EMP1, EMP2;
69) SELECT EMP1.*, EMP2.*, COMM FROM EMP1, EMP2;
71) SELECT EMP1.ID, NAME, COMM FROM EMP1 , EMP2 WHERE EMP1.ID = EMP2.ID;
72) SELECT EMP1.ID, NAME, COMM FROM EMP1 , EMP2 WHERE EMP1.ID = EMP2.ID
AND AGE >= 25;
73) SELECT A.*, B.* FROM EMP1 A, EMP2 B WHERE A.ID = B.ID;
74) SELECT EMP1.ID, NAME, COMM FROM EMP1 , EMP2 WHERE EMP1.ID < > EMP2.ID;
75) SELECT EMP1.ID, NAME, COMM FROM EMP1 , EMP2 WHERE EMP1.ID != EMP2.ID;

76) SELECT A.*, B.* FROM EMP A , EMP B;

Select from Dual – Virtual Table


dual is a virtual table. This really doesn’t exist. But, we can use this table to perform some non-table
activities.

SELECT 2+3 FROM DUAL; (OR) SELECT 2+3;

79) Date and Time Functions


CURDATE() : This function returns the current date
CURTIME() : This function returns the current time
select Year('2010-12-15');
select month('2010-12-15');
select day('2010-12-15');
SELECT HOUR('09:40:45.2300');
SELECT minute('09:40:45.2300');
SELECT second('09:40:45.2300');
SELECT microsecond('09:40:45.2300');

Transferring Data from a CSV File to MYSQL Table.


Syntax :
LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS
TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Do the following steps :
Step 1 : Create a csv file in notepad and save it 'e:/harifa/sample.csv'. Example
ID,Name, Phone, Address
101,Rama,9178561200, First street Adyar
105,Kala,910005678, Second street Besant nagar
Step 2 : Create a table cs in mysql
create table cs(id char(20), name varchar(200), phone varchar(100),address varchar(300));
Step 3 : Use the command in mysql
LOAD DATA INFILE 'e:/harifa/sample.csv' INTO TABLE cs FIELDS TERMINATED BY ',' Lines
Terminated By '\n' IGNORE 1 ROWS ;

Steps to take a backup of a database.


Step1 : Set the current directory to the full path of sql working directory using command prompt as
shown below
C:\>cd C:\Program Files\MySQL\MySQL Server 5.5\bin\
Step 2 : Use the command mysqldump with the following syntax
In the following command root is the user name and hb is the database we are going for a back up
The backup is going to be done in the E drive where \harifa\mysql\ are the folders already
existing.
new_hb.sql is the new name given
Once the command is given it prompts for the mysql password.
C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqldump -u root -p hb >
"e:\harifa\mysql\new_hb.sql"
Enter password: ****
Step 3 : Switch over to mysql. ie, Login in your mysql and enter the password.
Step 4 : Create a new database new_db
mysql> create database new_db;
Query OK, 1 row affected (0.09 sec)
Step 5 : Change to the new database new_db
mysql> use new_db;
Database changed
Step 6 : Now use the command source to extract the tables in the new database
mysql> source e:\harifa\mysql\new_hb.sql
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
…………
Now the extraction is done so use the command show databases; to see the backup
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| hb |
| new_db |
| performance_schema |
| vm |
+--------------------+

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