SQL I
SQL I
SQL I
Today, we are living in an era of BIG DATA so there is a need to store the data efficiently. There
are software or programs used to store computerized databases being used almost everywhere.
Such as Airforce, Police force, Medical Researches, Entertainment uses various computerized
databases for different purposes. In schools, library stores details of all their books in a
computerized database. When we want to know if a book is in stock, we cannot only look it up, but
can also check when it is due to be returned. The database also records details of all the borrowers,
what books they currently have borrowed and when they are due back.
To create and maintain a database on a computer, we need a database program or software, called
a Database management system, or DBMS. Database Management System is a software that
enables users to create and maintain databases. The popular DBMSs are MySQL, PostgreSQL,
Microsoft Access, Oracle, Microsoft SQL Server, DB2 and Sybase.
Relational Database
In the database named Learner shown below, the data is organized into separate tables. Once the
tables have been set up, a relationship can be created to link them together. Such a database that
stores data in separate tables that are related through the use of a common column is called a
Relational database.
RDBM S Terminology
1. Domain
It is pool of values or the collection (set) of possible values from which the value for a column
is derived.
Relational Databases store data or information in tables. A table is similar to a spreadsheet where
data is stored in rows and columns. A table refers to a two-dimensional representation of data using
rows and columns. The tables in a database are generally related to each other to facilitate efficient
management of the database. Interrelated tables also reduce the chances of errors in the database.
For example, consider the following table named Customer with details about customers:
2. Record - The horizontal subset of the Table is known as a Row/Tuple. Each row represents a
record, which is a collection of data about a particular entity such as person, place or thing.
3. Field - The vertical subset of the Table is known as a Column/Attribute. The term field is also
often used for column. Each column has a unique name and the content within it must be of the
same type.
6. Primary Key: The group of one or more columns used to uniquely identify each rowof a relation
is called its Primary Key.
When you got admission in the school, you were given an Admission number. The Admission
number assigned to you was not assigned to any other student of your school (it is unique). When
patients go to a hospital, each patient is given a unique patient number. When you go to open an
account in the bank, you are given a unique account number. Admission number, Patient number,
Account number are all examples of Primary key. A primary key is a field in a table that is unique
for each record. Every database table should have a column or a group of columns designated as
the primary key. The value this key holds should be unique for each record in the table. Some more
examples of Primary key are: Accession Number of a Book in the Book table, Employee ID of an
employee in the Employee Table, Item Code of an item in the Stock table, Flight Number of a flight
in the Flight Master Table, etc.
7. 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.
In a table, there may be more than one field that unique ly identifies a record. All such fields are
called candidate keys. A Candidate key is an attribute (or set of attributes) that uniquely identifies a
row. A Primary Key is one of the candidate keys. A table may have more than one candidate keys
but definitely has one and only one primary key.
8. Alternate Key: A candidate key of a table which is not selected as the primary key is called its
Alternate Key.
Example: Consider the following Table, RollNo and Admission_no both may be used to uniquely
identify each row in this Table, so both are candidate keys.
Candidate keys which are not made primary key are called Alternate keys. In the above example,
if we use one of the candidate keys, say, Admission_No as the Primary Key, the other Candidate
Key RollNo is the Alternate Key and vice-versa.
9. Foreign Key: A primary key of a base table when used in some other table is called as Foriegn
Key.
For example: Table Employee has columns : EMPID, EMPNAME, ADDRESS, CONTACT NO,
DEPTID. And the table Department has columns : DEPTID, DNAME, CITY. Then the DEPTID
column of the Employee table will be known as Foreign Key because it is declared as Primary Key
in the Department table.
Note : The primary key column and the foreign key column must have the same data type and size.
Introduction to MySQL:
Characteristics of MySQL:
Since MySQL is released under an open-source license, it does not require any cost or payment
for its usage. Any one can download this software from specific location on Internet. If you want to
download, follow the following steps. The step for two most popular OS platform, Windows and
Linux are discussed here.
https://www.mysql.com/downloads/
Scroll the above screen and Click on the "Download" button for the Community Server and choose
from the list of supported platforms (i.e., operating systems that it will run on), which include 32 -bit
and 64-bit Windows, several different Linux, Solaris, Mac OS X, and a few others.
Creating a Database
Before creating a table we will first create a database.To create a database we will give
CREATE DATABASE command.
Once the above mentioned statement gets executed, a database with the name School is created
on system. You may give any name of the database . Now to open the database to work USE
statements are required. ! Semicolon is standard way to end SQL statement
Using a database
Syntax: USE <databasename>;
mysql> USE School;
Database Changed
Creating a Table
After creating a database, the next step is creation of tables in the database. For this CREATE
TABLE statement is used.
Syntax:
CREATE TABLE <TableName>(<ColumnName1> <Data Type1>,
<ColumnName2> <Data Type2>
Create a simple table named Learner with only two columns RollNo and Name in the School
database.
To do this, enter the following statement:
mysql> CREATE TABLE Learner
(RollNo INTEGER,
Name VARCHAR(25));
Query OK, 0 rows affected (0.16 sec) will be displayed.
If table Student already exists in database school, then the error message "Table Student already
exists" is displayed. Give meaningful name to a table. If a table will store information about students,
name it STUDENT. Table names and column names are not case sensitive. For example,
STUDENT is treated the same as STUDENT or student. Each column in the table is given a unique
name. In the example above the column names are Rollno, Name etc. This doesn't mean each
column that is named has to be unique within the entire database. It only has to be unique within
the table where it exists. Also notice that the names do not use any spaces. When naming tables
and columns be sure to keep it simple with letters and numbers. Spaces and symbols are invalid
characters except for underscore(_). Column names like first_name, last_name, email are valid
column names.
Constraint Purpose
Primary Key Sets a column or a group of columns as a
primary key of the table. Therefore, NULLs
and Duplicate values in this column are not
accepted.
NOT NULL Makes sure that NULLs are not accepted in
the specified column.
FOREIGN KEY Data will be accepted in this column, if the
same data value exists in a column in
another related table. This other related
table name and column name are specified
while creating the foreign key constraint.
UNIQUE Make sure that duplicate values in the
specified column are not accepted.
Recall that the primary key of a table is a column or a group of columns that uniquely identifies a
row of the table. Therefore no two rows of a table can have the same primary key value. Now
suppose that the table Shoes is created with the following statement:
CREATE TABLE Shoes (Code CHAR(4), Name VARCHAR(20), type VARCHAR(10),size INT(2),
cost DECIMAL(6,2), margin DECIMAL(4,2),Qty INT(4), PRIMARY KEY (Code));
To create a table Bills with the combination of columns Order_No and Cust_Code as the primary
key, we enter the statement:
Contrary to our expectation, we get an error (Multiple primary key defined) with this statement. The
reason is that MySQL interprets this statement as if we are trying to create two primary keys of the
table - Order_Num, and Cust_code. But a table can have at most one primary key. To set this
combination of columns a primary key we have to enter the statement as follows:
Let us now check the table structure with the command: DESC bills;
The table structure is as shown below:
+-----------------+---------------------+----------+--------+-----------+------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+----------+--------+-----------+------------+
| Order_Num | INT(4) | NO | PRI | 0 | |
| cust_code | VARCHAR(4) | NO | PRI | | |
| bill_Date | date | YES | | NULL | |
| Bill_Amt | DECIMAL(8,2) | YES | | NULL | |
+-----------------+---------------------+----------+--------+-----------+------------+
NOT NULL CONSTRAINT
Many times there are some columns of a table in which NULL values should not be accepted. We
always want some known valid data values in these columns. For example, we cannot have an
order for which the customer code is not known. It means whenever we enter a row in the orders
table, corresponding customer code cannot be NULL.
Similarly while entering records in the Shoes table, we have to mention the Shoe size, it cannot be
set NULL. There may be any number of such situations.
While creating a table we can specify in which columns NULLs should not be accepted as follows:
Now if we try to enter a NULL in the specified column, MySQL will reject the entry and give an
error.
The table structure also includes the constraints, if any. Therefore, when we use DESC
command,we are shown the table structure as well as constraints, if any. A constraint is shown
beside the column name on which it is applicable. E.g., the statement:
DESC Shoes;
displays the table structure as follows:
+--------+-----------------------+-------+-------+---------+---------
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+---------+-----+---------+--------
| Code | CHAR(4) | NO | PRI | NULL | |
| Name | VARCHAR(20) | YES | | | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | |0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+---------+--------------------+--------+-------+---------+--------
After execution of the above ALTER TABLE statement, the Games column is added and
a NULL value is assigned to all the rows in this column.
Now, suppose we want to change the newly added Games column to hold integers(in
place of character data) using ALTER TABLE statement:
mysql> ALTER TABLE Student MODIFY games INTEGER;
To delete a column of a table the ALTER TABLE statement is used with Drop clause.
If we create a table without specifying any primary key, we can still specify its primary key by
ALTER TABLE command. Suppose we have created the Shoes table without specifying any
Primary key, then later we can enter the statement as follows:
This will set Code as the primary key of the table. But if the Code column already contains some
duplicate values, then this statement will give an error. In MySQL, it is also possible to change the
primary key column(s) of a table. Suppose, in the Shoes table, instead of Code, we want to set
the combination of 'Name' and 'Size' as the primary key. For this first we have to DROP the
already existing primary key (i.e Code) and then add the new primary key (i.e., Name and Size).
The corresponding statements are as follows:
Now if we see the table structure by DESC Shoes; statement, it will be shown as follows:
+--------+-----------------------+------+--------+-----------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+------+--------+-----------+-------+
| Code | CHAR(4) | NO | | NULL | |
| Name | VARCHAR(20) | NO | PRI| | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | PRI | 0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+--------+-----------------------+------+---------+-------+-----------+
In MySQL, it is not possible to add or drop NOT NULL constraint explicitly after the table creation.
But it can be done using the MODIFY clause of ALTER TABLE command. As an example,
suppose we don't want to accept NULL values in bill_date column of bills table, we can issue the
statement:
ALTER TABLE bills MODIFY bill_date DATE NOT NULL;
Although any column of a table can be removed, MySQL puts the restriction that a primary key
column can be removed only if the remaining, primary key columns, if any, do not contain any
duplicate entry. This can be understood more clearly with the help of following example:
The Name and Size columns of the Shoe table constitute its primary key. Now if we drop the Name
column from the table, Size will be the remaining Primary Key column of the table. Therefore,
duplicate entries in the Size column should not be allowed. To ensure this, before removing the
Name column from the table, MySQL checks that there are no duplicate entries present in the Size
column of the table. If there are any, then the statement trying to remove the Name column from
the table will result in an error and the Name column will not be removed. If there are no duplicate
entries in the Size column, then the Name column will be removed. Similar will be the case with the
Name column, if we try to remove the Size column. But there won't be any problem if we try to
remove both the primary key columns simultaneously with one ALTER TABLE statement as follows:
ALTER TABLE Shoes DROP name, DROP size;
DM L COMMANDS :
DML stands for Data Manipulation Language. DML commands are used for retrieving, inserting,
modifying/updating or deleting data from a relation. is used to manipulate the data in the relation.
Following are the DML commands :
- INSERT
- SELECT
- UPDATE
- DELETE
INSERT command is used in various ways to insert values within a table. Following points should
be kept in mind while inserting records in a relation. :
- Numeric values may be entered as numerals
- string must be enclosed in single/ double quotes
- -mm-
- NULL value should be entered as NULL without any quotes. NULL value means blank value in
the table.
Values entered in the column must be in same order as given in the list enclosed with table name
in INSERT command.
For example :
Above command will enter the values only in specified columns of the table. Remaining columns
of the table will have a NULL value inserted by default.
If we have to enter a record with values for all the attributes(columns) then list of columns is not
specified with table name in the command then we need to enter value for all the attributes of the
table. The order of values must be same as the order of attributes specified in the table
For example :
INSERT INTO STUDENT VALUES(1,'ABHISHEK','NARULA','M', '1998-10-05',98);
It can be observed that the numeric values can be inserted directly while string and date is
entered enclosed within single quotes.
The order of entering the values must be same as the order of attributes defined in the relation.
A select statement can also be used with the insert command provided, the result of select
query is of the same order as the given list of columns
Main purpose after storing the data in a table is to retrieve the data for generating various reports.
Data from tables can be retrieved/ fetched using Select Command.
+----------+
| r no |
+----------+
| 1|
| 2|
The output displayed the data in same order as the order of columns given in the command.
* is the wild card character ( means ALL) that is used to display names of all the columns.
DISTINCT ( Displaying values without repetition)
If a column contains repeated values then the select statement gives the result set with repeated
values like if a command is given to display DISTINCT keyword is used to eliminate repeated
values
Consider the query:
Select marks from student:
mysql> select marks from student;
+---------+
| marks |
+---------+
| 98 |
| 92 |
| 95 |
| 94 |
| 93 |
| 84 |
| 84 |
| NULL |
+---------+
8 rows in set (0.00 sec)
For example :
+---------+
| marks |
+---------+
| 98 |
| 92 |
| 95 |
| 94 |
| 93 |
| 84 |
| NULL |
+---------+
7 rows in set (0.00 sec)
A number of keywords and clauses are used with SELECT statement to retrieve data as per the
requirement. These are discussed below:
ALL
Keyword ALL when used with Select statement is used to display values of all columns in the row.
It displays even the duplicate values.
WHERE Clause
Where clause is used to fetch data based on a criteria/ condition. Criteria can be given using an
expression. Table has many records in it and it is not always desir able to show all the records every
time. At times only certain set of specific rows need to be displayed. based on the criteria. Keyword
WHERE is used for selection of rows with select statement. We can also say that WHERE clause
is used to filter records. It is used to fetch only those records that satisfy a specified criterion.
Syntax:
WHERE <condition>;
For example if we wish to display records of students who have a got marks greater thn we will 90
then following command needs to be entered:
Operator Description
+ For addition of values
- Subtraction of values
* For finding the product of values
/ Divide
% Modulo operator. Returns the remainder
Following set of examples show the use of arithmetic operators for performing calculations :
Arithmetic operators are used to perform calculations over the numeric fields of a table.
For example, if we wish to see the result after adding 10 marks for activity in each record then
what would be the total then this can also be done using expression as shown below:
Another example: in case to view the salary of employees after adding a bonus of 10 percent to
the salary , following command may be used:
Relational Operators
Relational Operators compare two values and gives a result in the form of true of false. Every row
is filtered using the relational operator in the expression in where clause. Given below are the
relational operators used in MySQL alongwith their functions:
These operators are of great help to fetch data on a particular criteria. If we need to display data
For example:
mysql> select fname from student where gender ='f' and marks>90;;
AND operator can be used to fetch records satisfying in a range of values as shown in the
example given below:
mysql> select fname, lname, marks
FROM student
WHERE marks >= 92 and marks<= 95;
In the above query, the output will display records of all the students who have marks greater than
or equal to 92 and less than or equal to 95. Similar result can be obtained using keyword
BETWEEN .
BETWEEN operator
Keyword BETWEEN is used to fetch data based on a range of values on a column. The result set
includes the values of the upper and lower bound given in the range.
For example , following command displays firstname, last name and marks of the students whose
marks are from 92 to 95;
mysql> select fname, lname, marks
FROM student
WHERE marks BETWEEN 92 and 95;
Output will be :
OR operator returns True if either one of the conditions is True.
For example : to view list of all the sports coach who give coaching for either football or hockey;
Coachname Game
NOT Operator
Not is used for negation. It returns the result set that is opposite to the given condition
For example : following command displays name and salary of employees whose salary is not
less than 50000.00
Following command displays name and zone of employees who are not in north zone:
HANDLING NULL Values
IS operator is used to match NULL value in the expression.
For example, following command is to display the records with NULL values in column edesig
from table employee
mysql>select empname, zone from employee where zone IS NULL;
IS operator is used to compare equality with NULL whereas IS NOT may be used for comparing
the values not equal to NULL;
mysql> select empname, zone from employee where zone IS NOT NULL;
Note: the operations = NULL and <> NULL are not defined!
To make the output more user friendly we can give customized heading to column name in the
select command. Keyword AS is used to give column alias in a set of single quotes as shown in
the example below:
For example :
from Student;
Remember : the name of column if for the query only and no changes are made in the original
table.
IN operator
IN operator is very useful when we wish to fetch selected records which match a certain set of
values. Suppose we wish to display list of students who have score marks 88,90,92,95 , then IN
operator can be used as follows :
IN operator helps in removing multiple conditions. Without IN operator the above command would
have been as follows :
mysql>select fname , marks from student
where marks=88 OR marks=92 OR marks=95;
LIKE keyword
LIKE is used for pattern matching and is very useful. Following characters used for applying
pattern matching:
% percent symbol is used to match none or more characters
_ underscore character is used to match occurrence of one character in the string
output is:
Following command displays list of students whose name starts and ends with a specified lett er.
Notice that in case no record matches the given pattern then the query returns empty set on
execution.
Similarly many more patterns may be given as follows :
matches any string with exactly four characters
matches any s
ORDER BY
The result set fetched by the query can be displayed in sorted order. The sorting can be on the
basis of any particular column from the table using ORDER BY clause.
Syntax is :
Following commands are used to display records in sorted order of marks of students
mysql>select fname, lname, marks
from STUDENT
order by marks;
It can be observed that the output is displayed in the sorted order of marks. NULL value is
displayed first and records are displayed in ascending order.
Following command displays the records in descending order of fname:
mysql> select fname, lname
from STUDENT
ORDER BY fname DESC;
ORDER By clause can be used to sort the records on the basis of two columns also.
Following command displays the result based on order of marks and then on fname.
mysql> select fname, lname , marks from STUDENT
ORDER BY marks ASC, fname DESC;
It can be observed from the above figure that the records are d isplayed in ascending order of
marks and for records having similar value of marks are sorted on the basis of descending order
of fname.
UPDATE
UPDATE command is used to modify data of records within the table. It is a type of DML and is
used to make changes in the values entered in the table :
Syntax: `
UPDATE <table name>
[WHERE <condition> ];
The command can be used to update one or more columns and WHERE clause is used for
modifying the records that matches a criteria.
For example:
Now with the help of update command we can add values to date of birth and marks for
Deepakshi :
Again the records as displayed and we can see that the changes have been made:
DELETE
Earlier the table was having 12 records and after the execution of the command it has 11 rows. It
may be noticed that record of Saurabh Makania has been removed.
POINTS TO REMEMBER :
EXERCISE
1. Write a short note on MySQL.
2.Mention features of a DBMS.
3.What is the difference between DBMS and RDBMS?
4.List some features of MySQL.
5.How is Primary Key different from Candidate Key?
6.Define the key(s) used in MySQL.
7.State the similarity and difference between the Primary Key, Candidate Key, Alternate Key
and Foreign Key
8.Which statement is used to select a database and make it current?
9.How is a database related to table(s)?
10Write SQL statement to view names of all the tables contained in the current database
11.In a database there is a table Cabinet. The data entry operator is not able to put NULL in a
column of Cabinet? What may be the possible reason(s)?
12. In a database there is a table Cabinet. The data entry operator is not able to put duplicate
values in a column of Cabinet? What may be the possible reason(s)?
13. Do Primary Key column(s) of a table accept NULL values?
14. There is a table T1 with combination of columns C1, C2, and C3 as its primary key? Is
it possible to enter:
a. NULL values in any of these columns?
b. Duplicate values in any of these columns?
15. At the time of creation of table X, the data base administrator specified Y as the
Primary key. Later on he realized that instead of Y, the combination of column P and
16should have been the primary key of the table. Based on this scenario, answer the
following questions:
a. Is it possible to keep Y as well as the combination of P and Q as the primary key?
b. What statement(s) should be entered to change the primary key as per the
requirement.
17. Does MySQL allow to change the primary key in all cases? If there is some special
case, please mention.
18. What are the differences between DELETE and DROP commands of SQL?
19Which statement is used to modify data in a table?
A. CHANGE
B. MODIFY
C. UPDATE
D. SAVE AS
20. Which SQL statement is used to delete data from a table?
A. DELETE
B. DROP
C. TRUNCATE
D. REMOVE
Lab exercises:
Consider the following table named "GYM" with details about Fitness products
being sold in the store.
Table Name : GYM
PrCode stores Codes of Products
PrName stores names of Products
(UnitPrice is in Rs.)