0% found this document useful (0 votes)
2 views44 pages

Chapter-9 (SQL)

Chapter 9 discusses Structured Query Language (SQL), which is widely used for managing relational databases. It covers SQL commands for creating, altering, and deleting databases and tables, as well as manipulating and querying data. The chapter also explains data types, constraints, and various SQL functions for data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Chapter-9 (SQL)

Chapter 9 discusses Structured Query Language (SQL), which is widely used for managing relational databases. It covers SQL commands for creating, altering, and deleting databases and tables, as well as manipulating and querying data. The chapter also explains data types, constraints, and various SQL functions for data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter 9: Structured Query a Language (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 types and constraints in MySQL

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.

SQL Commands are mainly categorized into five categories:

DDL – Data Definition Language


DML – Data Manipulation Language
DQL – Data Query Language
TCL – Transaction Control Language
DCL – Data Control Language

www.gkmvkalyan.blogspot.com Page 2
CREATE Database

To create a database, we use the CREATE DATABASE statement as shown in


the following syntax:

CREATE DATABASE databasename;

To create a database called GKDatabase, we will type following command at


mysql prompt.

A DBMS can manage multiple databases on one computer. Therefore, we


need to select the database that we want to use. To know the names of
existing databases, we use the statement SHOW DATABASES.

From the listed databases, we can select the database to be used. In order
to use the GKDatabase, the following SQL statement is required.

Once the database is selected, we can proceed with creating tables or


querying data.

www.gkmvkalyan.blogspot.com Page 3
CREATE Table

After creating a database GKDatabase, we need to define relations in this


database and specify attributes for each relation along with data type and
constraint (if any) for each attribute. This is done using the CREATE TABLE
statement.

Syntax:

CREATE TABLE tablename(

Attributename1 datatype constraint,

attributename2 datatype constraint,

attributenameN datatype constraint);

It is important to observe the following points with respect to the CREATE


TABLE statement:

• The number of columns in a table defines the degree of that relation,


which is denoted by N.

• Attribute name specifies the name of the column in the table.

• Data type specifies the type of data that an attribute can hold.

• Constraint indicates the restrictions imposed on the values of an attribute.


By default, each attribute can take NULL values except for the primary key.

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

After creating a table, we may realise that we need to add/remove an


attribute or to modify the datatype of an existing attribute or to add
constraint in attribute. In all such cases, we need to change or alter the
structure (schema) of the table by using the alter statement.

(A) Add primary key to a relation

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:

ALTER TABLE tablename ADD PRIMARY KEY(Columnname);

In the below screen you can see primary key constraint is added to the
column statsno.

(B) Add foreign key to a relation

Following points need to be observed while adding foreign key to a relation:

• The referenced relation must be already created.

• The referenced attribute(s) must be part of the primary key of the


referenced relation.

• 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:

ALTER TABLE tablename ADD FOREIGN KEY(attribute name)


REFERENCES referenced_tablename(attribute name);

(C) Add an attribute to an existing table

Sometimes, we may need to add an additional attributes(columns) in a


table. It can be done using the ADD attribute statement as shown in the
following

Syntax:

ALTER TABLE tablename ADD attribute name DATATYPE;

Now we can see a new column combination is added at last.

www.gkmvkalyan.blogspot.com Page 7
(D) Remove an attribute

Using ALTER, we can remove attributes(Columns) from a table.

syntax:

ALTER TABLE tablename DROP attribute;

In the below screen, you can see combination column is removed.

(E) Modify datatype of an attribute

We can change data types of the existing attributes of a table using the
following ALTER statement.

Syntax:

ALTER TABLE tablename MODIFY attribute DATATYPE;

The size of name is increased to 25 from 20.

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:

ALTER TABLE tablename DROP PRIMARY KEY;

ALTER TABLE Employee DROP empno;

(Note: I have taken table name has Employee)

(G) Add constraint UNIQUE to an existing attribute.

Using ALTER, we can add UNIQUE key to a column. UNIQUE which means no
two values in that column should be the same.

Syntax:

ALTER TABLE tablename ADD UNIQUE (attributename);

ALTER TABLE Employee ADD UNIQUE(mobileno);

(Note: I have taken table name has Employee)

www.gkmvkalyan.blogspot.com Page 9
DROP Statement

Sometimes a table in a database or the database itself needs to be removed


permanently from the system, We can use a DROP statement. However, one
should be very cautious while using this statement as it cannot be recovered
back.

Syntax to drop a table:

DROP TABLE tablename;

Example:

DROP TABLE Employee.

Syntax to drop a database:

DROP DATABASE databasename;

Example:

DROP DATABASE GKDATABASE;

Note: Using the DROP statement to remove a database will ultimately


remove all the tables within it.

SQL for data Manipulation

Data Manipulation using a database means either insertion of new data,


removal of existing data or modification of existing data in the database.

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

INSERT INTO statement is used to insert new records in a table.

Syntax:

INSERT INTO tablename VALUES(value1, value2,....);

Here, value 1 corresponds to attribute1, value2 corresponds to attribute2


and so on.

Note: Text and date values must be enclosed in ‘ ’ (single quotes).

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:

INSERT INTO tablename (column1, column2, ...)

VALUES (value1, value2, ...);

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:

SELECT attribute1, attribute2, ...

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.

The below query retrieves data from regno and name


where Gender is M (Male).

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:

(A) Retrieve selected columns

The following query selects employee numbers of all the employees:

mysql> SELECT EmpNo FROM GKEMP;

(B) Renaming of 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 GKEMP;

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.

For example, while retrieving a department name from GKEMP relation,


there can be duplicate values as many employees are assigned to the same
department. To select unique department number for all the employees, we
use DISTINCT as shown below:

mysql> SELECT DISTINCT Deptname FROM GKEMP;

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.

Following query gives distinct salaries of the employees working in the


department number D01:

mysql> SELECT * FROM GKEMP WHERE Deptname='Maths';

In the above example, = operator is used in the WHERE clause. Other


relational operators (<, <=, >, >=,!=) can be used to specify such
conditions. The logical operators AND, OR, and NOT are used to combine
multiple conditions.

mysql> SELECT EmpNo, Ename, Salary FROM GKEMP

WHERE EmpNo >103 AND Salary>=2000;

www.gkmvkalyan.blogspot.com Page 16
The following query selects details of all the employees who work in the
Maths or Chemistry department.

mysql >SELECT * FROM GKEMP

WHERE Deptname = 'Maths' OR Deptname = 'Chemistry';

(E) Membership operator IN

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:

mysql> SELECT * FROM GKEMP

WHERE Deptname IN ('Maths', 'Chemistry');

The following query selects details of all the employees those who are not
working in Maths or Chemistry department

mysql> SELECT * FROM EMPLOYEE

WHERE Deptname Not IN ('Maths', 'Chemistry');

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).

mysql> SELECT Ename, Salary FROM GKEMP

WHERE Salary BETWEEN 3000 AND 5000;

(F) ORDER BY Clause

ORDER BY clause is used to display data in an ordered form with respect to a


specified column. By default, ORDER BY displays records in ascending order.
To display the records in descending order, the DESC keyword needs to be
written with that column.

The following query selects details of all the employees in ascending order of
their salaries.

mysql> SELECT * FROM GKEMP ORDER BY Salary;

www.gkmvkalyan.blogspot.com Page 18
The following query selects details of all the employees in descending order
of their salaries.

mysql> SELECT * FROM GKEMP ORDER BY Salary DESC;

(G) Handling NULL Values

SQL supports a special value called NULL to represent a missing or unknown


value. The NULL is different from 0 (zero). Also, any arithmetic operation
performed with NULL value gives NULL.

For example: 5 + NULL = NULL because NULL is unknown hence the result is
also unknown.

In order to check for NULL value in a column, we use IS NULL operator.

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.

mysql> SELECT * FROM GKEMP WHERE Bonus IS NULL;

www.gkmvkalyan.blogspot.com Page 19
(H) Substring pattern matching

Many a times we come across situations where we do not want to query by


matching exact text or value. Rather, we are interested to find matching of
only a few characters or values in column values.

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:

• % (per cent)- used to represent zero, one, or multiple characters.

• _ (underscore)- used to represent exactly a single character.

The following query selects details of all those employees whose name starts
with 'A'.

mysql> SELECT * FROM GKEMP WHERE Ename like 'A%';

The following query selects details of all those employees whose name ends
with 'R', and gets a salary more than 2000.

mysql> SELECT * FROM GKEMP

WHERE Ename like '%R' AND Salary > 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.

mysql> SELECT * FROM GKEMP WHERE Ename like '_KL';

Data Updation and Deletion

Updation and deletion of data are also part of SQL DML Commands.

Data Updation

We may need to make changes in the value(s) of one or more columns of


existing records in a table. The UPDATE statement is used to make such
modifications in existing data.

Syntax:

UPDATE tablename

SET attribute1 = value1, attribute2 = value2, .....

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.

Let us make all Female students belong to PCMB combination.

www.gkmvkalyan.blogspot.com Page 22
Data Deletion

DELETE statement is used to delete/remove one or more records from a


table. Consider gkresult table

Note:

While using a DELETE statement to delete specific records in a table


we use WHERE clause. Otherwise, all the records in the table will get
deleted.

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

In this section, we will understand how to use single row functions,


multiple row functions, group records based on some criteria, and
working on multiple tables using SQL.

Differences between Single and Multiple Row Functions

1. Single Row Functions


Single row functions are applied on a single value and return a
single value. It is also known as Scalar functions.

Types of single row functions are:


 Numeric (Math),
 String,
 Date and Time.
a) Math Functions accept numeric value as input and return a
numeric value as a result.
b) String Functions accept character value as input and return
either character or numeric values as output.
c) Date and Time functions accept date and time value as input
and return numeric or string or Date and Time as output.

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.

Consider the below table gkresult with details.

www.gkmvkalyan.blogspot.com Page 29
GROUP BY Clause in SQL

The GROUP BY clause in MySQL is used to arrange identical data in a table


into groups. The GROUP BY statement groups rows that have the same
values into summary rows, like "find the number of customers in each
country".

The GROUP BY statement is often used with aggregate functions (COUNT(),


MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.

www.gkmvkalyan.blogspot.com Page 30
Consider the below table GKStaff.

The following SQL statement lists the number of Staff in each city:

mysql>SELECT COUNT(staffid), 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.

mysql> SELECT AGE, COUNT(Name) FROM gkstaff GROUP BY 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.

Consider the below two tables, GKStud1 and GKStud2.

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 ∩.

c) Set difference or Minus operation


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)

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.

Using two relations in a Query


Cartesian product on two tables
From the previous section, we learnt that application of operator cartesian
product on two tables results in a table having all combinations of tuples
from the underlying tables. In the query, the output was having degree 6
and cardinality 15.

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.

JOIN on two tables


JOIN operation combines tuples from two tables on specified conditions. This
is unlike cartesian product which make all possible combinations of tuples.
While using the JOIN clause of SQL, we specify conditions on the related
attributes of two tables within the FROM clause. Usually, such an attribute is
the primary key in one table and foreign key in another table.
Consider two tables GKCustomer and GKOrders
mysql> create table gkcustomer(customerid int(3) primary key,
customername varchar(20) not null,
city varchar(15) not null);

www.gkmvkalyan.blogspot.com Page 37
mysql> create table gkorders(orderid int(4) primary key,
customerid int(3) references gkcustomer(customerid),
orderdate date);

List the customerid, customername, city, orderid and


orderdate of related tuples of tables gkcustomer and
gkorder.

The given query may be written in three different ways as


given below.

www.gkmvkalyan.blogspot.com Page 38
a) Using condition in WHERE clause

b) Explicit use of JOIN clause


In this query we have used JOIN clause explicitly along with
condition in From clause. Hence no condition needs to be given 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.

The above SQL query using NATURAL JOIN is shown below:

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.

Following are some of the points to be considered while applying


JOIN operations on two or more relations:
• If two tables are to be joined on equality condition on the
common attribute, then one may use JOIN with ON clause or
NATURAL JOIN in FROM clause. If three tables are to be joined on
equality condition, then two JOIN or NATURAL JOIN are required.
• In general, N-1 joins are needed to combine N tables on
equality condition.
• With JOIN clause, we may use any relational operators to
combine tuples of two tables.

www.gkmvkalyan.blogspot.com Page 41
www.gkmvkalyan.blogspot.com Page 42
Syntax:

DELETE FROM table_name WHERE condition;

Data UpdatIon and Deletion.

Updation and deletion of data are also part of SQL Data

Manipulation Language (DML).

Data Updation

www.gkmvkalyan.blogspot.com Page 43
We may need to make changes in the value(s) of one or

more columns of existing records in a table.

The UPDATE statement is used to make such modifications in existing data.

Use the below table for max,min,avg functions

www.gkmvkalyan.blogspot.com Page 44

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy