sql unit - 1
sql unit - 1
Database Concepts: Introduction to database concepts and its need, Database Management System.
Database Management System : A database management system (DBMS) is a software that can be used to create,
manage, store and manage databases. Some examples of open source and commercial DBMS include MySQL,
Oracle, PostgreSQL, SQL Server, Microsoft Access, MongoDB etc.
RDBMS:
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all
modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in
RDBMS is stored in database objects called tables. A table(Relation) is a collection of related data entries
and it consists of columns and rows.
What is MySQL?:
MySQL is a open source Relational Database Management System. MySQL is very fast reliable and flexible Database
Management System. It provides a very high performance and it is multi threaded and multi user Relational
Database management system.
MySQL Features
1. MySQL is an open source RDBMS application.
2. MySQL command line tool is very powerful and can be used to run SQL queries against database.
3. It is fast, realiable and more cheaper than other DBMS softwares.
4. MySQL is compatible and portable.
5. MySQL has a client server archtecture.
6. MySQL has a strong data security layer.
7. MySQL is easy to manage.
Classification of SQL statements
SQL provides many different types of commands used for different purposes. SQL can be divided into following
parts:
1. Data Manipulation Language (DML) commands
2. Data Definition Language (DDL) commands.
1. DML commands: A DML is a language that enables users to access manipulated data as organized by the
appropriate data model.
● SELECT - extracts data from a database (DQL).
● DELETE- removes fields/rows from a table.
● UPDATE- change data in a table.
● INSERT INTO - inserts new data into a database
2. DDL commands: The DDL commands, as the name suggests, allow you to perform tasks related to data
definition. The DDL part of SQL permits database tables to be created or deleted. The most important DDL
statements in SQL are:
● CREATE DATABASE - creates a new database
● ALTER DATABASE - modifies a database
● CREATE TABLE - creates a new table
● ALTER TABLE - modifies a table
● DROP TABLE - deletes a table
MySQL Data Types
In MySQL there are three main data types: text, number, and Date/Time.
Text types:
Data type Description
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The
fixed size is specified in parenthesis. Can store up to 255 characters
VARCHAR(size) Holds a variable length string. The maximum size: up to 255 characters. Note: If you put a
greater value than 255 it will be converted to a TEXT type
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string, allowing for a fixed decimal point. The maximum number
of digits may be specified in the size parameter. The maximum number of digits to
the right of the decimal point is specified in the d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from a negative to positive
value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number.
Date types:
Data type Description
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the
Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM- DD
HH:MM:SS Range is from '1970-01-01 00:00:01' UTC to '2038-01- 09
03:14:07' UTC
The empty table can be filled with data with the INSERT INTO statement.
The INSERT INTO Statement (DML)
The INSERT INTO statement is used to insert a new row in a table. SQL
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted: INSERT INTO
table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Persons" table:
P_Id LastName FirstName Address City
Halwani Oneer
Siddiqui Taimur
Prasad Kishan
SELECT * Example
Now we want to select all the columns from the "Persons" table. We use the following SELECT statement: SELECT *
FROM Persons; // The asterisk (*) is a quick way of selecting all columns
Output:
P_Id LastName FirstName Address City
Surat
Srinagar
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion/condition. SQL
WHERE Syntax
SELECT <column_name(s)>
FROM <table_name>
WHERE <column_name> operator <value>
= Equal
IN If you know the exact value you want to return for at least one of the columns
Note: In some versions of SQL the <> operator may be written as !=
The AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition. The AND operator displays a
record if both the first condition and the second condition is true. And OR operator displays a record if either the
first condition or the second condition is true.
AND Operator Example
SELECT * FROM Persons
WHERE FirstName='Taimur' AND
LastName='Siddiqui'
The result-set will look like this:
P_Id LastName FirstName Address City
Wildcard Description
ALTER UPDATE
1. It is a DDL Command It is a DML command.
2. It is used to add, modify, remove the column. It is used to modify the data stored in rows
3. E.g. ALTER TABLE Student ADD Marks INT; E.g. UPDATE Student SET Class=”XII” WHERE
Name=”Kavita”;
Differences between DDL and DML
E.g. CREATE TABLE, ALTER TABLE, DROP E.g. INSERT , UPDATE, DELETE, SELECT
TABLE etd.
Functions in SQL
Function :
A function is a predefined command set that performs some operations and returns the single value. A function
can have single, multiple or no arguments at all.
SQL Functions: SQL supports two kinds of functions:
1. Single Row Functions : These functions work on a single value at a time and produce a result for each value
they operate on. They may obtain the data as an argument or from the value of a column of a table specified as
an argument.
2. Multirow Functions/Aggregate Functions : These functions work on a group of values at a time but
produce a single result for each group they work on.
Single Row Functions : Single row functions can be further classified into various types. Few of them are :
a. Text Function:
b. Math Functions
c. Date and Time functions
We will be using the following table to demonstrate various functions in the coming text.
Table : emp
Empid Ename Job Sal DeptNo Date_of_joining
a. Text/String Functions : Text functions generally perform an operation on a string input value and
return a string or numeric value. Various text function are described below:
i. Ucase()/Upper() : Converts given string to Uppercase. Examples : Select
upper('Apple Is reD');
Output:
APPLE IS RED
Select Upper(‘f/kvschool/2001-12/LIB/22’);
Output
F/KVSCHOOL/2001-12/LIB/22
ii. Initcap() :
iii. Lcase()/Lower(): Converts given string to lowercase. Examples : Select
lower('Apple Is reD');
Output:
apple is red
Select lcase(‘f/kvschool/2001-12/LIB/22’);
Output:
f/kvschool/2001-12/lib/22’
iv. Length() : It counts the number of characters in a given string. It includes all upper and lower
case alphabets, digits, spaces and other special characters.
Examples:
Select length('Hockey is our national game'); output:
27
Select (‘f/kvschool/2001-12/LIB/22’);
Output:
25
v. Left() : It extracts N characters from the left side of a given String. Syntax
left(String, No of Characters to be extracted)
Examples :
Select Left ( ‘Orange’, 3)
Output :
Ora
Note: If the number of characters extracted are more than the length of the string, the left function returns the
same string without any leading or trailing spaces.
left(Ename,4)
Jack
Vikr
vi. Right() : It extracts N characters from the right side of a given String. Syntax:
right(String, No of Characters to be extracted)
Examples :
Select Right ( ‘Orange’, 3)
Output :
nge
Note: if the number of characters extracted are more than the length of the string, the right function returns
the same string without any leading or trailing spaces.
Note :
● proving length/ no of characters to be extracted is optional. In case it is not provided, the
function extracts all characters from the given position till the end of the string.
● If the second argument (start) is negative, it will count from the right side of the string.
● No. of characters can not be negative, it will return empty string if supplied.
mid(date_of_joining, 6,2)
10
06
viii. Instr() : returns the position of the first occurrence of a string in another string.
Example:
SELECT INSTR(‘CBSE Exam’, ‘E’);
INSTR(‘CBSE Exam’, ‘E’)
Note: if the substring is not found in the main string, Instr() returns 0.
ix. Ltrim() : Removes Spaces on the left side of a given string.
Select Ltrim(‘### India Shining##‘)
Note: assume there are three spaces before and two spaces after India Shining respectively.
Spaces have been represented by #
###India Shining
xi. Trim() : Removes both leading (left) and Trailing (right ) Spaces from a given string.
Select Trim### India Shining## ‘)
13
b. Math Functions:
i. power(x,y)/pow(x,y): It returns the x raised to the power of y (xy).
select power(2,3);
power(2,3)
8
select pow(-1,5);
pow(-1,5)
-1
select pow(-1,4);
pow(-1,4)
1
select pow(10,-2);
pow(10,-2)
0.01
Note: Here the concept of negative power will be applied.
select pow(144, 1/2);
pow(144,
Note: 1/2)
Alternate way of finding square root.
12
ii. Round(N,D) : Rounds number N upto given D no. of digits (by default D=0, if not specified) select
round(4534.9767);
round(4534.9767)
4535
select round(4534.9767,0);
round(4534.9767,0)
4535
select round(4534.9767);
round(4534.9767)
4535
select round(4534.97378778,2);
round(4534.97378778,2)
4534.97
select round(4534.97578778,2);
round(4534.97578778,2)
4534.98
select round(4534.997,2);
round(4534.997,2)
4535.00
select round(4534.997,4);
round(4534.997,4)
4534.9970
Select round(4534.997,-1);
round(4534.997,-1)
4530
select round(4584.997,-2);
round(4584.997,-2)
4600
c. Date Functions():
i. Now() : returns the current date and time, as "YYYY-MM-DD HH:MM:SS" (string)
Select Now();
+ +
| now() |
+ +
| 2022-10-19 18:31:32 |
+ +
Assuming that the current date in the system is 19-Oct-2022 and time is 6:31pm
ii. Date() : returns the date part(yyyy-mm-dd) of date time value supplied as argument.
select date('1978-02-23 00:00:10')
+ +
| date('1978-02-23 00:00:10') |
+ +
| 1978-02-23 |
+ +
iii. Day() : returns the day part of the date/date-time value supplied as argument.
select day('1978-02-23');
+ +
| day('1978-02-23') |
+ +
| 23 |
+ +
iv. Month() : returns the month part for a given date/date-time (a number from 1 to 12).
select month('1978-02-23');
+ +
| month('1978-02-23') |
+ +
| 2|
+ +
v. Year() : returns the year part for a given date/date-time.
select year('1978-02-23');
+ +
| year('1978-02-23') |
+ +
| 1978 |
+ +
vi. MonthName() : returns the name of the month for a given date/date-time.
select monthname('2017-09-14');
+ +
| monthname('2017-09-14') |
+ +
| September |
+ +
vii. DayName() : returns the Day Name corresponding to date/date-time value supplied as
argument.
select dayname('2017-09-14');
+ +
| dayname('2017-09-14') |
+ +
| Thursday |
+ +
Group by Functions/Multi-Row functions/Aggregate Functions :
i. SUM() : it returns the sum of values of a numeric column.
● It gives the arithmetic sum of all the values present in a particular column.
● It can take only one argument.
● NULL values are not included in the calculations. Select
Sum(Sal) from emp;
Sum(sal)
7050
ii. COUNT(): the COUNT() function returns the number of rows that matches a specified criterion.
● Takes only one argument, which can be a column name or *.
● Count doesn’t count Null Values.
● Count(*) counts the number of rows in the table. A row is counted even if all the values in the row are
null values.
Select Count(*) from emp;
Count(*)
Count(job)
5
Note: The number of values in job column was 6 but it return 5 as one of the value is null
iii. AVG() : the average value of a numeric column.
● It gives the arithmetic average of all the values present in a particular column.
● It can take only one argument.
● NULL values are not included in the calculations. If in a column there are 7 values out of which 2
are NULL, to calculate the average, MySQL will divide the sum of 5 NOT NULL values by 5.
Select avg(sal) from emp;
avg(sal)
1410.0000
1600
Vikram
1988-10-22
Group by :
The GROUP BY Clause is utilized in SQL with the SELECT statement to organize similar data into groups. It
combines the multiple records in single or more columns using some functions.
select deptno, sum(sal) from emp group by deptno;
deptno sum(sal)
10 2700
20 2800
30 1550
Having clause : The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
10 2700
20 2800
WHERE Clause is used to filter the records from the HAVING Clause is used to filter the records from
table or used while joining more than one the groups based on the given condition in the
table.Only those records will be extracted who are HAVING Clause. Those groups who will satisfy
satisfying the specified condition in WHERE the given condition will appear in the final result
clause.
WHERE clause is used before GROUP BY HAVING clause is used after GROUP BY
Order by :The ORDER BY clause is used to sort the query result-set in ascending or descending order. It sorts the
records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Select empid, Ename, deptno from emp order by empid;
INTERSECTION
The INTERSECTION of these two relations can be created as :-
Select * from A intersect select * from B;
+------+----------+------+
| Rollno | name | age |
+------+----------+------+
| 102 | kushagra | 18 |
+------+----------+------+
1 row in set (0.00 sec)
A JOIN is a query through which we can extract queries from two or more tables. It means, it combines rows
fro two or more tables. Rows in one table can be joined to rows in another table according to common
values existing in corresponding columns.
EQUI-JOIN
In an EQUI-JOIN operation, the values in the columns are being joined and compared through equality
operator(=) is called Equi join. All the columns in the tables being joined are included in the results,
Syntax :
3 Hina 3 Delhi
4 Megha 2 Delhi
6 Gouri 2 Delhi
Select * from Record;
id class city
9 3 Delhi
10 2 Delhi
12 2 Delhi
Example
SELECT student.name, student.id, record.class, record.city
FROM student, recordWHERE student.city = record.city;
name id class city
Hina 3 3 Delhi
Megha 4 3 Delhi
Gouri 6 3 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
A non-equi join is a join condition containing something other than an equality operator.
Syntax:
SELECT * FROM table_name1, table_name2 WHERE table_name1.column [> | < | >= | <= ]
table_name2.column;
Example –
SELECT student.name, record.id, record.city FROM student, record WHERE Student.id < Record.id ;
Output :
name id city
Hina 9 Delhi
Megha 9 Delhi
Gouri 9 Delhi
1
Hina Delhi
0
name id city
1
Megha Delhi
0
1
Gouri Delhi
0
1
Hina Delhi
2
1
Megha Delhi
2
1
Gouri Delhi
2
NATURAL JOIN
The result of an equi-join contains two identical columns. Here by restarting the query, we can
eliminate one of the two identical columns. It is known as Natural Join.
We can also join two tables using the natural join using NATURAL JOIN clause.
CARTESIAN PRODUCT
The cartesian product is a binary operation and is denoted by (x). The degree of new relation is the sum of
the degrees of two relations on which cartesian product is operated. The number of tuples, of the new
relation is equal to the product of the number of tuples, of the two relations on which cartesian product is
performed.
e.g. if A = {1, 2, 3} and B = {a, b, c}, find A x B.
A x B = ((1, a), (1, b), (1, c), (2, a), (2, b), (2, c), (3, a), (3, b), (3, c))
In sql, the CROSS JOIN or CARTESIAN JOIN is used to produce the cartesian product of two tables.