Chapter-9 (SQL)
Chapter-9 (SQL)
The Structured Query Language (SQL) is the most popular query language
used by major relational database management systems such as MySQL,
ORACLE, SQL Server, etc.
SQL is easy to learn as the statements and are not case sensitive. SQL
provides statements for defining the Structure of the data, manipulating
data in the database, declaring constraints and retrieving data from the
database in various ways, depending on our requirements.
Data type of an attribute indicates the type of data value that an attribute
can have. It also decides the operations that can be performed on the data
of that attribute. Commonly used data types in MySQL
www.gkmvkalyan.blogspot.com Page 1
Constraints
Constraints are the certain types of restrictions on the data values that an
attribute can have. They are used to ensure correctness of data. However, it
is not mandatory to define constraints for each attribute of a table.
SQL commands are crucial for managing databases effectively. SQL can
perform various tasks like creating a table, adding data to tables, dropping
the table, modifying the table, set permission for users.
www.gkmvkalyan.blogspot.com Page 2
CREATE Database
From the listed databases, we can select the database to be used. In order
to use the GKDatabase, the following SQL statement is required.
www.gkmvkalyan.blogspot.com Page 3
CREATE Table
Syntax:
• Data type specifies the type of data that an attribute can hold.
www.gkmvkalyan.blogspot.com Page 4
Describe Table
We can view the structure of an already created table using the DESCRIBE
statement or DESC statement.
Syntax:
DESC tablename;
ALTER Table
Let us create one more table by name gkresult table and we will add a
primary key to the column name statsno:
www.gkmvkalyan.blogspot.com Page 5
Now we will add primary key constraints to statsno as shown below.
Syntax:
In the below screen you can see primary key constraint is added to the
column statsno.
• Data types and size of referenced and referencing attributes must be the
same.
www.gkmvkalyan.blogspot.com Page 6
Now we will add foreign key to regno column of gkresult table
Syntax:
Syntax:
www.gkmvkalyan.blogspot.com Page 7
(D) Remove an attribute
syntax:
We can change data types of the existing attributes of a table using the
following ALTER statement.
Syntax:
www.gkmvkalyan.blogspot.com Page 8
(F) Remove primary key from the table
Using ALTER, we can remove primary key constraint from the table.
Syntax:
Using ALTER, we can add UNIQUE key to a column. UNIQUE which means no
two values in that column should be the same.
Syntax:
www.gkmvkalyan.blogspot.com Page 9
DROP Statement
Example:
Example:
When we create a table, only its structure is created but the table has no
data. To insert records in the table, INSERT statement is used. Also, table
records can be deleted or updated using DELETE and UPDATE statements.
www.gkmvkalyan.blogspot.com Page 10
INSERTION of Records
Syntax:
Use the above insert command to insert the below data as shown in the
below table.
If we want to insert values only for some of the attributes in a table. Then
we shall specify the attribute names in which the values are to be inserted
using the following syntax of INSERT INTO statement.
Syntax:
www.gkmvkalyan.blogspot.com Page 11
SQL for Data Query
The SQL statement SELECT is used to retrieve data from the tables in a
database and is also called a query statement.
SELECT Statement
The SQL statement SELECT is used to retrieve data from the tables in a
database and the output is displayed in tabular form.
Syntax:
FROM tablename
WHERE condition;
Here, attribute1, attribute2, ... are the column names of the table tablename
from which we want to retrieve data. The FROM clause is always written with
SELECT clause as it specifies the name of the table from which data is to be
retrieved. 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:
www.gkmvkalyan.blogspot.com Page 12
The below query retrieves data only from Regno and Name.
www.gkmvkalyan.blogspot.com Page 13
QUERYING using Database OFFICE
Let us consider the relation ‘GKEMP’ as shown in Table and apply the SELECT
statement to retrieve data:
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:
www.gkmvkalyan.blogspot.com Page 14
(C) Distinct Clause
By default, SQL shows all the data retrieved through query as output.
However, there can be duplicate values. The SELECT statement when
combined with DISTINCT clause, returns records without repetition.
www.gkmvkalyan.blogspot.com Page 15
(D) WHERE Clause
The WHERE clause is used to retrieve data that meet some specified
conditions. In the GKEMP table, more than one employee can have the same
salary.
www.gkmvkalyan.blogspot.com Page 16
The following query selects details of all the employees who work in the
Maths or Chemistry department.
The IN operator compares a value with a set of values and returns true if the
value belongs to that set. The above query can be rewritten using IN
operator as shown below:
The following query selects details of all the employees those who are not
working in Maths or Chemistry department
www.gkmvkalyan.blogspot.com Page 17
The following query selects the name salary of all those employees who are
earning salary between 3000 and 5000 (both values inclusive).
The following query selects details of all the employees in ascending order of
their salaries.
www.gkmvkalyan.blogspot.com Page 18
The following query selects details of all the employees in descending order
of their salaries.
For example: 5 + NULL = NULL because NULL is unknown hence the result is
also unknown.
The following query selects details of all those employees who have not been
given a bonus. This implies that the bonus column will be blank.
www.gkmvkalyan.blogspot.com Page 19
(H) Substring pattern matching
For example, to find out names starting with “T” or to find out pin codes
starting with ‘60’. This is called substring pattern matching.
SQL provides a LIKE operator that can be used with the WHERE clause to
search for a specified pattern in a column.
The LIKE operator makes use of the following two wild card characters:
The following query selects details of all those employees whose name starts
with 'A'.
The following query selects details of all those employees whose name ends
with 'R', and gets a salary more than 2000.
www.gkmvkalyan.blogspot.com Page 20
The following query selects details of all those employees whose name
consists of exactly 3 letters and starts with any letter but has ‘KL’ after that.
Updation and deletion of data are also part of SQL DML Commands.
Data Updation
Syntax:
UPDATE tablename
WHERE condition;
Consider the below table GKStud, Combination column has null value(no
value)
www.gkmvkalyan.blogspot.com Page 21
Let us make all the students belong to PCMC combination.
www.gkmvkalyan.blogspot.com Page 22
Data Deletion
Note:
if you are deleting primary key table first, you will get error, so delete
child table(Foreign key) table first and later you can delete primary
key table.
www.gkmvkalyan.blogspot.com Page 23
Functions in SQL
www.gkmvkalyan.blogspot.com Page 24
a) Math Functions
Three commonly used numeric functions are POWER(), ROUND()
and MOD(). Along with syntax and example it is explained in below
table.
b) String Functions
String functions can perform various operations on alphanumeric
data which are stored in a table. They can be used to change the
case (uppercase to lowercase or vice-versa), extract a substring,
calculate the length of a string and so on.
String functions is explained with example in the below table.
www.gkmvkalyan.blogspot.com Page 25
Continued…
www.gkmvkalyan.blogspot.com Page 26
www.gkmvkalyan.blogspot.com Page 27
(C) Date and Time Functions
There are various functions that are used to perform operations on date and
time data. Some of the operations include displaying the current date,
extracting each element of a date (day, month and year), displaying day of
the week and so on. Date and Time functions is explained with example in
the below table.
www.gkmvkalyan.blogspot.com Page 28
2. Multiple Row Functions (Aggregate Functions)
Aggregate functions are also called Multiple Row functions. These functions
work on a set of records as a whole and return a single value for each
column of the records on which the function is applied.
The below table describes some of the aggregate functions along with the
example. Note that column must be of numeric type.
Max(), Min(), Avg(), Sum(), Count() and Count(*) are Aggregate functions.
www.gkmvkalyan.blogspot.com Page 29
GROUP BY Clause in SQL
www.gkmvkalyan.blogspot.com Page 30
Consider the below table GKStaff.
The following SQL statement lists the number of Staff in each city:
FROM GKStaff
GROUP BY City;
The following SQL statement lists the number of staffs in each city,
sorted in ascending order:
www.gkmvkalyan.blogspot.com Page 31
mysql> SELECT COUNT(staffid), City
FROM gkstaff
GROUP BY City
ORDER BY COUNT(staffid);
The below GROUP BY query is to group the staff based on their age.
In this example, let us group the staffs by their age and calculate the
average salary for each age using the following query.
www.gkmvkalyan.blogspot.com Page 32
mysql>SELECT AGE, AVG(SALARY) AS AVG_SALARY
FROM gkstaff
GROUP BY AGE;
Operations on Relations
www.gkmvkalyan.blogspot.com Page 33
The set operation is mainly categorized into the following:
a) Union operation
b) Intersection operation
c) Set difference or Minus operation
Note that, these operations can only be applied if both the relations have the
same number of attributes and corresponding attributes in both tables have
the same data types. These three operations are binary operations as they
work upon two tables.
a) Union operation
The SQL UNION operator combines the results of two or more SELECT
statements into one result set. By default, UNION removes duplicate
rows, ensuring that the result set contains only distinct records. It is
represented by symbol U.
www.gkmvkalyan.blogspot.com Page 34
b) Intersection operation
Intersect operation is used to get the common tuples/rows from two
tables and is represented by symbol ∩.
www.gkmvkalyan.blogspot.com Page 35
Cartesian Product (X)
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’.
Note that both relations are of degree 3. The cardinality of relations GKStud1
and GKStud2 is 5 and 3 respectively. Applying cartesian product on these
two relations will result in a relation of degree 6 and cardinality 15 as show
in below table.
www.gkmvkalyan.blogspot.com Page 36
From the all possible combinations of tuples of relations DANCE and MUSIC
display only those rows such that the attribute name in both have the
same value.
www.gkmvkalyan.blogspot.com Page 37
mysql> create table gkorders(orderid int(4) primary key,
customerid int(3) references gkcustomer(customerid),
orderdate date);
www.gkmvkalyan.blogspot.com Page 38
a) Using condition in WHERE clause
www.gkmvkalyan.blogspot.com Page 39
c) Explicit use of NATURAL JOIN clause
The output of above queries shown in above tables has a
repetitive column Ucode having exactly the same values. This
redundant column provides no additional information. There is an
extension of JOIN operation called NATURAL JOIN which works
similar to JOIN clause in SQL but removes the redundant
attribute. This operator can be used to join the contents of two
tables if there is one common attribute in both the tables.
www.gkmvkalyan.blogspot.com Page 40
It is clear from the output that the result of this query is same as
that of queries written in (a) and (b) except that the attribute
Customerid.
www.gkmvkalyan.blogspot.com Page 41
www.gkmvkalyan.blogspot.com Page 42
Syntax:
Data Updation
www.gkmvkalyan.blogspot.com Page 43
We may need to make changes in the value(s) of one or
www.gkmvkalyan.blogspot.com Page 44