UNIT-2 DataBases Using SQL - 1
UNIT-2 DataBases Using SQL - 1
Database:
It is an organized collection of data.
Eg: Address book, student register, Dictionary 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.
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.
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
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;
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;
d) SELECT Command:
it is used to retrieve the content from the table in the form either columns/rows.
Consider the following student Table:
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.
`
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‟.
(or)
The NOT IN operator finds rows that do not match in the list.
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‟?
Eg (5): To list all details of the students whose name has exactly 3 character length and second
character should be „a‟?
Eg (2): To list all details of the students who doesn‟t have a date of birth ?
Eg (2): To list all details of the students based on descending order of their marks ?
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
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):
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)
Eg:
(OR)
Upper() / ucase()
Syntax:
Upper(str)
(or)
ucase(str)
(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 :
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.
Eg (2):
Eg (3):
Eg (4):
Eg (1):
(or)
(or)
Eg (2):
(or)
Eg (3):
Eg (4):
ASCII()
Syntax:
ASCII(str)
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()
(or)
NOW()
Syntax:
Now()
Eg (2):
SYSDATE()
Syntax:
Sysdate()
Eg (2):
DATE()
Syntax:
Date()
Extracts the date part of a date or datetime expression.
Eg (1):
Eg (2):
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:
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);
DAYOFYEAR()
Syntax:
Dayofyear(date);
Return the day of the year for the given date in numeric format in the range 1 to
366.
Eg:
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;
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
(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);
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