SQL Revision
SQL Revision
AVG(FEES)
15500.00
------------------------------------------------------------
(i) SELECT Department, avg(salary) FROM Teacher GROUP BY
Department;
(ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM Teacher;
(iii) SELECT Name, Salary, T.Department, Place FROM Teacher T,
Placement P WHERE T.Department = P.Department AND
Salary>20000;
iv) SELECT Name, Place FROM Teacher T, Placement P WHERE
Gender =’F’ AND T.Department=P.Department;
v) select count(*) from Teacher where dateofjoin like ‘%2_’;
Count(*)
3
Insert the following record into the table STUDENT – Roll No- 108, Name- Aadit, Sem1- 470, Sem2-
444, Sem3-475, Div – I. Ans : INSERT INTO STUDENT VALUES (108, ‘Aadit’, 470, 444, 475, ‘I’);
------------------------------------------------------------------------------------------------------------------------------------------------
Increase the TAMIL marks of the STUDENT table by 3% whose name begins with ‘N’.
Ans : UPDATE STUDENT SET TAMIL = TAMIL + TAMIL * 3 / 100 WHERE SNAME LIKE “N%”;
-----------------------------------------------------------------------------------------------------------------------------------------------
Delete the record of students securing D grade. Ans : DELETE FROM STUDENT WHERE GRADE=’D’;
---------------------------------------------------------------------------------------------------------------------------------------------
Add a column REMARKS in the table STUDENT with datatype as varchar with 50 characters
Ans : ALTER TABLE STUDENT ADD (REMARKS VARCHAR(50));
---------------------------------------------------------------------------------------------------------------------------------------------
Add a new column PHONE to store the phone number of the student
Ans : ALTER TABLE STUDENT ADD PHONE INT;
----------------------------------------------------------------------------------------------------------------------------------------------
Set ROLL as the primary key of the table STUDENT Ans : ALTER TABLE STUDENT ADD PRIMARY KEY (Roll);
----------------------------------------------------------------------------------------------------------------------------------------------
* The AVERAGE column of the STUDENT table has data type INT. Change the data type of AVERAGE column to
allow for FLOATING POINT values (1.0 to 5.0) Ans: ALTER TABLE STUDENT MODIFY AVERAGE DECIMAL(2,1);
* Change the SNAME column of the STUDENT table to STUDNAME.
ALTER TABLE STUDENT CHANGE SNAME STUDNAME VARCHAR(20) ;
* ADD a new column PRICE with data type as DECIMAL.
ALTER TABLE STUDENT ADD (PRICE DECIMAL(5,2));
* Add column price in the above store table with datatype as float.
ALTER TABLE STORE ADD(PRICE FLOAT(5,2));
* Write SQL command to change the table name STUDENT to SCHOOL.
ALTER TABLE STUDENT RENAME AS SCHOOL;
------------------------------------------------------------------------------------------------------------------------------------------------
Delete the ROLL column of the STUDENT table. Ans : ALTER TABLE STUDENT DROP ROLL ;
-----------------------------------------------------------------------------------------------------------------------------------------------
* To increase the SALARY of all Female employees by 10%. Empid Name Dob Gender Salary
UPDATE Employees SET salary = salary + salary* 10/100 100 RAM 1994-01-15 M 2000
WHERE gender = ‘F’; 200 SAKTHI 1995-10-18 F 4000
* To increase the SALARY of all Female employees by 10.
Ans : UPDATE Employees SET salary = salary + 10 WHERE gender = ‘F’;
* To display the NAME and GENDER of employees for whom SALARY is NULL.
Ans : SELECT name, gender from Employees WHERE salary is NULL;
* To display the maximum salary of employees born AFTER 31 December 1995.
Ans : SELECT max(Salary) FROM Employees WHERE dob > ’1995-12-31’;
* To delete the records of all employees born BEFORE 01 January 1995.
Ans : DELETE from Employees WHERE dob < ’1995-01-01’ ;
* To delete the records of all employees. Ans : DELETE from Employees ;
* Delete the records of those employees whose gender is male. Ans: DELETE from employees where gender = “ M”;
* Write commands to open database ‘KVS’ and show all tables in this database. And display
design/schema/structure of the table EMPLOYEE which is inside this database. And display all the records of table
EMPLOYEE. (i) Use KVS; (ii) Show Tables; (iii) Desc EMPLOYEE; (iv) Select * from EMPLOYEE;
--------------------------------------------------------------------------------------------------------------------------------
Table : Employees Table : Departments
Empid Name DOB Gender Salary Dept_id Dept_id Dept_name
100 Ram 1994-01-20 M 3000 1 1 Manager
200 Shakthi 1995-05-18 F 6000 2 2 Sales
* SELECT MONTHNAME(DOB) FROM Employees WHERE Gender = "F"; MONTHNAME(DOB)
* Display the Average Salary for Male and Female Employees MAY
Ans : SELECT GENDER, AVG(SALARY) FROM EMPLOYEES GROUP BY GENDER;
* Display the Employee Name and Department Name for all employees in descending order of their salary.
Ans : SELECT NAME, DEPT_NAME FROM EMPLOYEES NATURAL JOIN DEPARTMENTS ORDER BY SALARY DESC;
* Display the department id and number of employees for all departments having more than 1 employee.
Ans : SELECT Dept_id , count(*) from Employees GROUP BY Dept_id HAVING count(*)>1;
* Display the details of Employees having the highest salary.
SELECT * FROM EMPLOYEES WHERE SALARY = ( SELECT MAX(SALARY) FROM EMPLOYEES ) ;
* Display the details of employees having highest salary with gender as “M” .
SELECT * FROM EMPLOYEES WHERE SALARY = ( SELECT MAX(SALARY) FROM EMPLOYEES WHERE GENDER = “M” ) ;
-------------------------------------------------------------------------------------------------------------------------------------
* To show all information about the teacher of maths department
Ans: SELECT * FROM TEACHER WHERE DEPT=’MATHS’;
* To list name and department whose name starts with letter ‘M’
Ans: SELECT NAME , DEPT FROM TEACHER WHERE NAME LIKE ‘M%’;
* To display all details of female teacher whose salary in between 35000 and 50000
Ans: SELECT * FROM TEACHER WHERE SEX = ’F’ AND SALARY BETWEEN 35000 AND 50000 ;
-----------------------------------------------------------------------------------------------------------------------------------------------
* Display the Emp_Name and Gross salary of each employee. (Gross=basic+da+hra+nps).
SELECT EMP_NAME, BASIC+DA+HRA+NPS AS “GROSS SALARY” FROM EMPLOYEES;
* Display employee name and Total Salary (sum of basic and HRA ) of all employees. The column
heading ‘Total Salary’ should also be displayed.
SELECT emp_name, basic + HRA AS "Total Salary" FROM employees;
* Increase the DA by 3% of respective basic salary of all employees.
UPDATE EMPLOYEES SET DA=DA+BASIC * 3 / 100 ;
* Create a new table STUDENT having same fields and tuples as SCHOOL.
CREATE TABLE STUDENT AS SELECT * FROM SCHOOL;
* Removes those records from table SCHOOL whose Date of joining is after year 2000.
DELETE FROM School WHERE Year(DOJ)>2000;
* Insert a new record in table SCHOOL with values code=2001, subject = Tamil, experience = 12.
INSERT INTO SCHOOL(code, subject, experience) VALUES ( 2001 , ’Tamil’ , 12 ) ;
* Display total periods subjectwise.
SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT ;
* Display minimum experience and maximum code from relation SCHOOL.
SELECT MIN(EXPERIENCE), MAX(CODE) FROM SCHOOL;
* Display teacher name, gender by joining both tables on the basis of CODE attribute for the designation COORDINATOR.
Ans : SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN
WHERE SCHOOL.CODE = ADMIN.CODE and DESIGNATION = ‘COORDINATOR’ ;
* Display the total number of different subjects in school relation.
SELECT COUNT(DISTINCT SUBJECT) FROM SCHOOL;
--------------------------------------------------------
MAX(DATEOFAPP) = 24/02/1998
MIN(DATEOFAPP) = 01/01/1998
* Change the Flavour of the chips to “black salt “ for those chips whose flavour is “SALTY”.
UPDATE CHIPS SET FLAVOUR = ”BLACK SALT” WHERE FLAVOUR = ”SALTY” ;
* Display the Brand_Name ,Flavour and Total Amount(price*quantity) of those chips whose Brandname ends with ‘s’.
SELECT BRAND_NAME , FLAVOUR , PRICE*QUANTITY AS “TOTAL AMOUNT” WHERE BRAND_NAME LIKE “%S”;
* Display bookname, Author name and quantity issued from table Books and issued.
SELECT BNAME, AUNAME, QTY_ISSUED FROM BOOKS , ISSUED WHERE BOOKS.BID = ISSUED.BID;
* Display the details of books in the order of qty whose price is in between 200 to 300.
SELECT * FROM BOOKS WHERE PRICE BETWEEN 200 AND 300 ORDER BY QTY;
* Display total qty of books of type “Computer”.
SELECT SUM(QTY) FROM BOOKS WHERE TYPE=”COMPUTER”;
* To display the total Quantity for each Product, excluding Products with total Quantity less than 5.
SELECT PRODUCT, SUM(QTY) FROM ORDERS GROUP BY PRODUCT HAVING SUM(QTY)>=5;
* To display the total number of orders quantity-wise.
SELECT QTY, COUNT(*) FROM ORDERS GROUP BY QTY;
* List the PCode , PName and UPrice in Descending order of their PName.
If PName is same then display the data in Ascending order of UPrice.
SELECT PCODE , PNAME , UPRICE FROM PRODUCT ORDER BY PNAME DESC, UPRICE ASC ;
* 10% discount is given on PNAME other than SOAP and POWDER.
UPDATE PRODUCT SET UPRICE =UPRICE – UPRICE * 10 / 100 WHERE PNAME NOT IN (‘SOAP’,’POWDER’);
* To display the Cartesian Product of the tables WATCHES and SALE. Ans : SELECT * FROM Watches , Sale ; (or)
SELECT * FROM Watches CROSS JOIN Sale; (or) SELECT * FROM Watches JOIN Sale; (or) SELECT * FROM Watches INNER JOIN Sale ;
* NATURAL JOIN (NO duplicate of columns) : SELECT * FROM WATCHES NATURAL JOIN SALE ;
* EQUI JOIN (duplicate of columns) : SELECT * FROM WATCHES , SALE WHERE WATCHES.WATCHID = SALE.WATCHID ; ( OR )
SELECT * FROM WATCHES JOIN SALE ON WATCHES.WATCHID = SALE.WATCHID ;
* Cartesian Product between WATCHES and SALE : Degree = 8 , Cardinality = 35
* NATURAL JOIN between WATCHES and SALE : Degree = 7 , Cardinality = 7
* Are these values same?What can be the reason for this?No, because cartesian product is the all-possible combination of tuples
between two tables. Where as Natural join selects only those tuples for whom the values of the common attributes are same.
* To add Primary Key : ALTER TABLE WATCHES ADD PRIMARY KEY (WATCHID) ;
* Define CID in CUSTOMER table as Foreign Key that refers to CID i.e. Primary Key of COMPANY table.
ALTER TABLE CUSTOMER ADD FOREIGN KEY(CID) REFERENCES COMPANY(CID);
* To add Foreign Key : ALTER TABLE SALE ADD FOREIGN KEY (WATCHID) REFERENCES WATCHES(WATCHID) ;
* To add UNIQUE constraint : ALTER TABLE WATCHES ADD UNIQUE (WATCH_NAME) ;
* While creating table by default each column takes NULL value except PRIMARY KEY column. To change the column constraint
from NULL to NOT NULL : ALTER TABLE WATCHES MODIFY WATCHNAME VARCHAR(20) NOT NULL;
* To change the size of the column PNAME from VARCHAR(30) to VARCHAR(40) of the PRODUCT table.
ALTER TABLE PRODUCT MODIFY PNAME VARCHAR(40) ;
* To set default value of DateofBirth of STUDENT to 15th MAY 2000 :
ALTER TABLE STUDENT MODIFY DateofBirth DATE DEFAULT ‘2000-05-15’ ;
* To remove the column PNAME from the table PRODUCT : ALTER TABLE PRODUCT DROP PNAME ;
* To remove primary key from the table PRODUCT : ALTER TABLE PRODUCT DROP PRIMARY KEY;
* To remove STUDENT table permanently : DROP TABLE STUDENT ;
* To remove Database SCHOOL permanently : DROP DATABASE SCHOOL ;
CHAR(n) : Character type – n could be any value from 0 to 255.
VARCHAR(n) : Character type – n could be any value from 0 to 65535.
INT : Integer type – each INT occupies 4 bytes storage. BIGINT occupies 8 bytes.
FLOAT : Holds numbers with decimal points. Each FLOAT value occupies 4 bytes.
DATE : Date type – format ‘YYYY-MM-DD’ . The supported range is ‘1000-01-01’ to ‘9999-12-31’.
CREATE TABLE student CREATE TABLE stud
( admno INT PRIMARY KEY, (admno INT ,
roll INT NOT NULL UNIQUE, tamil INT,
sname VARCHAR(20), english INT ,
grade CHAR(2) DEFAULT “E1” , CHECK (tamil > English),
age INT CHECK (age > 10) CONSTRAINT myfkey FOREIGN KEY (admno) REFERENCES student(admno)
); );
Single Row Functions or Scalar Functions : Aggregate Functions or Multiple row Functions:
* It operates on a single row at a time. * It operates on groups of rows
* It returns one result per row. * It returns one result for a group of rows.
* It can be used in Select, Where and Order * It can be used in the select clause only.
by Clause. * Examples : Max() , Min() , Sum() , Avg () , count() and count(*).
* Examples : Math , String and Date functions
* Select the day, month number and year of joining of all students.
SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM STUDENT;
*If the date of joining is not a Sunday, then display it in the following format "Wednesday, 26, November, 1979."
mysql> SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ) FROM STUDENT WHERE DAYNAME(DOJ)!='Sunday';
* Display the number of Cars purchased by each Customer from SALE table.
SELECT CustID, COUNT(*) "Number of Cars" FROM SALE GROUP BY CustID;
*Display the Customer Id and number of cars purchased if the customer purchased more than 1 car from SALE table.
mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
* Display the number of people in each category of payment mode from the table SALE.
mysql> SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY Paymentmode ORDER BY Paymentmode;
* Display the PaymentMode and number of payments made using that mode more than once.
SELECT PaymentMode, Count(PaymentMode) FROM SALE GROUP BY Paymentmode HAVING COUNT(*)>1 ORDER BY Paymentmode;
* Write SQL statement to display the name of the Product whose price is more than 0.5 hundred.
SELECT Pname FROM detergents WHERE price > price/100;
* To display name of the detergent powder manufactured by HL.
SELECT Pname FROM detergents WHERE manufacturer = ‘HL’;
* To display details of all the products not manufactured by HL.
SELECT * FROM detergents WHERE manufacturer != ‘HL’;
* List the name of employees whose name ends with 'N' or does not contain 'M' in it.
SELECT ename FROM empl WHERE ename LIKE '%N' OR ename NOT LIKE '%M%';
* List the name of employees whose name starts with 'S' and have length at least 5.
SELECT ename FROM empl WHERE ename LIKE 'S_ _ _ _%'; (4 underscores after S )
* Display the hometowns and no. of employees belonging to them if the headcount per hometown is at least 2.
SELECT HOMETOWN, COUNT(EID) AS 'NO OF EMPLOYEE' FROM EMP GROUP BY HOMETOWN HAVING COUNT(EID) >= 2;
* Display the number of employees working in each DEPT_ID excepting 'D01' where no. of employees in the
DEPT_ID is more than 1. Ans : SELECT DEPTID, COUNT(*) AS 'NO OF EMPLOYEE' FROM EMP
WHERE DEPTID != 'D01' GROUP BY DEPT_ID HAVING COUNT(*) > 1;