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

UNIT-2 DataBases Using SQL - 1

The document discusses database concepts including data, databases, DBMS, relational databases, RDBMS, tables, keys, and the SQL language. It provides definitions and examples of each concept. It describes the different types of SQL statements including DDL, DML, DCL, and TCL. Specific SQL commands like CREATE DATABASE, CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE and SELECT are discussed along with their syntax and examples. Data types in MySQL including numeric, string and date/time types are also outlined.

Uploaded by

Abhinav Khanna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

UNIT-2 DataBases Using SQL - 1

The document discusses database concepts including data, databases, DBMS, relational databases, RDBMS, tables, keys, and the SQL language. It provides definitions and examples of each concept. It describes the different types of SQL statements including DDL, DML, DCL, and TCL. Specific SQL commands like CREATE DATABASE, CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE and SELECT are discussed along with their syntax and examples. Data types in MySQL including numeric, string and date/time types are also outlined.

Uploaded by

Abhinav Khanna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

UNIT-2:Database Query using SQL


Data:
It is a collection of raw facts and figures.
Eg: 1234

Database:
It is an organized collection of data.
Eg: Address book, student register, Dictionary etc.

DBMS( DataBase Management System):


The software which is used to creating and managing the database is called DBMS.
Eg: MySQL, MS-ACCESS, Oracle, SQL Server, Sybase, DB2, postgreSQL etc.

Relational Database:
A database in which the data is stored in the form of relations (also called tables) is called a
Relational Database. In other words a Relational Database is a collection of one or more tables.

RDBMS(Relational DataBase Management System):


A DBMS used to manage Relational Databases is called an RDBMS.
Some popular RDBMS software available are:
Oracle, MySQL, Sybase, Ingress.

Benefits of using a DBMS are:


a. Redundancy can be controlled
b. Inconsistence can be avoided
c. Data can be shared
d. Security restrictions can be applied.

Relation/Table:
A table refers to a two dimensional representati on of data arranged in columns (also called fields or
attributes) and rows (also called records or tuples).

Degree:
The number of columns in a table is called degree.

Cardinality:
The number of rows in a table is called degree.

Key:
A column or a combination of columns which can be used to identify one or more rows (tuples) in a
table is called a key of the table.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Primary Key:
The group of one or more columns used to uniquely identify each row of a relation is called its
Primary Key.

Candidate Key:
A column or a group of columns which can be used as the primary key of a relation is called a
candidate key because it is one of the candidates available to be the primary key of the relation

Alternate Key:
A candidate key of a table which is not made its primary key is called its Alternate Key.

MySQL:
It is an Open Source RDBMS Software. It is available free of cost.

Characteristics of MySQL:
 MySQL is released under an open-source license so it is customizable.
 MySQL has superior speed, is easy to use and is reliable.
 MySQL uses a standard form of the well-known ANSI-SQL standards.
 MySQL is a platform independent.
 MySQL is an easy to install RDBMS and is capable of handling large data sets.

Data Types:
 Datatypes is used to identify the type of data and associated operations for handling it.
 Datatypes in MySQL categorized into three types.
a) Numeric
b) String
c) Data and Time type
a) Numeric data types
Numbers without fraction part (Integral values)
Datatype Storage(Bytes) Range(Signed) Range(Un-Signed)
TINYINT 1 -128 to 127 0 to 255
SMALLINT 2 -32768 to 32767 0 to 65535
MEDIUMINT 3 -8388608 to 8388607 0 to 16777215
INT 4 -2147483648 to 2147483647 0 to 4294967295
BIGINT 8 -9223372036854775808 to 0 to
9223372036854775807 18446744073709551615

Numbers with fraction part (decimal values)


FLOAT(M,D): „M‟ specifies total length of number and ‟D‟ specifies the total number of
decimal
digits. It can‟t be unsigned. Decimal precision can go to 24 places for a FLOAT.
Double(M,D): „M‟ specifies total length of number and ‟D‟ specifies the total number of
decimal digits. It can‟t be unsigned. Decimal precision can go to 53 places for
a DOUBLE.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Decimal(M,D): „M‟ specifies total length of number and ‟D‟ specifies the total numb er of
decimal digits. It can‟t be unsigned.

b) String data types


Datatype Meaning
Char(M) „M‟ specifies the maximum size of value. Each value will
occupies „M‟ bytes of space irrespective no.of characters
it has.
Varchar(M) „M‟ specifies the maximum size of value. The space
occupied by value depends upon the characters in value

c) Date and Time types


Datatype Storage(Bytes)
YEAR 1
DATE 3
TIME 3

The SQL statements Categorized as follows:-


1) Data Definition Language (DDL) Commands or Statements
2) Data Manipulation Language (DML) Commands
3) Data Control Language(DCL)
4) Transaction Control Language(TCL)

1) DDL (Data Definition Language):-


These statement are used create database or table Structure or to alter the table structure .
The DDL Statements are:-
a. CREATE DATABASE
b. CREATE TABLE
c. ALTER TABLE
d. DROP TABLE

a. Create Database command:-


It is used to create a new database.
Syntax:- create database databasename;
Ex:- mysql> CREATE DATABASE School;
We can select the database by using the following command.
Syntax:-Use databasename;
Eg: mysql> use school;
We can display list of databases using the following command
Eg: mysql> show databases;

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
b. “CREATE TABLE” COMMAND:-
it is used to create the new table‟s structure.
Syntax:
CREATE TABLE <table-name>(<columnname1> <datatype>
[<size>],(<columnname2> <datatype>[<size>], …);
Example:
Create table student(rno int,name varchar(20),marks decimal(5,2),dob
date);
Viewing Structure of Table:-
“Describe” or “desc” is used to know the table‟s structure .
Syntax:
Describe tablename;
(Or)
Desc tablename;
Eg:
mysql> DESCRIBE Student;
(or)
mysql> desc student;

c. “Alter Table” Command :-


It is used to add any new column to the existing table or to change the datatype/size
of existing column or to drop an existing column or to change name of existing column.
Syntax1:-to add new column
ALTER TABLE <table_name> ADD <column_name> [datatype];
Eg: ALTER TABLE STUDENT ADD PHNO LONG;
Syntax2:-To modify the datatype of existing column.
ALTER TABLE <table_name> MODIFY <column_name> <new_definition>;
syntax3:-to change column name
mysql>alter table tablename change oldcolumnname newcolumnname datatype;
Syntax4:-to drop a column
ALTER TABLE <table_name> DROP <column_name>;
Eg:
mysql> ALTER TABLE Student DROP Games;
d. drop table command:
It is used to drop the entire table‟s structure.
syntax:
mysql> drop table table-name;
2) DML (Data Manipulation Language) Commands
These commands are used to insert new data into table or to update table‟s content or to retrieve
content of the table.
Data Manipulation Language Commands are:
a) INSERT INTO command
b) UPDATE command
c) DELETE command
d) SELECT command

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
a) Insert into command:-it is used to insert new tuples into a relation.
Syntax (1):- To insert a single tuple with all column values
INSERT INTO <TableName> VALUES (column1value, column2value…..columnnvalue);
if column values are text or date or time values then these values should be enclosed within the
quotes.
Eg: mysql> insert into student values( 1, „ram‟, 45.67, „1999 -01-25‟);
Syntax (2):- To insert a multiple tuple
INSERT INTO <TableName> VALUES (column1value, column2value…..columnnvalue);
Eg: mysql> insert into student values ( 2, „rama‟, 65.87, „1989 -11-15‟) , ( 2, „raman‟,95.55,„1992-01-
09‟);

Syntax (3):- To insert a single tuple with few column values.


INSERT INTO <TableName> (colname1,colname2) VALUES (column1value, olumn2value);

b) UPDATE command
It is used to update all values of a column or specific value(s) of a column.
Syntax (1): To update all column values:-
update <tablename> set <columnname>=<newvalue>;
Eg: To set all „phno‟ values of a „student‟ table to „12345‟
mysql> update student set phno=12345;

Syntax (2):- To update specific column values


update <tablename> set <columnname>=<newvalue> where condition;
Eg: To change „phno‟ value to „6789‟ of a student whose roll nu mber is 2;
mysql> update student set phno=6789 where rno=2;

c) DELETE Command:
It is used to delete all tuples or specific tuples from a table.
Syntax (1):-to delete all tuples
delete from tablename;
Eg: to delete all tuples from „student‟ table.
Mysql>delete from student;

Syntax (2):-to delete specific tuples


Delete from tablename where condition;
Eg:-to delete student record whose rollno is 1
Mysql>delete from student where rno=2;

d) SELECT Command:
it is used to retrieve the content from the table in the form either columns/rows.
Consider the following student Table:

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

Retrieving single Column values:-


Syntax1:-select columnname from tablename;
mysql> SELECT rno FROM Student;

Retrieving Multiple Columns values:-


Syntax: select columnname1,columnname2,.… from tablename;
Eg: mysql> SELECT rno, Name FROM Student;

To Retrieving all column values:-


Sytax
select *from tablename;
Eg:
mysql> SELECT * FROM Student;

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Changing the order ofColumns in output:-
We can display the column‟s data in which ever order we want.
mysql> SELECT Name, rno FROM Student;

Eliminating duplicate values


By using distinct keyword we can eliminate duplicate values of a column on which it applied.
Eg:

Changing Column name in the output:


By using ‘as’ clause we can change column name in the output only. But, there will be no change in the
original table.
Eg: Write a SQL command to change „rno‟ title as „RollNo‟ in the output.

Note: It is not mandatory to keep column alias value within quotes if there is no special character like space, but it is
mandatory if there is any space any.
`

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Putting text in the Query output:
We can put some text and comments in the output.
Eg:

Selecting specific rows – where clause:


The WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned.
Syntax:
SELECT <colnames> FROM <tablename> WHERE <condition>.
Relational operators:
 To compare two values, a relational operator is used.
 The result of the comparison is either true or false.
 The SQL recognizes following relational operators:
<, <= , >, >=, =, and <> (not equals to)
Eg: A SQL query to display name of student whose roll number is 2;

Logical operators:
The logical operators OR (| | ), AND (&&), and NOT (!) are used to combine search conditions in the WHERE
clause.
Ex (1): To list all the students whose marks are in between 60 and 80.

Ex (2): To list all the students whose name is either „ram‟ or „peter‟.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Ex (3): To list all the students except whose name is „ram‟.

(or)

Condition Based on a Range:


 The BETWEEN operator defines a range of values that the column values must fall in to make the
condition true.
 The range includes both lower value and the upper value.
Ex (1): To list all the students whose marks are in between 60 and 80.

 The operator NOT BETWEEN is as reverse of BETWEEN operator.


Ex (1): To list all the students except whose marks are in between 60 and 80.

Condition Based on a List:


 The IN operator selects values that match any value in the given list of values.
Eg: To List roll number and Names of all the students whose name is either „ram‟ or „peter‟ or „john ‟.

 The NOT IN operator finds rows that do not match in the list.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg: To List roll number and Names of all the students except whose name is either „ram‟ or „peter‟
or „john‟.

Condition Based on pattern Matches:


 SQL includes a String matching operator called LIKE for comparisons on character strings using
patterns.
 There are two wild card characters in pattern matching. They are
 The percent symbol (%)
 The underscore symbol (_)

 The Percent (%) symbol is used to represent any sequence of zero or more characters.
 The underscore (_) symbol is used to represent a single character.
Syntax:
SELECT <column name>, [<column name>…] WHERE <column name> LIKE Pattern [AND
[OR]] <Condition2>;

Eg (1): To list all details of the students whose name starts with „r‟?

Eg (2): To list all details of the students whose name ends with „m‟?

Eg (3): To list all details of the students whose name has „z‟?

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg (4): To list all details of the students whose name has exactly 4 character length?

Eg (5): To list all details of the students whose name has exactly 3 character length and second
character should be „a‟?

Searching for NULL:


 NULL means a value that is unavailable, unassigned, unknown or inapplicable.
 NULL is not the same as zero or a space or any other character.
 In a table NULL is searched for using IS NULL keywords.
Eg (1): To list all details of the students who have a date of birth ?

Eg (2): To list all details of the students who doesn‟t have a date of birth ?

Sorting results – ORDER BY:


 The result obtained using SELECT statement is displayed in the order in which the rows were
entered in the table using the INSERT INTO statement.
 The results of the SELECT statement can be displayed in the ascending or descending values of a
single column or multiple columns using ORDER BY clause.
 To display data in descending order, DESC keyword is used in ORDER BY clause.
 However it is not necessary to specify ASC for ascending order as it is the default order.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Syntax:
SELECT <column name>, [<column name>…] [WHERE <Condition list>] ORDER BY <column
name>;
Eg (1): To list all details of the students based on ascending order of their marks ?

Eg (2): To list all details of the students based on descending order of their marks ?

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

Functions in MySQL
 A Function is a special type of predefined command set that performs some operation and returns
single value.
 There are two types of functions in MySQL. They are
 Single row functions
 Multiple row functions

Single row functions


 Single row functions operate on a single value to return a single value.
 They can accept one or more arguments but return only one result per row.
 They are further categorized into:
1. Numeric functions
2. String functions
3. Date and Time functions

Multiple row functions (also called Aggregate Functions):


 Multiple row functions operate on a set of rows to return a single value. Examples include SUM(),
AVG() and COUNT().

1) Numeric functions:
MySQL numeric functions perform operations on numeric values and return numeric values.
Some of the numeric functions are:
 Mod()
Syntax:
Mod(m,n)
Returns the remainder of „m‟ divided by „n‟. Returns „m‟ if m<n
Eg (1):

Eg (2):

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg (3):

 Pow()/power()
Syntax:
Power(m,n)
Returns value of „m‟ to the power of „n‟.
Eg(1):

(or)

 Sign()
Syntax:
Sign(n)
This function returns sign of a given number.
This function returns -1, if argument n<0
This function returns 0, if argument n=0
This function returns 1, if argument n>0
Eg (1):

Eg (2):
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg (3):

 Sqrt()
Syntax:
Sqrt(n)
Return square root of given number. This function returns a real value.
Eg (1):

Eg (2):

 Round()
Syntax:
round(X,D)
 Rounds the argument X to D decimal places.
 If number of decimal places is not specified or is zero, the number rounds to the nearest
Integer.
Eg:

(or)
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 If negative value is specified for precision, it counts off that value left from the decimal
point.
 Eg (1):

Eg (2) :

Eg (3):

Eg(4):

 If positive value is specified for precision, it counts off that value right from the decimal
point.
Eg (1):
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg (2):

Eg (3):

 Truncate()
Syntax:
truncate(X,D)
Returns the number X, truncated to D decimal places. If D is 0, the result has no decimal point
or fractional part. If D is negative, it causes D digits left of the decimal point of the value X to
become zero.
Note: TRUNCATE does not round a number. It simply chops off digits from a number.
Eg (1):

Eg (2):

Eg (3):
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

Eg (4):

Eg (5):

2) String Functions
These functions perform operations on either strings or characters and returns result as number or
string.
 Length()
Syntax:
Length(str)
This will return length of given string in bytes.
Eg (1):

Eg (2):
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 Concat()
Syntax:
Concat(str1,str2,….,strn)
This function concatenates the given strings.

Eg (1):

Eg (2):

 Instr()
Syntax:
Instr ( str, substr)

Returns the position of the first occurrence of substring substr in string str.
Eg (1):

Eg (2):

 Lower() / lcase()
Syntax:
Lower(str)
(or)
Lcase(str)
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

Returns the argument (str) in lowercase.

Eg:

(OR)

 Upper() / ucase()
Syntax:
Upper(str)
(or)
ucase(str)

Returns the argument (str) in uppercase.


Eg:

(or)

 Left()
Syntax:
Left(str,n)
Returns the „n‟ specified number of characters from the left side of string str. Returns NULL
if any argument is NULL.
Eg :

CHAPTER – 9: REVIEW OF XI CLASS MySQL 140


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 Right()
Syntax:
Right(str,n)
Returns the „n‟ specified number of characters from the right side of string str. Returns
NULL if any argument is NULL.

Eg :

 Ltrim()
Syntax:
Ltrim(str)
Removes leading spaces i.e. removes spaces from the left side of the string str.
Eg:

 Rtrim()
Syntax:
rtrim(str)
Removes trailing spaces i.e. removes spaces from the right side of the string str.
Eg:

 Trim()
Syntax:
Trim(both | leading | trailing <remstr> from str)
Removes both leading and trailing spaces from the string str.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg (1):

Eg (2):

Eg (3):

Eg (4):

 Substring() / mid() /substr()


Syntax:
Substring(str,m,n)
(or)
Mid(str,m,n)
 Returns the specified number of characters from the middle of the string.
 There are 3 arguments.
 The first argument is the source string.
 The second argument is the position of first character to be displayed.
 The third argument is the number of characters to be displayed.
 If the third argument is missing, then starting from the position specified, the
rest of the string is returned.
 It is also possible to use a negative value for the second argument i.e. position
(pos). In such a case, the beginning of the substring is pos characters from the
end of the string

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

Eg (1):

(or)

(or)

Eg (2):

(or)

Eg (3):

Eg (4):

 ASCII()
Syntax:
ASCII(str)

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 Returns the ASCII value of the leftmost character of the string str.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 Returns 0 if str is an empty string.
 Returns NULL if str is NULL.
Eg (1):

Eg (2):

Eg (3):

Eg (4):

3) Date Functions:
Date and Time functions allow us to perform many types of tasks on Date type data and will returns
the result as date or number.
The default date format in MySQL is YYYY-MM-DD.
 CURDATE() / CURRENT_DATE()
Syntax:
Curdate()
UNIT-2:Database Query using SQL
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
(OR)
Current_date()

 Returns the current date in YYYY-MM-DD format


 Eg:

(or)

 NOW()
Syntax:
Now()

 Returns the current date and time in 'YYYY -MM-DD HH:MM:SS' or


YYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a
string or numeric context.
 Now() returns a constant time that indicates the time at which the statement began
to execute.
Eg (1):

Eg (2):

 SYSDATE()
Syntax:
Sysdate()

 Returns the current date and time in 'YYYY -MM-DD HH:MM:SS' or


YYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a
string or numeric context.
UNIT-2:Database Query using SQL
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 Sysdate() returns the time at which it executes.

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
 This differs from the behavior for NOW(), which returns a constant time that
indicates the time at which the statement began to execute.
Eg (1):

Eg (2):

 DATE()
Syntax:
Date()
 Extracts the date part of a date or datetime expression.
Eg (1):

Eg (2):

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

 MONTH()
Syntax:
Month(date);

 Returns the numeric month from the date passed, in the range 0 to 12.
 It returns 0 for dates such as '0000 - 00-00' or '2010-00-00' that have a zero
month part.
Eg (1):

Eg (2):

Eg (3):

 YEAR()
Syntax:
Year(date)
 Returns the year for date passed in the range 0 to 9999.
 Returns values like 1998, 2010, 1996 and so on.
Eg:

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

 DAY()
Syntax:
Day(date)
 Returns the day for date passed in the range 0 to 31.
Eg (1):

Eg (2):

 DAYNAME()
Syntax:
Dayname(date)
This returns day name of the given date like Monday, Tuesday etc .
Eg:

 MONTHNAME()
Syntax:
monthname(date)
This returns month name of the given date like J anuary, February etc .
UNIT-2:Database Query using SQL
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
Eg:

 DAYOFWEEK()
Syntax:
Dayofweek(date)
Returns the day of week in number as 1 for Sunday, 2 for Monday and so on.
Eg:

 DAYOFMONTH()
Syntax:
DayofMonth(date);

 Returns the day of the month in the range 0 to 31.


Eg:

 DAYOFYEAR()
Syntax:
Dayofyear(date);
 Return the day of the year for the given date in numeric format in the range 1 to
366.
Eg:

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
SAMPLE QUESTIONS
1) A table “TRAINS” in a database has degree 3 and cardinality 8.What is the number of rows and columns in it?
2) Sarthak, a student of class XI created a table “Class”. Grade is one of the columns of this table. To find the
details of students whose grade have not been entered, he wrote the following MYSQL query, which did not
give the desired result.
SELECT * FROM CLASS WHERE GRADE=”NULL”
3) Write an SQL query to create a table STUDENT with the following structure

Field Type
Roll_No Integer
Names Varchar(20)
Stream Varchar(10)
Date_of_Admission Date

4) In a database BANK, there are two tables with a sample data given below

TABLE EMPLOYEE
ENo EName Salary Zone Age Grade Dept
1 Mona 70000 East 40 A 10
2 Muktar 71000 West 45 B 20
3 Nalini 60000 East 26 A 10
4 Sanaj 65000 South 36 A 20
5 Surya 58000 North 30 B 30

TABLE DEPARTMENT
Dept DName HOD
10 Computers 1
20 Economics 2
30 English 5
Write the SQL queries for the following:
i) To display Eno,EName,Salary and corresponding DName of all the employees whose age is between 25 and
35(both values inclusive)
ii) To display DName and corresponding EName from the tables DEPARTMENT and EMPLOYEE(HINT HOD of
the DEPARTMENT table should be matched with ENo of the EMPLOYEE table for getting the desired result).
iii)To display EName, Salary, Zone and Income Tax (Note Income Tax to be calculated as 30% of salary) of all
the employees with appropriate column headings.
5) There is a column Salary in a table EMPLOYEE. The following two statements are given different outputs.
What may be the possible reason?
SELECT COUNT(*) FROM EMPLOYEE;
SELECT COUNT (Salary) FROM EMPLOYEE;

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
6) Consider the table EXAM given below.Write the commands in MYSQL for( i) to (iv) and output for (v) to (vii)
TABLE EXAM
No. Name Stipend Subject Average Division
1 Sharon 400 English 38 THIRD
2 Amal 680 Mathematics 72 FIRST
3 Vedant 500 Accounts 67 FIRST
4 Shakeer 200 Informatics 55 SECOND
5 Anandha 400 History 85 FIRST
6 Upasana 550 Geography 45 THIRD
i) To list the names of those students,who have obtained Division as FIRST in ascending order of Name.
ii) TO display a report listing Name,Subject and Annual Stipend received assuming that the Stipend colum n
has monthly Stipend.
iii) To count the number of students,who have either Accounts or Informatics as Subject.
iv) To insert a new row in the table EXAM.
6,‟Mohan‟,500,‟English‟,73,‟SECOND‟
v) SELECT AVG(Stipened) FROM EXAM WHERE Division=‟THIRD”;
vi) SELECT COUNT(DISTINCT Subject) FROM EXAM;
vii) SELECT MIN(Average) FROM EXAM WHERE Subject=‟English‟;
7) Differentiate between alternate key and candidate key?
8) Write a MYSQL command to create the table PAYMENT, where structure is given below
Field Name Data Type Size Constraint
Loan_Number Integer 4 Primary Key
Payment_Number Varchar 3
Payment_Date Date
Payment_Amount Integer 8 Not Null

9) While creating the table statement last week MS. Sharma forgot to include the column
Game_Played. Now write a command to insert the Game_Played column with VARCHAR data type
and size 30 into the student table?
10) Mr. Amith while creating a Table he forgot to give primary key on a column. Now he wrote a
statement to add primary key column in the table but the statement is displayin g error. What may
be the possible reason for it?
11) Which SQL statement is used to make operations done permanent during the Transaction in a
Database?
12) What are the differences between DELETE and DROP commands of SQL?
13) What is the purpose of primary key? How it is different from candidate key
14) Name the MYSQL functions that extract first characters and last characters
15) Consider the following Garment table. write SQL commends for (i) to (v) and output for (iv) to (viii)
TABLE: GARMENT
GCode Description Price QTY Readydate.
10023 Pencil Skirt 1150 25 2010-12-19
10001 Formal skirt 1250 15 2010-01-12
10012 BABY TOP 750 20 2009-04-09
10009 Informal pant 1500 35 2012-12-20
10020 Frock 850 20 2012-01-01

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
10089 Slacks 750 10 2010-10-31

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

(i) To display the details of all the Garments whose price is more than 1200
(ii) To display the details of all the Garments which has Readydate between 2010 -12- 31
and 2010-10-31 (both incentives)
(iii) To display Description and Price of all the Garments whose description ends with pant
(iv) To display the highest price of the Garments
(v) To display all the details of the Garments in descending order of Readydate whose
Quantity less than 15
(vi) SELECT COUNT (DISTNCT DESCRPTION) FROM GARMENTs ;
(vii) SELECT DESCRIPTION FROM GARMENTS WHERE QTY IN (10,15);

16) What is the purpose of following MySql command:


SELECT MAX(salary) FROM EMP;
17) A table sales has following information:
TABLE : SALES
SALES COMMISSION
60000 560
35000 450
23000 400
8000 NULL
i) Select Avg (Commission) for Sales;
ii) Select Count (Commission) from Sales;
18) If a database “Student” exists, which Mysql command helps you to start working in that database?
19) Pooja created a table in Mysql. Later she found that there should have been another column in the
table. Which command should she use to add another column to the table?
20) Predict the output of the Query
SELECT ROUND (65. 95, 1) , Truncate (65.95, 1);
21) Write a SQL Command to View the Constraints of DEPARTMENT Table.
22) A Student of class XII has created a Table “PARTICIPANTS”.
CITY is one of the Columns in the Table . She wants to find out the names of Participants who have not
come from Mumbai, Delhi, Ahmadabad
SELECT NAME FROM PARTICIPANTS WHERE CITY HAS NOT Mumbai, Delhi, Ahmadabad;
Find out the errors and rewrote the above Query
23) Rewrite the following SQL statement after correcting error(s). Underline the corrections made.
INSERT IN EMP (EMPNO, SALES) VALUE (100, 20078.50) ;
24) Consider the table Doctor given below, write command in SQL for (i) to (iv) and output for (v) to (viii).
Table : DOCTOR
ID Name Dept Gender Experience ConstFee
201 R K Nath ENT M 12 300
457 Mahavir Singh Skin M NULL 500
365 M asthana Medicine F 9 250
221 V S nag ENT M 3 150
122 P Sinha Nephro F NULL 200
UNIT-2:Database Query using SQL
INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)
110 JP Pandey Cardiology M 9 500

UNIT-2:Database Query using SQL


INFORMATICS PRACTICES (065) - XII BY G SIVA PRASAD (PGT)

i) To display name of all doctors who are in Medicine having more than 10 years of
experience.
ii) To display the different departments.
iii) To display minimum consultation fee of female doctors.
iv) To display name and department of male doctors who has no experience.
v) SELECT AVG (ConstFee) FROM Doctor WHERE NOT Gender=‟F‟;
vi) SELECT Count(Experience) From Doctor;
vii) SELECT Name, Experience FROM Doctor WHERE id BETWEEN 100 AND 200;
viii) SELECT SUM(ConstFee), MAX(Experience) FROM Doctor;

25) Consider the following table. Write SQL Queries for (i) to (v) and output for (vi) to (viii)
TABLE NAME : ORDER_DETAILS

i) To display all Sales person names by eliminating duplicate values


ii) To display order ID, Salesperson in descending order of order Amount
iii) To display all details of orders whose orderAmount between 30000 and 50000
iv) To display average order sssAmount for each salesperson
v) To display all the details of order details whose name not begins with „R‟
vi) SELECT MAX (ORDAMOUNT) FROM ORDER_DETAILS;
vii) SELECT COUNT (*) FROM ORDER_DETAILS ;
viii ) SELECT * FROM ORDER_DETAILS WHERE ORDDATE >‟2015-10-01‟;
26) In SQL LIKE Clause uses a wildcard character to specify the Sequence of zero, one or
more character. Which wildcard character it is ?

UNIT-2:Database Query using SQL

You might also like