Chapter 9 SQL
Chapter 9 SQL
Structured Query
Language (SQL)
9.1 Introduction
RDBMS allow us to create a database consisting of relations, store,
retrieve and manipulate data on that database through queries.
Ex: MySQL, Microsoft SQL Server, PostgreSQL, Oracle, etc.
1
VARCHAR(n) Specifies character type data of length where n could be
any value from 0 to 65535. But unlike CHAR,
VARCHAR(n) is a variable-length data type. That is,
declaring VARCHAR (30) means a maximum of 30
characters can be stored but the actual allocated bytes
will depend on the length of entered string. So ‘city’ in
VARCHAR (30) will occupy space needed to store 4
characters only.
INT INT specifies an integer value. Each INT value
occupies 4 bytes of storage. The range of unsigned
values allowed in a 4 byte integer type are 0 to
4,294,967,295. For values larger than that, we have
to use BIGINT, which occupies 8 bytes.
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. The supported
range is '1000-01-01' to '9999-12-31'.
9.3.1 Constraints
Constraints are the types of restrictions on the data values that an
attribute can have.
Constraint Description
NOT NULL Ensures that a column cannot have NULL values
where NULL means missing/ unknown/not
applicable value.
UNIQUE Ensures that all the values in a column are
distinct/unique
DEFAULT A default value specified for the column if no value is
provided
PRIMARY KEY The column which can uniquely identify each
row/record in a table.
FOREIGN KEY The column which refers to value of an attribute
defined as primary key in another table.
2
To list the names of existing databases, we use the statement
mysql> SHOW DATABASES.
STUDENT Relation
Attribute Name Data expected to be Data type Constraint
stored
Numeric value consisting PRIMARY
RollNumber INT
of maximum 3 digits KEY
Variant length string of
SName
maximum 20 characters VARCHAR(20) NOT NULL
SDateofBirth Date value DATE NOT NULL
Numeric value consisting of FOREIGN
GUID CHAR (12)
12 digits KEY
GUARDIAN Relation
Attribute Name Data expected to be stored Data type Constraint
3
Numeric value consisting of PRIMARY
GUID CHAR (12)
12 digit Aadhaar number KEY
Variant length string of
GName
maximum 20 characters VARCHAR(20) NOT NULL
Numeric value consisting of NULL
GPhone CHAR(10)
10 digits UNIQUE
Variant length String of size
GAddress VARCHAR(30) NOT NULL
30 characters
ATTENDACE Relation
Attribute Name Data expected to be stored Data type Constraint
PRIMARY
AttendanceDate Date value DATE
KEY*
PRIMARY
Numeric value consisting of KEY*
RollNumber INT
maximum 3 digits FOREIGN
KEY
‘P’ for present and ‘A’ for
AttendanceStatus CHAR(1) NOT NULL
absent
Now let us add the primary key to the ATTENDANCE relation. The
primary key of this relation is a composite key made up of two attributes
- AttendanceDate and RollNumber.
4
mysql> ALTER TABLE ATTENDANCE ADD PRIMARY KEY(AttendanceDate,
RollNumber);
6
9.6.1 SELECT Statement
The SQL statement SELECT is used to retrieve data from the tables
in a database and the output is also displayed in tabular form.
Syntax:
SELECT attribute1, attribute2, ... FROM table_name WHERE condition;
Here, The WHERE clause is optional and is used to retrieve data that meet
specified condition(s).
To select all the data available in a table, we use the following select
statement:
Syntax: SELECT * FROM table_name;
Ex: SELECT * FROM GUARDIAN;
+--------------+--------------+-----------+ ------------------------------------------------- +
| GUID | GName | Gphone | GAddress |
+--------------+--------------+-----------+ ------------------------------------------------- +
| 333333333333 | Danny Dsouza | NULL | S -13, Ashok Village,Daman |
| 444444444444 | Amit Ahuja | 5711492685| G-35, Ashok vihar, Delh |
+--------------+--------------+-----------+ ------------------------------------------------- +
9.6.2 Querying using SELECT
Employee Relation
EmpNo Ename Salary Bonus Deptld
101 Aaliya 10000 234 D02
102 Kritika 60000 123 D01
103 Shabbbir 45000 566 D01
104 Gurpreet 19000 565 D04
105 Joseph 34000 875 D03
106 Sanya 48000 695 D02
107 Vergese 15000 D01
108 Nachaobi 29000 D05
109 Daribha 42000 D04
110 Tanya 50000 467 D05
7
| 109 |
| 110 |
+ +
The following query selects the employee number and employee name of
all the employees: mysql> SELECT EmpNo, Ename FROM EMPLOYEE;
+-------+ ------------- ----+
| EmpNo | Ename |
+-------+ ------------- ----+
| 101 | Aaliya |
| 102 | Kritika |
| 103 | Shabbir |
| 104 | Gurpreet |
| 105 | Joseph |
| 106 | Sanya |
| 107 | Vergese |
| 108 | Nachaobi |
| 109 | Daribha |
| 110 | Tanya |
+-------+ ------------- ----+
(B) Renaming the columns
In case we want to rename any column while displaying the output, it
can be done by using the alias 'AS'. The following query selects
Employee name as Name in the output for all the employees:
mysql> SELECT EName as Name FROM EMPLOYEE;
+ ----------- ------+
| Name |
+ ----------- ------+
| Aaliya |
| Kritika |
| Shabbir |
| Gurpreet |
| Joseph |
| Sanya |
| Vergese |
| Nachaobi |
| Daribha |
| Tanya |
+ ----------- ------+
Select names of all employees along with their annual income (calculated as
Salary*12). While displaying the query result, rename the column EName
as Name
mysql> SELECT EName as Name, Salary*12 as ‘Annual Income’ FROM EMPLOYEE;
+----------+ ----------------- +
| Name | Annual |
| | Income |
+----------+ ----------------- +
| Aaliya | 120000 |
8
| Kritika | 720000 |
| Shabbir | 540000 |
| Gurpreet | 228000 |
| Joseph | 408000 |
| Sanya | 576000 |
| Vergese | 180000 |
| Nachaobi | 348000 |
| Daribha | 504000 |
| Tanya | 600000 |
+----------+ ----------------- +
Note: If an aliased column name has space as in the case of Annual
Income, it should be enclosed in quotes as 'Annual Income'.
mysql> SELECT * FROM EMPLOYEE WHERE Ename like '%a' AND Salary > 45000;
12
mysql> SELECT * FROM INVENTORY;
+--------+--------------+------------+-------------+-------------------+------------------------------------------- +
| CarId | CarName | Price | Model | YearManufacture | Fueltype |
+--------+--------------+------------+-------------+-------------------+------------------------------------------- +
| D001 | Dzire | 582613.00 | LXI | 2017 | Petrol |
| D002 | Dzire | 673112.00 | VXI | 2018 | Petrol |
| B001 | Baleno | 567031.00 | Sigma1.2 | 2019 | Petrol |
| B002 | Baleno | 647858.00 | Delta1.2 | 2018 | Petrol |
| E001 | EECO | 355205.00 | 5 STR STD | 2017 | CNG |
| E002 | EECO | 654914.00 | CARE | 2018 | CNG |
| S001 | SWIFT | 514000.00 | LXI | 2017 | Petrol |
| S002 | SWIFT | 614000.00 | VXI | 2018 | Petrol |
+--------+--------------+-------------------------+------------+ ------------------------------------------------ +
13
(A) Math Functions
Function Description Example with output
POWER(X,Y) Calculates X to the mysql> SELECT POWER(2,3);
can also be power Y. Output:
written as
8
POW(X,Y)
ROUND(N,D) Rounds off number N mysql>SELECT
to D number of ROUND(2912.564, 1);
decimal places. Output:
Note: If D=0, then it 2912.6
rounds off the mysql> SELECT ROUND(283.2);
number to the
Output:
nearest integer.
283
MOD(A, B) Returns the remain mysql> SELECT MOD(21, 2);
der after dividing
Output:
number A by number
1
B.
Ex:
mysql> SELECT ROUND(12/100*Price,1) "GST" FROM INVENTORY;
mysql> SELECT CarId, FinalPrice, MOD(FinalPrice,10000) "Remaining Amount"
FROM INVENTORY;
14
LOWER(string) converts string into mysql> SELECT
OR lowercase. LOWER(“Informatics
LCASE(string) Practices”); Output:
informatics practices
MID(string, pos, Returns a substring of size mysql> SELECT
n) OR n starting from the specified MID(“Informatics”, 3, 4);
SUBSTRING(stri position (pos) of the string. If Output:
ng, pos, n) n is not specified, it returns
form
OR the substring from the
SUBSTR(string, position pos till end of the mysql> SELECT
pos, n) string.
MID(‘Informatics’,7); Output:
atics
LENGTH(string) Return the number of mysql> SELECT
characters in the specified LENGTH(“Informatics”);
string. Output:
11
LEFT(string, N) Returns N number of mysql> SELECT
characters from the left side LEFT(“Computer”, 4); Output:
of the string. Comp
RIGHT(string, N) Returns N number of mysql> SELECT
characters from the right side RIGHT(“SCIENCE”, 3);
of the string. NCE
INSTR(string Returns the position of the mysql> SELECT
, substring) first occurrence of the INSTR(“Informatics”,
substring in the given string. “ma”);
Returns 0, if the substring is Output:
not present in the string.
6
LTRIM(string) Returns the given string mysql> SELECT LENGTH(“
after removing leading white DELHI”), LENGTH(LTRIM(“
space characters. DELHI”));
Output:
+--------+------------------ +
|7 | 5 |
+--------+------------------ +
RTRIM(string) Returns the given string mysql>SELECT LENGTH(“PEN
after removing trailing white “)LENGTH(RTRIM(“PEN “));
space characters. Output:
+--------+------------------ +
|5 | 3 |
+--------+------------------ +
TRIM(string) Returns the given string mysql> SELECT LENGTH(“
after removing both leading MADAM “),LENGTH(TRIM(“
and trailing white space MADAM “));
characters. Output:
+--------+------------------ +
|9 | 5 |
+--------+------------------ +
mysql> SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;
15
mysql> SELECT MID(Phone,3,4) FROM CUSTOMER WHERE CustAdd like
‘%Rohini%’;
+ -------------------------- +
| MID(Phone,3,4) |
+ -------------------------- +
| 1163 |
+ -------------------------- +
mysql> SELECT TRIM(“.com” from Email) FROM CUSTOMER;
16
AVG(column) Returns the average of mysql> SELECT AVG(Price) FROM
the values in the INVENTORY;
specified column.
Output: 576091.625000
SUM(column) Returns the sum of the mysql> SELECT SUM(Price) FROM
values for the specified INVENTORY;
column.
Output: 4608733.00
COUNT(*) Returns the number of mysql> SELECT COUNT(*) from
records in a table. MANAGER;
Note: In order to display +-----------+
the number of records | count(*) |
that matches a +-----------+
particular criteria in the | 4 |
table, we have to use +-----------+
COUNT(*) with WHERE
clause.
COUNT(column) Returns the number of mysql> SELECT * from MANAGER;
values in the specified
+------------- +----------------+
column ignoring the
NULL values. | MNO | MEMNAME |
+------------ +-----------------+
Note: | 1 | AMIT |
In this example, let us
| 2 | KAVREET |
consider a MANAGER
table having two | 3 | KAVITA |
attributes and four | 4 | NULL |
records.
+-----------+ ------------------+
mysql> SELECT COUNT(MEMNAME)
FROM MANAGER;
+---------------------------+
| COUNT(MEMNAME) |
+---------------------------+
| 3 |
+---------------------------+
Single Row Function Multiple row function
1. It operates on a single row at a 1. It operates on groups of rows.
time. 2. It returns one result for a group of
2. It returns one result per row. rows.
3. It can be used in Select, Where, 3. It can be used in the select clause
and Order by clause. only.
4. Math, String and Date functions 4. Max(), Min(), Avg(), Sum(), Count()
are examples of single row and Count(*) are examples of
functions. multiple row functions.
+---------+------+-------+------------+-------------+------+----------+ ------------------------------------------- +
| I00001 | D001 | C0001 | 2019-01-24 | Credit Card | E004 |613248.00 | 73589.64 |
| I00002 | S001 | C0002 | 2018-12-12 | Online | E001 |590321.00 | 70838.52 |
| I00003 | S002 | C0004 | 2019-01-25 | Cheque | E010 |604000.00 | 72480.00 |
| I00004 | D002 | C0001 | 2018-10-15 | Bank Finance| E007 |659982.00 | 79198.84 |
| I00005 | E001 | C0003 | 2018-12-20 | Credit Card | E002 |369310.00 | 44318.20 |
| I00006 | S002 | C0002 | 2019-01-30 | Bank Finance| E007 |620214.00 | 74425.68 |
+---------+------+-------+------------+-------------+------+----------+ ------------------------------------------- +
18
DANCE
+------+--------+-------------- +
| SNo | Name | Class |
+------+--------+-------------- +
|1 | Aastha | 7A |
|2 | Mahira | 6A |
|3 | Mohit | 7B |
|4 | Sanjay | 7A |
+------+--------+-------------- +
MUSIC
+------+---------+-------------- +
| SNo | Name | Class |
+------+---------+-------------- +
|1 | Mehak | 8A |
|2 | Mahira | 6A |
|3 | Lavanya | 7A |
|4 | Sanjay | 7A |
|5 | Abhay | 8A |
+------+---------+-------------- +
DANCE U MUSIC
+------+---------+ ------------- +
| SNo | Name | Class |
+------+---------+ ------------- +
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
+------+---------+ ------------- +
9.10.2 INTERSECT
Intersect operation is used to get the common tuples from two
tables and is represented by symbol ∩.
DANCE ∩ MUSIC
+----+---------+ ------------- +
| SNo| Name | Class |
+----+---------+ ------------- +
| 2 | Mahira | 6A |
| 4 | Sanjay | 7A |
+----+---------+ ------------- +
9.10.3 MINUS
This operation is used to get tuples/rows which are in the first
table but not in the second table and the operation is represented by the
symbol - (minus).
DANCE - MUSIC
+------+---------+-------------- +
| SNo | Name | Class |
19
+------+---------+-------------- +
|1 | Mehak | 8A |
|3 | Lavanya | 7A |
|5 | Abhay | 8A |
+------+---------+-------------- +
9.10.4 Cartesian Product
Cartesian product operation combines tuples from two relations. It
results in all pairs of rows from the two input relations, regardless of
whether or not they have the same values on common attributes. It is
denoted as ‘X’.
The degree of the resulting relation is calculated as the sum of
the degrees of both the relations under consideration. The cardinality of
the resulting relation is calculated as the product of the cardinality of
relations on which cartesian product is applied.
DANCE X MUSIC
+---+-------+-------+------+-----------+--------+
|SNo| Name | Class | SNo | Name | Class |
+---+-------+-------+------+-----------+ ------+
| 1 | Aastha | 7A | 1 | Mehak | 8A |
| 2 | Mahira | 6A | 1 | Mehak | 8A |
| 3 | Mohit | 7B | 1 | Mehak | 8A |
| 4 | Sanjay | 7A | 1 | Mehak | 8A |
| 1 | Aastha | 7A | 2 | Mahira | 6A |
| 2 | Mahira | 6A | 2 | Mahira | 6A |
| 3 | Mohit | 7B | 2 | Mahira | 6A |
| 4 | Sanjay | 7A | 2 | Mahira | 6A |
| 1 | Aastha | 7A | 3 | Lavanya | 7A |
| 2 | Mahira | 6A | 3 | Lavanya | 7A |
| 3 | Mohit | 7B | 3 | Lavanya | 7A |
| 4 | Sanjay | 7A | 3 | Lavanya | 7A |
| 1 | Aastha | 7A | 4 | Sanjay | 7A |
| 2 | Mahira | 6A | 4 | Sanjay | 7A |
| 3 | Mohit | 7B | 4 | Sanjay | 7A |
| 4 | Sanjay | 7A | 4 | Sanjay | 7A |
| 1 | Aastha | 7A | 5 | Abhay | 8A |
| 2 | Mahira | 6A | 5 | Abhay | 8A |
| 3 | Mohit | 7B | 5 | Abhay | 8A |
| 4 | Sanjay | 7A | 5 | Abhay | 8A |
+--+-------+-------+------+---------+ -------------- +
20
As we are using SELECT * in the query, the output will be the Table
having degree 6 and cardinality 20.
22