2. Some MySQL Elements :-The MySQL implementation of SQL has
certain elements that play an important role in defining/querying a
database. These are
1) Literals 2) Datatypes 3) Nulls 4) Comments
1) Literals:- Literals are refer to fixed values. This fixed data value may
be of character type or numeric literal. All character literals are enclosed
in single or double quotation marks. Example ‘Rahul’, ’Ekagra’, ‘8’,
‘305’.
Numbers are not enclosed in any quotation marks. Example 22, 18, 1971
Numeric literals without decimal point are known as integer literals and
with decimal point are known as real literals i.e. 17.0, 3.14, 5.5 etc.
3. 2) Data Types:-Data types are means to identify the type of data and
associated operation for handling it. For example you can add values of
number datatype, but you cannot add values of character datatype. These
are divided in three categories.
i) Numeric ii) Date and Times iii) String
i) Numeric Data Types:
INT A normal sized integer value that can be signed or unsigned range
signed -2147483648 to +2147483648 unsigned 0 to 4294967295
TINYINT Very small integers signed or unsigned range signed -128 to +127
unsigned 0 to 255
SMALLINT A small integers signed or unsigned range signed -32768 to +32767
unsigned 0 to 65535
4. .MEDIUMINT A medium sized integer value that can be signed or unsigned range
signed -8388608 to +8388607 unsigned 0 to 16777215
BIGINT A large integers signed or unsigned range signed -
9223372036854775808 to +9223372036854775807 unsigned 0 to
18446744073709551615
FLOAT(M,D) A floating point number that cannot be unsigned. M total length of
number and D number of decimals. Float(10,2) where 2 is number of
decimals and 10 is total number of digits (including decimal).
Decimal precision can go to 24 places for a Float.
DOUBLE(M,D) A double precision floating point number that cannot be unsigned.
Decimal precision can go to 53 places for a Double.
DECIMAL(M,D) Unpacked floating point number that cannot be unsigned. In
unpacked decimals, each decimal corresponds to one byte.
5. ii) Date and Times Data Types
DATE A date YYYY-MM-DD format. Between 1000-01-01 to 9999-12-31
December 30th 1973 would be stored as 1973-12-30
DATETIME A date and time combination in YYYY-MM-DD HH:MM:SS format
between 1000-01-01 00:00:00 to 9999-12-31 23:59:59. For example
3:30 in the afternoon on December 30th 1973 would be store as 1973-
12-30 15:30:00.
TIMESTAMP A timestamp between midnight, January 1,1970 and sometime in
1938. This look like the DATETIME format only without the hypens
between number 3:30 in the afternoon on December 30th 1973 would
be store as 19731230153000 (YYYYMMDDHHMMSS).
TIME Store time in HH:MMLSS
YEAR(M) Store year in 2 digit or 4 digit format. If the length is specified as 2
(for example year(2)) year can be 1970 to 2069 (70 to 69).
6. iii) String/Text Data Types
CHAR(M) A fixed length string between 1 and 255 characters in length (for
example CHAR(5). By default size is 1 like CHAR
VARCHAR(M) A variable length string between 1 and 255 character in length for
example VARCHAR(25). You must define a length when creating a
VARCHAR field.
BLOB or TEXT A field with maximum length of characters 65335. BLOB (Binary
Large Object) are used to store large amount of binary data, such as
images or other type of files.
TINYBLOB or
TINYTEXT
A BLOB or TEXT column with a maximum length of 255 characters.
You do not specify a length with TINYBLOB or TINYTEXT.
MEDIUMBLOB
or MIDIUMTEXT
A BLOB or TEXT column with a maximum length of 16777215
characters. You do not specify a length with MEDIUMBLOB or
MEDIUMTEXT.
7. Fixed Length Fields:- have fixed length i.e. they occupy fixed number of byte
for every data element they store. These number of bytes are determined by
maximum number of characters the field can store. Not necessary, all data
elements inside the field are of same length, but the field length is
determined by determining maximum possible characters in a data element.
In fixed length fields, some space is always wasted as all data elements do not
use all the space reserved but processing is much simpler in case of fixed
length fields. Example Char(20) always store 20 by in record.
LONGBLOB or
LONGTEXT
A BLOB or TEXT column with a maximum length of 4294967295
characters. You do not specify a length with LONGBLOB or
LONGTEXT.
ENUM An enumeration is a fancy term for list. When defining an ENUM
you are creating a list of items from which the value must be selected
or it can be NULL. e.g ENUM(‘A’,’B’,’C’) the value of this field can
be A,B,C or NULL.
8. Variable Length Fields:- have varied length i.e. field length is determined
separately for every data element inside the field. The number of characters
in the data element become its fields length. Let us consider a field
‘studentName ’ is having data element “Sunita Raj” and “Shalu Harbans”. For
the first data element “Sunita Raj” field length is 10 bytes (1 byte for each
character and space also) and “Shalu Harbans” it is 13 bytes. In variable
length field, there is no wastage of space, but processing is complex in case of
variable length. Example Varchar(n).
iv) Null Values:- If in a column in a row has no value, then column is said to
be null or to contain a null. Nulls can appear in a column of any data type
provided they are not restricted by NOT NULL or PRIMARY KEY integrity
constant. You should use a null value when the actual value is not known or
when a value would not be meaningful.
9. Comment :- Comment is a text that is not executed, it is only for
documentation purpose A comment generally describes the statement’s
purpose with in application.
A comment can appear between any keywords, parameters or punctuation
marks in a statement. You can use comment in 3 ways:
Begin the comment with /* :- Proceed with the text of the comment. This text
can span multiple line. End the comment with */. The opening and
terminating character need not be separated from the text by a space or a line
break.
Begin the comment with -- :- This text can not extend to a new line. End
the comment with new line break.
10. Begin the comment with # :- This text can not extend to a new line. End the
comment with new line break.
Example :-
SELECT ename, sal, job, loc
/* select all employees whose compensation is
greater than 300. */
FROM empl, dept # join two tables
WHERE empl.deptno=dept.dept.no
AND sal > 300; -- this condition is testing whether salary is more than 300 or not.
11. Making Simple Queries
Query means asking some result from DBMS.
Creating Database:-
mysql > create database <database name>;
mysql > create database school;
Here create database is command for creating database and school is database
name.
Accessing Database:-
mysql > use <database name>;
mysql > use school;
Here use is command and school is database name for logging in Mysql.
12. The Select Command:- The select command of SQL lets you make queries on
the database. It is used to retrieve rows from DBMS.
Example:
mysql > SELECT <column name1>, <column name1>, <column …n> FROM
<table name>;
mysql > select name, owner from pet;
Here name and owner is column name and pet is table name. It will show only
name and owner column of pet table.
13. Name Owner Species Sex Birth Death
Fluffy Harold Cat F 1993-02-04 NULL
Claws Gwen Cat M 1994-03-17 NULL
Buffy Harold Dog F 1989-05-13 NULL
Fang Benny Dog M 1990-08-27 NULL
Bowser Diane Dog M 1979-08-31 1995-07-29
Chirpy Gwen Bird F 1998-09-11 NULL
Whistler Gwen Bird NULL 1997-12-09 NULL
Slim Benny Snake M 1996-04-29 NULL
Puffball Diane Hamster F 1999-03-30 NULL
Table Name Pet
14. Name Owner
Fluffy Harold
Claws Gwen
Buffy Harold
Fang Benny
Bowser Diane
Chirpy Gwen
Whistler Gwen
Slim Benny
Puffball Diane
mysql > select name, owner from pet;
Output of query is
15. Name Owner Species
Fluffy Harold Cat
Claws Gwen Cat
Buffy Harold Dog
Fang Benny Dog
Bowser Diane Dog
Chirpy Gwen Bird
Whistler Gwen Bird
Slim Benny Snake
Puffball Diane Hamster
mysql > select name, owner, species from pet;
Output of query is
16. Select all columns:- Use the asterisk (*) sign use without any column name.
mysql > select * from pet;
Name Owner Species Sex Birth Death
Fluffy Harold Cat F 1993-02-04 NULL
Claws Gwen Cat M 1994-03-17 NULL
Buffy Harold Dog F 1989-05-13 NULL
Fang Benny Dog M 1990-08-27 NULL
Bowser Diane Dog M 1979-08-31 1995-07-29
Chirpy Gwen Bird F 1998-09-11 NULL
Whistler Gwen Bird NULL 1997-12-09 NULL
Slim Benny Snake M 1996-04-29 NULL
Puffball Diane Hamster F 1999-03-30 NULL
17. Reordering Column in Query:-
mysql > select species, name, sex from pet; Species Name Sex
Cat Fluffy F
Cat Claws M
Dog Buffy F
Dog Fang M
Dog Bowser M
Bird Chirpy F
Bird Whistler NULL
Snake Slim M
Hamster Puffball F
18. Eliminating Redundant Data (with keyword
DISTINCT) :- The DISTINCT keyword
eliminates duplicate row from the result of
SELECT statement.
mysql> select DISTINCT species from pet;
Selecting from all the rows (ALL
keyword):- If in the place of DISTINCT
you give then the result retains the duplicate
output rows.
mysql> select ALL species from pet;
Species
Cat
Dog
Bird
Snake
Hamster
Species
Cat
Cat
Dog
Dog
Dog
Bird
Bird
Snake
Hamster
19. Viewing Databases :-
SHOW DATABASES sql command show all databases store in server
mysql > show databases;
20. Show Tables:- Show all tables in a database.
mysql > show tables;
Viewing Structure of Table :-
If you want to know the structure of table, you can use DESCRIBE or DESC
command.
mysql > DESCRIBE | DESC <table name>;
Mysql > DESC pet;
21. mysql > desc pet;
Fields Type Null Key Default Extras
Name Varchar(20) Yes NULL
Owner Varchar(20) Yes NULL
Species Varchar(20) Yes NULL
Sex Char(1) Yes NULL
Birth Date Yes NULL
Death Date Yes NULL
22. How to Perform Simple Calculation :-
MySql also provide a dummy table called Dual to provide compatibility with SQL of
other DBMSs. Dual table is a small worktable, which has just one row and one column.
It can be used for obtaining calculation result and also system date.
23. Scalar Expression With Select Field:- If you want to perform simple numeric
computation on the data to put it in a form more appropriate to need, SQL
allows you to place scalar expression constant among the selected fields.
SELECT salesman_name comm * 100 from salesman;
salesman_name Comm * 100
Ajay 13.00
Amit 11.00
Shally 07.00
Isha 15.00
24. Using Column Aliases:- The column that you select in a query can be given a
different name i.e. column alias name for output purpose.
SELECT col name1 as name1, colname2 as name2 from <table name>;
mysql > SELECT name as ‘Pet Name’, sex
from pet;
Pet Name Sex
Fluffy F
Claws M
Buffy F
Fang M
Bowser M
Chirpy F
Whistler NULL
Slim M
Puffball F
25. Handling Nulls:- The empty values are represented as Null in table. When you
list a column having null values, only non-null values are displayed.
mysql > SELECT name , birth, death from pet;
Name Birth Death
Fluffy 1993-02-04 NULL
Claws 1994-03-17 NULL
Buffy 1989-05-13 NULL
Fang 1990-08-27 NULL
Bowser 1979-08-31 1995-07-29
Chirpy 1998-09-11 NULL
Whistler 1997-12-09 NULL
Slim 1996-04-29 NULL
Puffball 1999-03-30 NULL
26. If you want to substitute null with a value in the output, you can use
IFNULL() function.
Syntax IFNULL(<column name>, value_to_be_substitute>)
mysql > SELECT name , birth,
IFNULL( death, ’Alive’)
from pet;
Name Birth IFNULL( death, ’Alive’)
Fluffy 1993-02-04 Alive
Claws 1994-03-17 Alive
Buffy 1989-05-13 Alive
Fang 1990-08-27 Alive
Bowser 1979-08-31 1995-07-29
Chirpy 1998-09-11 Alive
Whistler 1997-12-09 Alive
Slim 1996-04-29 Alive
Puffball 1999-03-30 Alive
27. mysql > SELECT name , birth, IFNULL( death, ’Alive’) AS ‘Died On’ from pet;
Name Birth Died On
Fluffy 1993-02-04 Alive
Claws 1994-03-17 Alive
Buffy 1989-05-13 Alive
Fang 1990-08-27 Alive
Bowser 1979-08-31 1995-07-29
Chirpy 1998-09-11 Alive
Whistler 1997-12-09 Alive
Slim 1996-04-29 Alive
Puffball 1999-03-30 Alive
28. SELECT salesman_name, ’Get the commision’ comm * 100, ‘%’ from
salesman;
salesman_name Get the commission Comm * 100 %
Ajay Get the commission 13.00 %
Amit Get the commission 11.00 %
Shally Get the commission 07.00 %
Isha Get the commission 15.00 %
30. Selecting Specific Rows-Where Clause:- There is no need to view all the row
when only certain rows are needed. SQL enabled you to define criteria to
determine which rows are selected for output. The WHERE clause in
SELECT statement specifies the criteria of rows to be returned. The SELECT
statement with WHERE clause takes the following general form:
SELECT <col name 1>, <col name 2>, <col name n>,
FROM <table name>
WHERE <condition>;
SELECT Item_Name, Price
FROM Items
WHERE Price > 10;
31. Relational Operators:- To compare two values, a relational operator is used.
The result of comparison true or false. There are following relational
operators in SQL.
= Equal to > Greater Than < Less Than
>= Greater Than Equal to >= Greater Than Equal to <> Not Equal to
Logical Operator:- The logical operators OR(||), AND(&&) and NOT(!) are
used to connect search conditions in the WHERE clause.
Example:-
1. To list the employees details having grade ‘E2’ or ‘E3’ from table
employee, logical operator OR will be used as
SELECT ecode, ename, grade, gross
FROM employee
WHERE (grade = ‘E2’ OR grade = ‘E3’);
32. Symbol || may also be used as OR operator in same query
SELECT ecode, ename, grade, gross
FROM employee
WHERE (grade = ‘E2’ || grade = ‘E3’);
2. To list all the employees details having grade as ‘E4’ but with gross < 9000,
logical operator AND will be used.
SELECT ecode, ename, grade, gross
FROM employee
WHERE (grade = ‘E4’AND gross < 9000);
Symbol && may also be used as AND operator.
33. 3. To list all the employees details whose grades are other than ‘G1’, logical
operator NOT will be used as
SELECT ecode, ename, grade, gross
FROM employee
WHERE ( NOT grade = ‘G1’);
Symbol ! may also be used as NOT operator.
The order of precedence is NOT (!) , AND (&&) and OR (||).
34. Write a query to display all the details from pet table for species cat, dog
having the gender as male.
SELECT *FROM pet
WHERE (species = ‘cat’ || species = ‘dog’ ) && sex = ‘m’;
Name Owner Species Sex Birth Death
Claws Gwen Cat M 1994-03-17 NULL
Fang Benny Dog M 1990-08-27 NULL
Bowser Diane Dog M 1979-08-31 1995-07-29
35. Condition Based on a Range:- The BETWEEN operator define a range of
values must fall into make the condition true. The range includes both lower
and upper values.
SELECT *FROM items
WHERE Price BETWEEN 10 AND 15;
ItemNo Item_Name Price
I1 Milk 15.00
I4 Milk Bread 14.00
I6 Cream Biscuit 10.00
I7 Ice Cream 16.00
I9 Namkeen 15.00
36. The operator NOT BETWEEN is reverse of BETWEEN operator, that is the
rows not satisfying the BETWEEN condition are retrieved.
SELECT *FROM items
WHERE Price NOT BETWEEN 10 AND 15;
ItemNo Item_Name Price
I2 Cake 5.00
I3 Bread 9.00
I5 Plain Biscuit 6.00
I8 Cold Drink 8.00
37. Condition Based on a List:- To specify a list of values, IN operator selects
values that match any value in a given list of values.
SELECT *FROM members
WHERE city IN(‘Delhi’, ’Mumbai’, ’Chennai’, ’Bangalore’);
The NOT IN operator finds rows that do not math in the list.
SELECT *FROM members
WHERE city NOT IN(‘Delhi’, ’Mumbai’, ’Chennai’, ’Bangalore’);
38. Condition Based on Pattern Matches:- SQL has a string matching operator
LIKE, for comparisons on character strings using patterns. Patterns are
described using two special wildcard characters :
• Percent ( % ) The % character matches any substring.
• Underscore ( _ ) The _ character matches any character.
Patterns are case sensitive that is upper case character do not match lower case
character or vice-versa.
• ‘San%’ matches any string beginning with ‘San’.
• ‘%idge’ match any string containing ‘idge’ as a substring as ‘Ridge’,
Bridge’, ‘Cartridge’, ‘Ridgeway’.
• ‘_ _ _ _’ matches any string of exact 4 characters.
• ‘_ _ _%’ matches any string of at least 3 characters
39. 1. To list members which are in area with pin codes starting with 13, query is
SELECT firstName, lastName, city
FROM members
WHERE pin LIKE ‘13%’ ;
2. To list names of pets who have names ending with ‘y’ the query would be:
SELECT name
FROM pet
WHERE name like ‘%y’ ;
The keyword NOT LIKE is used to select rows that do not match the specific
pattern of characters.
Name
Fluffy
Buffy
Chirpy
40. 1. Write query to display the names of pets beginning with ‘F’. Use table pet.
SELECT *FROM pet WHERE name LIKE ‘F%’;
2. Write query to display the names of pets having exactly four letter names.
Use table pet.
SELECT *FROM pet WHERE name LIKE ‘_ _ _ _’;
Name Owner Species Sex Birth Death
Fluffy Harold Cat F 1993-02-04 NULL
Fang Benny Dog M 1990-08-27 NULL
Name Owner Species Sex Birth Death
Fang Benny Dog M 1990-08-27 NULL
Slim Benny Snake M 1996-04-29 NULL
41. Searching for NULL:- The NULL value in a column can be searched for in a
table using IS NULL in the WHERE clause. Relational operators like =, <>
etc. can’t be used with NULL.
SELECT empno, empname, job
FROM employee
WHERE depno IS NULL ;
Note :- Non-NULL values in a table can be listed using IS NOT NULL
Write query to display the names of pets who are no more.
SELECT name FROM pet
WHERE death IS NOT NULL ;
Name
Bowser
42. Sorting Result – ORDER BY clause:- You can sort the results of a query in a
specific order by using ORDER BY clause. The sorting can be done either in
ascending or descending order, the default order is ascending. The ORDER
BY clause is used as:
SELECT col name1, col name2, col name n
FROM table name
[WHERE <predicate>]
[ORDER BY <col name>];
To display list of employee in alphabetical order query is
SELECT * FRON employee ORDER BY ename ;
43. To display the list of students having aggregate more than 400 in alphabetical
order of their names.
SELECT name, aggregate FROM student
WHERE aggregate > 400
ORDER BY name ;
To display the list of employees in the descending order of ecode.
SELECT *FROM employee ORDER BY ecode DESC;
To specify the sort order, we may specify DESC of descending or ASC for
ascending order.
SELECT *from employee ORDER BY grade DESC, ecode ASC;
Name Aggregate
Abu Bakar 456
Gurvinder 480
Zubin 412
44. Write a query to display name, age, aggregate of student whose aggregate
between 300 to 400. Order the query in descending order of name.
SELECT name, age, aggregate
FROM student
WHERE aggregate between 300 and 400
ORDER BY name DESC ;
Name Age Aggregate
Simran 15 378
Michelli 15 321
Fatimah 14 400
Anup 15 302
Aanya 16 340
45. MySQL Functions:- A function is a special predefined command set that
performs some operation and return a single value. Function operate on zero,
two or more values that are provided to them. The values that is provided to a
functions are called parameters or arguments.
String Functions:-The string functions of MySQL can manipulate the text in
many ways. Some commonly used functions are:
Function Description Example
1 CHAR() Return the character for
each integer passed
SELECT CHAR(70,65,67,69) o/p FACE
SELECT CHAR(65,66,67.3,68.3) o/p ABCD
2 CONCAT() Return concatenated
string
SELECT CONCAT(name,aggregate) from
student WHERE age=14 ;
3 LOWER() /
LCASE()
Return the argument in
lowercase
SELECT LOWER(‘MR.OBAMA’);
SELECT LOWER(‘Ms. Gandhi’);
46. Function Description Example
4 SUBSTRING()
/ SUBSTR()
Return the substring
as specified
SELECT SUBSTR('ABCDEFG',3,4); o/p CDEF
SELECT SUBSTR('ABCDEFG',-5,4); o/p DEFG
5 UPPER() /
UCASE()
Convert string upper
case
SELECT UPPER(‘hello’); o/p HELLO
SELECT UCASE(‘hello’); o/p HELLO
6 LTRIM() Remove left side
space
SELECT TRIM(‘ hello’); o/p hello
7 RTRIM() Remove right side
space
SELECT TRIM(‘hello ’); o/p hello
8 TRIM() Remove both left and
right side space
SELECT TRIM(‘ hello ’); o/p hello
9 INSTR() Return the index of
first occurrence of
substring
SELECT INSTR(‘CORPORATE’,’OR’); o/p 2
10 LENGTH() Return length of
string
SELECT LENGTH(‘Nizam’); o/p 5
47. Function Description Example
11 LEFT() Return the left most
number of characters
as specified
SELECT LEFT('ABCDEFG',3); o/p ABC
12 RIGHT() Return the right most
number of characters
as specified
SELECT LEFT('ABCDEFG',3); o/p EFG
13 MID() Return the substring
starting from the
specified position
SELECT SUBSTR('ABCDEFG',3,4); o/p CDEF
SELECT MID('ABCDEFG',3,4); o/p CDEF
48. Numeric Functions:-The numeric functions are those functions that accept
numeric values and after performing the required operation, return numeric
values. Some commonly used functions are:
Function Description Example
1 MOD() Return the remainder by
dividing another expression.
SELECT MOD(11,4); o/p 3
SELECT MOD(12,4); o/p 0
2 POWER() /
POW()
Return the value in power SELECT POWER(5,3); o/p 125
3 ROUND() Return the round up value by
specified value.
SELECT ROUND(15.193,1); o/p 15.2
SELECT ROUND(15.193,2); o/p 15.19
4 SIGN() Return sign of value SELECT SIGN(-15); o/p -1
SELECT SIGN(25); o/p 1
5 SQTR() Return square root of number SELECT SQRT(25); o/p 5
6 TRUNCATE() Return truncate decimal place SELECT TRUNCATE(15.79,1) o/p 15.7
SELECT TRUNCATE(15.79,2) o/p 15.79
49. Date and Time Functions:-Date functions are operate on value of date
datatype . Some commonly used functions are:
Function Description Example
1 CURDATE()/
CURRENT_D
ATE()/
CURRENT_D
ATE
Return the current
system date
SELECT CURDATE()
2 DATE() Return month from date SELECT DATE(‘2020-12-21 01:08:35’)
o/p 2020-12-21
3 MONTH() Return month from date SELECT MONTH(‘2020-12-21 01:08:35’) o/p 21
4 YEAR() Return year from date SELECT MONTH(‘2020-12-21’) o/p 2020
5 DAYNAME() Return day name SELECT DAYNAME(‘2021-07-25’) o/p Sunday
6 DAYOFMON
TH()
Return day SELECT DAYOFMONTH(‘2021-07-25’) o/p 25
50. Function Description Example
7 DAYOFWEEK() Return the index
number of week day
SELECT DAYOFWEEK(‘2021-07-25’) o/p 1
8 DAYOFYEAR() Return the day of the
year (1-366)
SELECT DAYOFYEAR(‘2021-07-25’) o/p 206
9 NOW() Return time at which
the function
execution
SELECT NOW() o/p current time
10 SYSDATE() Return current date
and time
SELECT NOW(), SLEEP(2), NOW()