sql -xii IP
sql -xii IP
Revision of SQL
1|Page
- Grant it gives user’s access privilege to a database
- Revoke It withdraws user’s access privileges given by
using the GRANT command
DATA TYPE OF ATTRIBUTE:
Data type indicates the type of data value that an attribute can have and the
operations that can be performed on the data of that attribute
FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4
bytes.
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is
the 4 digit year, MM is the 2 digit month and DD is the 2 digit date
CONSTRAINTS:
2|Page
SQL queries:
DDL Commands
1. CREATE Syntax : Example :
DATABASE CREATE DATABASE CREATE DATABASE EMP_DATA;
<DBNAME>;
2. For using Syntax : Example :
/opening USE <DBNAME>; USE EMP_DATA;
Database
3. To show all Syntax : Example :
available SHOW DATABASES; SHOW DATABASES;
databases
4. To create Syntax : Example :
table CREATE TABLE <table_name> CREATE TABLE EMP
(<col_name> <datatype> (EMPNO INT ,
<size> constraint, ENAME VARCHAR(20),
<col_name> <datatype> SALARY INT);
<size> constraint,----------
); CREATE TABLE EMP
(EMPNO INT PRIMARY KEY,
ENAME VARCHAR(20),
SALARY INT);
3|Page
5. Describe table Syntax : Example :
DESCRIBE <TABLE_NAME>;
– can view the
structure of
the table
OR
OR
4|Page
INSERT INTO STUDENT
(ROLLNO,SNAME,SDOB)
VALUES (20, ‘SHEENA’, ‘2009-10-
13’);
Output:-
5|Page
11. DISTINCT Syntax : To display unique department
clause - The SELECT DISTINCT <COLNAME> number for all the employees.
SELECT FROM <tablename>;
statement mysql> SELECT DISTINCT DeptId
when FROM EMPLOYEE;
combined
with Output:-
DISTINCT
clause,
returns
records
without
repetition
(distinct
records)
12. WHERE Syntax : To display distinct salaries of
clause - The the employees working in the
WHERE SELECT * FROM <tablename> department number D01.
clause is WHERE <condition>;
used to mysql> SELECT DISTINCT Salary
retrieve data FROM EMPLOYEE WHERE
that meet Deptid='D01';
some
specified Output:-
conditions
6|Page
13. Membership Syntax:
Operator – SELECT * FROM <tablename>
IN WHERE <colname> IN
(<val1>,<val2>…);
The IN
operator
compares a
value with a
set of values
and returns
true if the
value belongs
to that set.
14. ORDER BY Syntax : Example :
clause –
used to SELECT <colname>… SELECT * FROM EMP
FROM <tablename>
display data ORDER BY <colname>; ORDER BY SALARY;
in an ordered
(arranged) Output:-
form with
respect to a
specified
column.
By default
displays
records in
ascending
order
To display
The following query displays
the records in
details of all the employees in
descending
descending order of their salaries.
order, the
DESC
mysql> SELECT * FROM
keyword
EMPLOYEE ORDER BY Salary
written
DESC;
Output:-
7|Page
15. Handling Syntax : Displays details of all those
NULL employees who have not been
Values SELECT * FROM <tablename> given a bonus. This implies that
WHERE <colname> IS NULL/
IS NOT NULL; the bonus column will be blank.
Output:-
Output:-
9|Page
existing
records in a
table.
18. Data Deletion Syntax: To delete the details of
- TheDELETE FROM table_name student whose Roll number is 2.
DELETE WHERE condition;
statement is mysql> DELETE FROM STUDENT
used to WHERE RollNumber = 2;
delete one or
more
record(s)
from a table
SQL Joins:
Process of accessing data from multiple tables is called Join in SQL
JOIN operation combines tuples from two tables on specified conditions. This is
unlike cartesian product, which make all possible combinations of tuples
Example : List the Ucode, Uname, Ucolor, size and Price of related tuples of
table UNIFORM and COST.
(a) SELECT * FROM UNIFORM U, COST C where U.Ucode = C.Ucode;
10 | P a g e
Equi Join
The SQL Equi join is a simple join clause where the relation is established using
equal to sign as the relational operator to mention the condition.
The join in which columns are compared for equality is called equi-join. A non
equi join specifies condition with non-equality operator. In equi-join we put (*)
in the select list will print common column twice in the output.
Example :
Equi Join – Inner join is used to return the records which are having matching values
in both the tables
An Equi Join is a type of join that combines tables based on matching values in the
specified columns.
❖ The column names do not need to be the same.
❖ The resultant table can contain repeated columns.
❖ It is possible to perform an equi join on more than two
Equi Join- ❖ It performs a JOIN against equality or matching column(s) values of the
associated tables.
SELECT * /Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;
Or
SELECT * /Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;
11 | P a g e
Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname
belongs
toDEPT table. So, to retrieve data in this we will use join
SELECT emp.ename, emp.sal, dept.dname
FROM emp, dept WHERE emp.deptno=dept.deptno;
Output:
++++
| ename | sal | dname |
++++
| SMITH | 800.00 | RESEARCH |
| ALLEN | 1600.00 | SALES |
| WARD | 1250.00 | SALES |
| JONES | 2975.00 | RESEARCH |
| MARTIN | 1250.00 | SALES |
| BLAKE | 2850.00 | SALES |
| CLARK | 2450.00 | ACCOUNTING |
| SCOTT | 3000.00 | RESEARCH |
| KING | 5000.00 | ACCOUNTING |
| TURNER | 1500.00 | SALES |
| ADAMS | 1100.00 | RESEARCH |
| JAMES | 950.00 | SALES |
| FORD | 3000.00 | RESEARCH |
| MILLER | 1300.00 | ACCOUNTING |
Note:
FUNCTION in MySQL
Function:
12 | P a g e
A function is a predefined command set that performs some operation and returns
the single value. A function can have single, multiple or no arguments at all.
13 | P a g e
vi. RTRIM()
vii. SUBSTR()/MID()
viii. INSTR(),
ix. LENGTH()
x. RIGHT()
xi. LEFT()
3) Date Functions:
i. SYSDATE()
ii. NOW()
iii. DATE()
iv. MONTH()
v. YEAR()
vi. DAYNAME()
vii. MONTHNAME()
viii. DAY()
Math Functions:
1.Pow(x,y )/power(x,y): Returns the value of X raised to the power of Y.
Example:
(i)Select POW(2,4); Result:16
(ii)SELECT POW(2,-2; Result:0.25
(iii)SELECT POW(-2,3); Result: -8
(iv)SELECT id, salary, POWER(salary,2) FROM employee;
Result:
14 | P a g e
+----+----------+-----------------+
| id | salary | power(salary,2) |
+----+----------+-----------------+
| 1 | 25000.00 | 625000000 |
| 2 | 30000.00 | 900000000 |
| 3 | 32000.50 | 1024032000.25 |
| 4 | 37500.50 | 1406287500.25 |
| 5 | 42389.50 | 1796869710.25 |
+----+----------+-----------------+
2.ROUND(X): Rounds the argument to zero decimal place, whereas ROUND(X,
d) rounds X to d decimal places.
Example:
(i) ROUND(-1.23); Result: -1
(ii) ROUND(-1.68); Result: -2
(iii) ROUND(1.58); Result: 2
(iv) ROUND(3.798, 1); Result: 3.8
(v) ROUND(1.298, 0); Result: 1
(vi) ROUND(76823.298, -1); Result: 76820
(vii) ROUND( 25.298,-1); Result: 30
(viii) ROUND(3.798, 1); Result: 3.8
(ix) ROUND(4536.78965,-3) Result: 5000
(X) ROUND(4536.564553,-2): Result: 4500
(XI) ROUND(4586.564553,-2): Result: 4600
(XII)ROUND(76823.298, -2); Result:76800
XII)ROUND(76823.298, 2); Result: 76823.30
(XIII) ROUND(3.798, 2); Result: 3.80
15 | P a g e
1. LENGTH(): Returns the length of a string in bytes/no. of characters in string.
Example:
(i) SELECT LENGTH(‘#INFOR MATICS#’); Result:14
(ii)SELECT LENGTH(First_Name) FROM Employee;
Result:
+--------------------+
| LENGTH(First_Name) |
+--------------------+
|4|
|7|
|8|
|5|
|6|
+--------------------+
5 rows in set (0.00 sec)
16 | P a g e
|0|
|0|
+---------------------------+
Example:
SELECT UCASE(‘informatics’); Result: INFORMATICS
7.LEFT(): Returns the given number of characters by extracting them from the left
side of the given string
Example:
SELECT LEFT(‘INFORMATICS PRACTICES’, 3); Result: INF
8. RIGHT(): Returns the given number of characters by extracting them from the
right side of the given string
Example:
SELECT RIGHT(‘INFORMATICS PRACTICES’,3); Result: CES
17 | P a g e
(iv) SELECT SUBSTRING('Computers', -5, 3); Result: 'ute'
(v) SELECT MID('Informatics',3,4); Result: 'form'
(vi) SELECT MID(first_name,3,2) FROM Employee;
Result:
+---------------------+
| MID(first_name,3,2) |
+---------------------+
| it |
| ek |
| vk |
| mt |
| aw |
+---------------------+
10. LTRIM(): Removes leading spaces.
Example:
SELECT LTRIM(' INFORMATICS '); Result: 'INFORMATICS’
Date/Time Functions
1. NOW(): Returns the current date and time
Example:
select NOW(); Result: '2020-04-06 13:58:11'
18 | P a g e
Example:
SELECT DATE('2020-04-06 01:02:03'); Result: '2020-04-06'
Aggregate functions summarize the results of a query and return a single value
calculated from values in a column instead of providing the listing of all of the
rows.
Syntax:
SELECT <FUNCION> (column_name) FROM <table_name>;
The following are aggregate functions:
19 | P a g e
1) SUM(): returns the total sum of a numeric column. It gives the arithmetic sum of
all the values present in a particular column. It can take only one argument. NULL
values are not included in the calculations.
Example: SELECT SUM(MARKS) FROM STUDENT;
It displays sum of all the marks in the table student
3) MAX(): It returns the maximum value among the given set of values of any
column or expression based on column.
Example: SELECT MAX(MARKS) FROM STUDENT;
It displays maximum marks from the column marks of student table.
4) MIN(): It returns the minimum value among the given set of values of any
column or expression based on column.
Example: SELECT MIN (MARKS) FROM STUDENT;
It displays minimum marks from the column marks of student table.
5) COUNT(): It count the number of non-null values in a column. It can take one
argument, which can be a column name or *. When the argument is a column name
then COUNT() returns the non-null values in that column.
If the argument is an * then COUNT() counts the total number of records / rows
along with the NULL values satisfying the condition, if any, in the table. So, it returns
the total number of records or rows from the table.
20 | P a g e
It will give output as 10 rows.
But while writing SELECT COUNT(MARKS) FROM STUDENT;
Will give output as 7 because there will be 3 null values which is ignored by COUNT()
Example: To display the roll number, name and marks of all the students in
descending order of their marks and ascending order of their names.
SELECT ROLLNO, NAME , MARKS FROM STUDENT
ORDER BY MARKS DESC, NAME;
21 | P a g e
GROUP BY in SQL
At times we need to fetch a group of rows on the basis of common values in a
column. This can be done using a GROUP BY clause.
It groups the rows tog-ether that contain the same values in a specified
column. We can use the aggregate functions (COUNT, MAX, MIN, AVG and
SUM) to work on the grouped values.
HAVING Clause in SQL is used to specify conditions on the rows with GROUP
BY clause.
Syntax:
SELECT <column1, column2…..> , aggregate function(colname)
FROM <tablename>
WHERE <condition>
GROUP BY <column1>
HAVING <condition>;
22 | P a g e
(ii) Write a query to display customer id and number of cars purchased
if the customer purchased more than one car from the sale table.
mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING
Count(*)>1;
(iv) Display the payment mode and number of payments made using
23 | P a g e
that mode more than once.
mysql> SELECT PaymentMode, Count(PaymentMode) FROM SALE GROUP
BY Paymentmode HAVING COUNT(*)>1 ORDER BY Paymentmode;
1 Write down name of four functions that can be used with Group by?
24 | P a g e
Select * from travel where order by tdate;
But he is not getting the desired result.
Help him by choosing the correct command.
a. Select * from travel order by tdate;
b. Select * from travel in ascending order;
c. Select tdate from travel order by tdate;
Ans. Select * from travel order by tdate;
8. Find the output of the following SQL queries:
i. SELECT ROUND(7658.345,2); O/P – 7658.35
ii. SELECT MOD(ROUND(13.9,0),3); o/p - 2
9. Give any two differences between POWER() and SUM().
Ans: POWER(x,y) – will return value x power to y
SUM() – Aggregate function, and returns sum of values of one column
10. Find the output of the following SQL queries:
i. SELECT SUBSTR(‘FIT INDIA MOVEMENT’,5);
O/P – INDIA MOVEMEMNT
ii. SELECT INSTR(‘ARTIFICIAL INTELLIGENCE’, ‘IA’);
O/P - 8
UNSOLVED QUESTIONS
25 | P a g e
Write the queries of the following:
i. Display the details of furniture which are purchased in month of December.
ii. Display the average price of furniture.
5) Explain the difference between group by and order by clause with example.
6) When we use having clause? Explain with example.
7) Write the SQL queries to do the following:
i. Add a new column “Name” of data type Varchar(30) in table “Hotel”.
ii. Delete a record from table “emp” whose empid is 101.
iii. Delete all the records of table “stock” along with structure.
iv. Display the total of column “Salary” from table “emp”.
v.
8) Based on the table: “Emp” given below:
Empid Salary
1 45000
2 50000
3 55000
4 40000
26 | P a g e
5 NULL
Write the output of the following:
i. Select mod(Salary, 100) from emp;
ii. Select average(Salary) from emp;
iii. Select sum(Salary) from emp where empid > 3;
iv. Select max(Salary) from emp;
27 | P a g e
He was surprised with the output as query (i) returns 5 rows whereas Query(ii)
returns only 3 rows. Explain why?
14) Which functions in MySQL extract words from specified character to n number of
character from given string. Write the function names and explain them with
example.
15) Anuj is student of class XII, trying to execute the following queries, help him to
predict the output.
i. select round (45.9,-2);
ii. select round ( -101.86,0)
28 | P a g e