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

CS2202_MySQL

The document provides an overview of SQL (Structured Query Language) and MySQL, detailing their origins and functionalities. It covers basic MySQL commands for creating databases, users, and tables, as well as data types, integrity constraints, and commands for data manipulation such as insertion, updating, and deletion. Additionally, it explains SQL query structures, including selection, projection, and duplicate elimination.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views105 pages

CS2202_MySQL

The document provides an overview of SQL (Structured Query Language) and MySQL, detailing their origins and functionalities. It covers basic MySQL commands for creating databases, users, and tables, as well as data types, integrity constraints, and commands for data manipulation such as insertion, updating, and deletion. Additionally, it explains SQL query structures, including selection, projection, and duplicate elimination.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 105

SQL

CS2202

1
SQL
• SQL stands for Structured Query Language
• A special purpose programming language designed for managing data in a
relational database system
• Initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in early
1970s
• Initially it was known as SEQUEL and later changed to SQL

2
MySQL
• MySQL is an open source relational database management system
• It runs as a server to provide multi user access to a number of databases
• MySQL is a popular choice of database for use in web application

Some useful links-


https://www.tutorialspoint.com/mysql/index.htm
https://www.w3schools.com/sql/default.asp
https://www.techonthenet.com/mysql/index.php
3
Basic MySQL Commands
• At first, we will learn the commands to do the followings-
– How to create a database?
– How to add users?
– How to create tables?
– How to specify constraints and keys?
– How to insert data into the table?
– How to update the data?
– How to delete data?
– Use of alter table command

4
Create Database
• It is used to create a database
• A name will be associated with it
– Example, if we want to create a database named dblab then we may use the
following command-
– sql> CREATE DATABASE dblab;

 To check all databases, use SHOW databases command


• sql> SHOW DATABASES;

• To create tables under a specific database, then we have to provide USE


databaseName command
– sql> USE dblab;
5
Create user
• It is used to create a new user
• For each user-
– username and password are required
– Example, if we want to create a user named bob with password denver then
we may use the following command-
– sql> CREATE USER ‘bob’@’localhost’ IDENTIFIED BY ‘denver’;
User bob can login locally
where the server is installed
• But the new user has no permission to access anything

6
Granting permission
• Type of permissions
– ALL PRIVILEGES: provides all access
– CREATE: allows to create new tables and databases
– DROP: allows user to delete tables or databases
– DELETE: allows user to delete rows of tables
– INSERT: allows user to insert rows into tables
– SELECT: allows user to use the SELECT command
– UPDATE: allows user to update table rows
– GRANT OPTION: allows user to grant or remove other users’ privileges

7
Grant & Revoke command

• Grant command is used to provide permission


• GRANT [type of permission] ON [database name].[table name] TO
‘*username+’@’localhost’;
– To give access to any database or any table, (*) can be used in place of
database name and table name
• Revoke command is used to revoke permission
• REVOKE [type of permission] ON [database name].[table name] FROM
‘*username+’@’localhost’;

8
Create Table
• To create table under a database name, we have to use CREATE TABLE
command
• For example, to create a table for land entity-
– sql> CREATE TABLE land(
land_id char(10),
address varchar(30),
land_type varchar(15),
region varchar(15));

9
Data types
• Frequently used text data types-
– char(size): holds a fixed length upto 255 character
– varchar(size): holds a variable length upto 255 character
– text: holds a maximum length of 65,535 characters

10
Data types
• Frequently used number data types- – bool:
– int(size): • Zero is considered as false,
nonzero values are
• range from -2147483648 to
considered as true
2147483647 normal. 0 to
4294967295 unsigned – bit(size)
• Size is maximum number of • A bit-value type. The
digits number of bits per value is
specified in size.
• Default is SIGNED. For
UNISIGNED, e.g id INT • The size parameter can hold
UNSIGNED a value from 1 to 64. The
default value for size is 1.
– smallint(size):
• range from -32768 to 32767 Check for tinyint, mediumint,
normal. 0 to 65535 unsigned bigint 11
Data types
• Frequently used number data types- – double(size,d):
– float(size,d): • A normal-size floating point number.
The total number of digits is
• A small number with a floating decimal specified in size. The number of digits
point. The maximum number of digits may after the decimal point is specified in
be specified in the size parameter. The the d parameter
maximum number of digits to the right of
the decimal point is specified in the d – float(p):
parameter • A floating point number. MySQL uses
the p value to determine whether to
• This syntax is deprecated in MySQL 8.0.17, use FLOAT or DOUBLE for the
and it will be removed in future MySQL resulting data type. If p is from 0 to
versions 24, the data type becomes FLOAT().
If p is from 25 to 53, the data type
becomes DOUBLE()
Note: Use FLOAT for approximate numeric calculations (e.g., scientific
computations, measurements).If you require exact decimal places (e.g.,
financial applications), use DECIMAL(m, d) instead. Here, m: Total number
of digits and d: Number of digits after the decimal point. 12
Date types
• Frequently used date/time data types-
– date():
• A date. Format: YYYY-MM-DD
– datetime():
• A date and time combination. Format: YYYY-MM-DD HH:MM:SS
– time():
• A time. Format: HH:MM:SS
– year():
• A year in two-digit or four-digit format.

13
Describe command
• Once a table has been created, the schema definition can be seen using DESC (or
describe) command
• Check the schema description of table land
– sql> DESC land;

14
Integrity Constraints on Tables

• not null
• unique
• primary key
• foreign key

15
Specifying primary key
• Example:
create table branch(
branch_name char(15) primary key,
branch_city char(30) not null,
assets int);

• Example:
create table branch(
branch_name char(15),
branch_city char(30),
assets int,
primary key (branch_name));

16
Specifying Primary Key
create table branch(
branch_name char(15),
branch_city char(30),
assets int, Explicitly
constraint branch_pk mentioning
the
primary key (branch_name));
constraint
name

17
Specifying foreign key
• Example:
– Sql> create table account(
account_no integer primary key,
branch_name char(15),
branch_city char(30),
assets float(8,2),
constraint account_fk1 foreign key (branch_name) references
branch(branch_name))

18
Specifying unique constraint
• Like primary key, UNIQUE constraint uniquely identifies each record in a database
table
• Unlike primary key, a table can have more than one UNIQUE constraint
• Example:
– Sql> create table student(
roll_no char(10) ,
name varchar(20) not null,
mobile_no int(10) unique,
primary key (roll_no));

19
Insertion
• Newly created table is empty account<acc_no, branch_name, balance>
• Add a new tuple to account
insert into account
values (9732, 'Park Road', 1200)

– Insertion fails if any integrity constraint is violated

20
insertion
• Multiple rows can also be inserted using single insert command
• Example:
– sql> insert into account
values (9732, 'Park Road', 1200),
(1332, ‘Buchtel Blvd', 1560 ),
(1991, ‘Exhibition Rd', 2560 )

21
Update
• The UPDATE command is used to update records in a table
• For example, if we want to update the mobile_no of a student with roll_no =
‘2009CS01’
– sql> update student
set mobile_no=9876543210
where roll_no = ‘2009CS01’
• When using update operation care must be taken to specify appropriate condition
in where clause

22
deletion
• The DELETE command is used to delete rows a table
• Example 1: to delete record from student table with roll_no ‘2009CS01’
– sql> delete from student
where roll_no =‘2009CS01’
• Example 2: to delete all records from student table
– sql> delete from student

23
Drop command
• The drop table command is used to delete a table from the database
– sql> drop table table_name
• The drop database command is used to delete a database
– sql> drop database database_name

24
Alter table: adding attribute
• The alter table command is used to add attributes to an existing relation:
– sql> alter table student
add dob date;
– All tuples in the relation are assigned null as the value for the new attribute.
– sql> alter table student
add dob date first;
Positions the new column at the beginning
– sql> alter table student
add dob date after stud_name;
Positions the new column after a specific column

25
Alter Table: dropping attribute
• The alter table command is used to drop attributes from an existing relation:
– sql> alter table student
drop dob;
Drops the specified column
However, this drop clause will not work if the column is the only one left in the
table

26
Alter Table: modify existing attributes
• The alter table command can also be used to modify existing attributes of a
relation:
• Suppose we want to increase the size of name attribute of student relation from
15 to 30
• Using modify clause
– sql> alter table student
modify name varchar(30)
• Using change clause
– sql> alter table student
change name stud_name varchar(30)
Allows to change the column name as well
27
Alter Table: for changing default option
• Changing the column’s default value
– sql> alter table account
modify balance decimal(10,2) default 100.00;

• Removing the column’s default constraint


– sql> alter table account
modify balance decimal(10,2);

28
Alter Table
• Renaming a table
– Sql> alter table account
rename to acounts;

29
Adding primary key
• Command alter table can be used to add primary key in an existing table
• Example: Table name
alter table ac_type
add primary key (account_no) Attribute name
or Table name
alter table ac_type
add constraint ac_type_pk primary key (account_no)

Primary key constraint name

30
Adding foreign key
• Foreign key can also be added in an existing table using alter table command
• Example:
alter table ac_type
add foreign key (account_no) references account (account_no)
or
alter table ac_type
add constraint ac_type_fk1 foreign key (account_no) references account
(account_no)

31
Dropping Primary key
• One relation can have at most one primary key. So without using the primary key
name, the constraint can be dropped.
• Example:
alter table ac_type
drop primary key

32
Dropping foreign key
• Foreign key needs to be dropped using the foreign key name
• Example:
alter table ac_type
drop foreign key ac_type_fk1;

33
To check the constraint name
• The following command can be used to check the constraint names of a table
• SHOW CREATE TABLE account;

34
SQL Query
• Basic form

SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>

SQL commands are case Call this a SFW query.


insensitive

35
Bank Example

36
Simple SQL Query: Selection
account_number branch_name balance

Selection is the 1009 Boring Rd 19.99


operation of filtering a 1233 PU 29.99
relation’s tuples on 2124 Patliputra 149.99
some condition 8721 PU 203.99

SELECT *
FROM account account_number branch_name balance
WHERE branch_name = ‘PU’
1233 PU 29.99
8721 PU 203.99
In SELECT clause, ‘*’ indicates all
attributes
37
Simple SQL Query: Projection
Projection is the account_number branch_name balance
operation of producing an 1009 Boring Rd 19.99
output table with tuples 1233 PU 29.99
that have a subset of 2124 Patliputra 149.99
their prior attributes 8721 PU 203.99

SELECT account_number, balance


FROM account account_number balance
WHERE branch_name = ‘PU’
1233 29.99
8721 203.99

38
Notation
Input schema account(account_number, branch_name, balance)

SELECT account_number, balance


FROM account
WHERE branch_name = ‘PU’

Output schema Answer(account_number, balance)

39
SQL Query: duplicate elimination
• SQL allows duplicates in relations as well as in query results
• To force the elimination of duplicates, insert the keyword distinct after SELECT
clause.
• Find the names of all branches in the account relations, and remove duplicates
SELECT DISTINCT branch_name
FROM account

40
More features of Select clause
• The SELECT clause can contain arithmetic expressions involving the operation,
+, –, * and /, and operating on constants or attributes of tuples.
• E.g.:
SELECT account_number, branch_name, balance * 100
FROM account

41
where Clause
• The where clause can include multiple conditions
• To find all loan number for loans made at the “Patliputra” branch with loan
amounts greater than 1200.
SELECT loan_number
FROM loan
WHERE branch_name = ‘Patliputra' and amount > 1200
• Comparison results can be combined using the logical connectives and, or, and
not.

42
from Clause
• The from clause can also include multiple relations involved in the query
• Find all the possible combinations of borrower and loan relations
– SELECT *
FROM borrower, loan
• Find the name, loan number and loan amount of all customers having a loan at
the Patliputra branch.
– SELECT customer_name, borrower.loan_number, amount
FROM borrower, loan
WHERE borrower.loan_number = loan.loan_number AND branch_name =
'Patliputra'

43
The Rename Operation
• SQL allows renaming relations and attributes using the as clause:
old-name as new-name
• E.g. Find the name, loan number and loan amount of all customers; rename the
column name loan_number as loan_id.

SELECT customer_name, borrower.loan_number AS loan_id, amount


FROM borrower, loan
WHERE borrower.loan_number = loan.loan_number

44
Operator ‘like’
• ‘like’ operator can be used to compare a pattern
• For character data types, two wild cards are frequently used-
– ‘%’: allows to match any string of length (including zero)
– ‘_’ :allows to match a single character
• Example:
SELECT * FROM customer
WHERE name LIKE ‘_avi%’

45
Operator ‘not like’
• Similar to like operator but in this case we are interested in not selecting some
specific pattern using NOT LIKE operator
• Example:
SELECT * from CUSTOMER
WHERE name NOT LIKE ‘_avi%’

46
regexp
• regexp can be used to catch some specific patterns
• Following characters can be used
– ^ to match beginning
– $ to match end
– . to match each instance
– a* matches 0 or more instances of a
– a+ matches 1 or more instances of a
– [abc] matches patterns containing a,b,or c
– [a-e] matches characters say a to e
– [^a-e] not matches a-e characters
– ^…$ matches exactly 3 characters
– ^.{3}$ also matches exactly 3 characters 47
Regexp
• Case insensitive pattern
• Example: Find the names which contain ‘w’ (w or W)
– SELECT cust_name
FROM customer
WHERE cust_name REGEXP ‘w‘
• Case sensitive pattern
• Use ‘binary’ option
• Example: Find the names which contain ‘w’ (lowercase w)
– SELECT cust_name
FROM customer
WHERE cust_name REGEXP binary ‘w‘
48
Operator ‘in’
• Allows to specify multiple values in a ‘where’ clause
• Example:
SELECT *
FROM customers
WHERE city IN (‘Dhanbad’, ‘New Delhi’)

49
Operator ‘between’
• To select a range of data between two values in a ‘where’ clause
• The values can be number, text or dates
• Example:
SELECT * FROM account
WHERE account_no BETWEEN 1234 and 5555

BETWEEN operator is inclusive, i.e., includes both start and


end values

50
Operator ‘not between’
• Not to select a range of data between two values in a ‘where’ clause
• Example:
SELECT * FROM account
WHERE account_no NOT BETWEEN 1234 and 5555

51
Aggregate functions
• SQL aggregate functions return a single value, calculated from values in a column.
• Some useful functions are
– AVG() - Returns the average value
– COUNT() - Returns the number of rows
– MAX() - Returns the largest value
– MIN() - Returns the smallest value
– SUM() - Returns the sum

52
Aggregate Function
• AVG function returns the average value of a numeric column
– SELECT AVG(amount) AS avg
FROM account
• COUNT function returns the number of rows that match a given criterion
– SELECT COUNT(*) FROM account; //counts the number of rows in the table
– SELECT COUNT(account_number) FROM account;

53
Aggregate Function
• SUM function returns the total sum of a numeric column
– SELECT SUM(amount) AS total
FROM account
• MAX function returns the largest value of a selected column
– SELECT MAX(balance) FROM account;
• MIN function returns the smallest value of a selected column
– SELECT MIN(balance) FROM account;

54
ORDER BY Clause account
account_no branch_name balance
Used to sort the results 101 'Downtown' 1500.00

102 ‘Uptown’ 2500.50


SELECT account_number, balance
103 ‘Downtown’ 3000.50
FROM account
WHERE branch_name=‘Downtown’ 104 ‘Downtown’ 1500.00

ORDER BY balance, account_number 105 ‘Uptown’ 1200.00

Ties are broken by Ordering is SELECT *


the second ascending, unless FROM account
attribute on the you specify the ORDER BY balance DESC,
ORDER BY list, etc. DESC keyword. branch_name ASC;

55
‘group by’ clause
• Used to group the result set
• Used in conjunction with aggregate functions
• Example: suppose we want to count the number of accounts owned by a customer
from depositor relation depositor
– SELECT customer_name, COUNT(account_no) cust_name account_no
FROM depositor ‘Alice’ 101

GROUP BY customer_name ‘Bob’ 102

‘Charlie’ 103

‘Diana’ 104

‘Alice’ 105

56
‘having’ clause
• ‘where’ clause could not be used with the aggregate functions. Alternatively,
‘having’ clause can be used
• In the previous example, if we have to show the customer names who have more
than one account
– SELECT customer_name, COUNT(account_no)
FROM depositor
GROUP BY customer_name
HAVING COUNT(account_no)>1

57
Having clause: Another example
• Both WHERE and HAVING can be used in one query
• Suppose, we have to find those customers who have more than one account in
‘Downtown’ branch
– SELECT customer_name, COUNT(depositor.account_no)
FROM depositor, account
WHERE depositor.account_no = account.account_no AND
account.branch_name = ‘Downtown’
GROUP BY customer_name
HAVING COUNT(depositor.account_no)>1;

58
Inner Join
• A join clause is used to combine rows depositor borrower
of two tables based on a related cust_name account_no cust_name loan_no
column between them
‘Alice’ 101 ‘Alice’ 201
• INNER JOIN or JOIN both are same ‘Bob’ 102 ‘Bob’ 202
SELECT depositor.customer_name ‘Charlie’ 103 ‘Frank’ 203
FROM depositor ‘Diana’ 104 ‘Diana’ 204
INNER JOIN borrower
‘Alice’ 105 ‘Grace’ 205
ON depositor.customer_name=borrower.
customer_name;

Does not proceed without a valid ON clause.


59
LEFT JOIN
 The LEFT JOIN returns all records from depositor borrower
the left table (first table), and the cust_name account_no cust_name loan_no
matched records from the right table
‘Alice’ 101 ‘Alice’ 201
(second table). The result is NULL from
‘Bob’ 102 ‘Bob’ 202
the right side, if there is no match.
‘Charlie’ 103 ‘Frank’ 203

SELECT depositor.customer_name, ‘Diana’ 104 ‘Diana’ 204

borrower.customer_name ‘Alice’ 105 ‘Grace’ 205


FROM depositor
LEFT JOIN borrower
ON depositor.customer_name=borrower.
customer_name;
60
RIGHT JOIN
 The RIGHT JOIN returns all records depositor borrower
from the right table (second table), cust_name account_no cust_name loan_no
and the matched records from the left
‘Alice’ 101 ‘Alice’ 201
table (first table). The result is NULL
‘Bob’ 102 ‘Bob’ 202
from the left side, if there is no match.
‘Charlie’ 103 ‘Frank’ 203

SELECT depositor.customer_name, ‘Diana’ 104 ‘Diana’ 204

borrower.customer_name ‘Alice’ 105 ‘Grace’ 205


FROM depositor
RIGHT JOIN borrower
ON depositor.customer_name=borrower.cus
tomer_name;
61
Union operation
• Used to combine two result sets
• In UNION operation, depositor borrower
– SELECT clause must have the same cust_name account_no cust_name loan_no
number of columns. ‘Alice’ 101 ‘Alice’ 201

– The columns must also have similar ‘Bob’ 102 ‘Bob’ 202
data types. ‘Charlie’ 103 ‘Frank’ 203
– Also, the columns in each SELECT ‘Diana’ 104 ‘Diana’ 204
statement must be in the same ‘Alice’ 105 ‘Grace’ 205
order.
SELECT customer_name FROM depositor UNION by default select the distinct values
UNION UNION ALL will select the duplicate values
SELECT customer_name FROM borrower; also
62
Intersect and Minus operation
• Mysql does not support INTERSECT and MINUS operation directly
• Nested query can be used to implement these functions

63
Nested Query
• A nested query, also known as a subquery, is a query that is embedded within
another SQL query. It can be used in the SELECT, FROM, WHERE, or HAVING
clauses of an outer query to perform intermediate operations or filter results.
• SELECT *
Outer
FROM t1 query
WHERE column1 IN (
SELECT column1
FROM t2);
Inner/sub
query

A sub query can be nested within another sub query


64
For joining two relations
• SELECT cust_name depositor borrower
FROM depositor cust_name account_no cust_name loan_no
WHERE cust_name IN (
‘Alice’ 101 ‘Alice’ 201
SELECT cust_name
‘Bob’ 102 ‘Bob’ 202
FROM borrower)
‘Charlie’ 103 ‘Frank’ 203
• An equivalent to set intersection operation
‘Diana’ 104 ‘Diana’ 204
‘Alice’ 105 ‘Grace’ 205

65
Equivalent minus operation
• SELECT cust_name depositor borrower
FROM depsositor cust_name account_no cust_name loan_no
WHERE cust_name NOT IN ( ‘Alice’ 101 ‘Alice’ 201
SELECT cust_name ‘Bob’ 102 ‘Bob’ 202
FROM borrower) ‘Charlie’ 103 ‘Frank’ 203
• An equivalent to minus operation ‘Diana’ 104 ‘Diana’ 204
‘Alice’ 105 ‘Grace’ 205

66
Exists/ Not Exists
• SELECT column1
FROM t1
WHERE EXISTS (
SELECT *
FROM t2);
• If a subquery returns any rows at all then the EXISTS subquery is true and NOT
EXISTS subquery is false

67
depositor borrower
cust_name account_no cust_name loan_no
‘Alice’ 101 ‘Alice’ 201
• SELECT cust_name ‘Bob’ 102 ‘Bob’ 202
FROM depositor ‘Charlie’ 103 ‘Frank’ 203
WHERE EXISTS ( ‘Diana’ 104 ‘Diana’ 204
SELECT *
‘Alice’ 105 ‘Grace’ 205
FROM borrower
WHERE borrower.cust_name = depositor.cust_name)

A query is called correlated nested query when both the inner query
and the outer query are interdependent.

68
Sub-queries with the INSERT Statement:
• Copy customer names from the depositor table to a new customer_log table.
depositor customer_log
CREATE TABLE customer_log ( cust_name account_no cust_name
cust_name VARCHAR(50) ‘Alice’ 101 ‘Alice’
); ‘Bob’ 102 ‘Bob’
‘Charlie’ 103 ‘Charlie’
INSERT INTO customer_log (cust_name)
‘Diana’ 104 ‘Diana’
SELECT DISTINCT cust_name
FROM depositor; ‘Alice’ 105

69
Sub-queries with the UPDATE Statement:
• Updates the balance of all accounts whose current balance is less than the
average balance of all accounts. Ensures that accounts with below-average
balances are incremented by 100. account
account_no branch_name balance
UPDATE account
101 'Downtown' 1500.00
SET balance = balance + 100
102 ‘Uptown’ 2500.50
WHERE balance < (
SELECT AVG(balance) 103 ‘Downtown’ 3000.50

FROM account 104 ‘Downtown’ 1500.00

); 105 ‘Uptown’ 1200.00

Avg(balance)=1940.20

70
Sub-queries with the DELETE Statement:
• Delete all accounts from the account table that belong to branches where the
average balance is less than 2000. account
account_no branch_name balance
DELETE FROM account 101 'Downtown' 1500.00
WHERE branch_name IN ( 102 ‘Uptown’ 2500.50
SELECT branch_name
103 ‘Downtown’ 3000.50
FROM account
104 ‘Downtown’ 1500.00
GROUP BY branch_name
HAVING AVG(balance) < 2000 105 ‘Uptown’ 1200.00

);
branch_name Avg(balance)

'Downtown' 2000.16

‘Uptown’ 1850.25
71
Some string functions
• ASCII()
– Returns the ASCII value of a character
– mysql> SELECT ASCII(‘a’); 97
• Char_length()
– Returns the length of the string in characters
– mysql> SELECT CHAR_LENGTH(‘university’); 10
• Concat()
– Adds two or more expressions together
– mysql> SELECT CONCAT(‘delhi ‘ ,‘university’); delhi university
• Concat_ws()
– Adds two or more expressions together with separator
– mysql> SELECT CONCAT_WS(‘-’, ‘delhi‘, ’university’);
delhi-university

72
Some string functions
• Field
– Returns the index position of a value in a list of values. Returns 0 if the value is
not available in the list
– Syntax: FIELD(value, val1, val2, val3, ...) 4
– mysql> SELECT FIELD (‘a’,’k’,’d’,’s’,’a’);
• Format
– The FORMAT() function formats a number to a format like "#,###,###.##",
rounded to a specified number of decimal places, then it returns the result as
a string.
– Syntax: FORMAT(number, decimal_places)
– mysql> SELECT FORMAT(123456789.789,2) 123,456,789.79

73
Some string functions
• Insert()
– The INSERT() function inserts a string within a string at the specified position
and for a certain number of characters.
– Syntax: INSERT(string, position, number, string2)
univ.gov.in
– mysql> SELECT INSERT(“univ.edu.in", 6, 3 “gov");
• Instr()
– The INSTR() function returns the position of the first occurrence of a string in
another string
– Syntax: INSTR(string, substring)
– mysql> SELECT INSTR(“du.edu", “edu") AS MatchPosition;
4
74
Some string functions
• Lcase() or Lower()
– Converts a string to lowercase
– Syntax: Lcase(text), Lower(text)
– mysql>SELECT LCASE(‘UNIVERSITY’)
– mysql>SELECT LOWER(‘UNIVERSITY’) university
• Ucase or Upper()
– Converts a string to uppercase
– Syntax: Ucase(text), Upper(text)
– mysql>SELECT UCASE(‘University’) UNIVERSITY
– mysql>SELECT UPPER(‘University’)

75
Some more string functions
• LOCATE()
– The LOCATE() function returns the position of the first occurrence of a
substring in a string.
– Syntax: LOCATE(substring, string)
– mysql> SELECT LOCATE("com", “www.yahoo.com") AS MatchPosition;

11

76
• LPAD()
– Left-pads a string with another string, to a certain length
– Syntax: LPAD(string, length, lpad_string)
*****alice
– mysql> SELECT LPAD(‘alice’, 10, ’*’)
• RPAD()
– Similar to LPAD() but it right-pads a string with another string, to a certain
length
alice*****
– mysql> SELECT RPAD(‘alice’, 10, ’*’)

77
Some more string functions
• LTRIM()
– The LTRIM() function removes leading spaces from a string
– Syntax: LTRIM(string)
– mysql> SELECT LTRIM(‘ delhi’);
delhi
• RTRIM()
– Similar to LTRIM. The RTRIM() function removes trailing spaces from a string

78
Some more string functions
• REPEAT()
– The REPEAT() function repeats a string for a specified number of times
– Syntax: REPEAT(string, number)
– mysql> SELECT REPEAT(‘abc’,3); abcabcabc
• Replace
– The REPLACE() function replaces all occurrences of a substring within a string,
with a new substring
– Syntax: REPLACE(string, from_substring, new_substring)
– mysql> SELECT REPLACE("SQL Tutorial", "SQL", "HTML");

HTML Tutorial
79
Some more string functions
• REVERSE()
– The REVERSE() function reverses a string and returns the result.
– Syntax: reverse(string)
– mysql> SELECT REVERSE(‘delhi’);
ihled
Some more string functions
• STRCMP()
– The STRCMP() function compares two strings
– Syntax: strcmp(string1, string2))
– If string1 = string2, this function returns 0
– If string1 < string2, this function returns -1
– If string1 > string2, this function returns 1
– mysql> SELECT STRCMP(‘abc’,’abb’);
1

81
Some more string functions
• SUBSTR()
– The SUBSTR() function extracts a substring from a string (starting at any
position).
– Syntax: SUBSTR(string, start, length)
– mysql> SELECT SUBSTR(‘hello, world’, 8) ; world
– mysql> SELECT SUBSTR(‘hello, world’, 8, 3) ; wor

– mysql> SELECT SUBSTR(‘hello, world’, -9, 3) ; lo,

82
• RIGHT() Function
– Extracts a specified number of characters from the right side of a string
– Syntax: RIGHT(str, len)
– mysql> SELECT RIGHT(‘IIT Patna’,5)
Patna

83
View
• A view consists of a stored query accessible as a virtual table composed of the
result set of a query
• Unlike ordinary tables in a relational database, a view does not form part of
the physical schema
• It is a dynamic, virtual table computed from data in the database
• Changing the data in a table alters the data shown in subsequent invocations of
the view
View
• A view is a virtual table that contains no physical data. It provides an alternative
way to look at the data.
cust_view is the view name
– mysql> CREATE VIEW cust_view AS
SELECT customer_name AS cust_name, customer_city AS cust_city
FROM customer;
• Once a view is created, it can be used like a table
– mysql> SELECT * FROM cust_view;

85
Uses of Views
• Hiding some information from some users
– Consider a user who needs to know a customer’s name, loan number and
branch name, but has no need to see the loan amount.
– mysql> CREATE VIEW cust_loan_data AS
SELECT customer_name, borrower.loan_number, branch_name
FROM borrower, loan
WHERE borrower.loan_number = loan.loan_number
– Grant the user permission to read cust_loan_data, but not borrower or loan

86
Uses of view (2)
• Views can act as aggregated tables, where the database engine aggregates data
(sum, average etc.) and presents the calculated results as part of the data
• Create a view that aggregates Total balance of all accounts for each customer,
Average balance of their accounts and Number of accounts per customer.

– mysql>CREATE VIEW CustomerAccountSummary AS


SELECT d.cust_name, COUNT(d.account_no) AS num_accounts, SUM(a.balance)
AS total_balance, AVG(a.balance) AS average_balance
FROM depositor d , account a
WHERE d.account_no = a.account_no
GROUP BY d.cust_name;
87
SELECT * FROM CustomerAccountSummary
Updating tables through views
• A view is updatable if:
– It references a single table.
– It does not use aggregation functions (SUM, AVG, etc.), GROUP BY, or
DISTINCT.
– It does not include UNION or UNION ALL.
– It does not use subqueries in the SELECT list.
– All columns in the view that you want to update must correspond to real
columns in the underlying table (i.e., no computed or derived columns).

88
Updatable view
• Create a updatable view

CREATE VIEW PatliputraAccounts AS


SELECT account_no, balance
FROM account
WHERE branch_name = ‘Patliputra';

UPDATE PatliputraAccounts
SET balance = balance + 500
WHERE account_no = 101;
89
Some Date Functions

90
Curdate()
• In MySQL the CURDATE() returns the current date in 'YYYY-MM-DD' format or
'YYYYMMDD' format depending on whether numeric or string is used in the
function
• CURRENT_DATE() and CURRENT_DATE functions are same as CURDATE()
– mysql> SELECT curdate(); 2025-01-29

– mysql> SELECT curdate() + 0; 20250129

– mysql> SELECT current_date(); 2025-01-29

– mysql> SELECT current_date; 2025-01-29

91
Sysdate()
• SYSDATE() returns the current date and time in YYYY-MM-DD HH:MM:SS or
YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function.
– mysql> SELECT sysdate(); 2025-01-29 18:19:10

– mysql> SELECT sysdate() + 0; 20250129181910

92
Extract()
• EXTRACTs a part of a given date. This function does not perform date arithmetic.
The unit specifiers of DATE_ADD() and DATE_SUB() work with this function also.
– Syntax: extract(unit from date1)
– mysql> SELECT EXTRACT(year from ‘2018-09-24 18:30:23’) 2018
– Like year, one can extract month, day, hour, minute, seconds, etc
– mysql> SELECT EXTRACT(hour from ‘2018-09-24 18:30:23’) 18

93
Adddate()
• MySQL ADDDATE() adds a time value with a date.
• The DATE_ADD() is the synonym of ADDDATE()
– Syntax: ADDDATE(date, INTERVAL expr unit), ADDDATE(expr,days)
– mysql>SELECT ADDDATE('2024-02-20', INTERVAL 10 DAY) as required_date;

required_date
2024-03-01

94
Addtime()
• In MySQL the ADDTIME() returns a time or datetime after adding a time value with
a time or datetime.
– Syntax: ADDTIME(expr1,expr2)
– mysql>SELECT ADDTIME('2024-02-20 13:20:32.50','21:39:27.50') as
required_datetime;

required_datetime
2024-02-21 11:00:00

95
DATE_FORMAT
• DATE_FORMAT(date, format): it formats the date value according to the
format string
• In the format string, specifier character is used along with the % symbol
• Example:
– mysql> SELECT DATE_FORMAT ( ‘2024-02-20', '%D %b %Y' )
20th Feb 2024
– mysql> SELECT DATE_FORMAT ( ‘2024-02-20', '%d %c %y' )
20 2 24

96
Specifier Table
Specifier Description Specifier Description
%a Abbr. weekday name (like Sun..Sat) %i Minutes, numeric (0..59)
%b Abbr. month name (like Jan..Dec) %s Seconds (00,..59)
%c Month numeric (0..12) %p AM or PM
%D Day of the month with English %i Minutes, numeric (0..59)
suffix (0th, 1st, 2nd, 3rd , …)
%d Day of the month, numeric (00..31) %W Weekday name (like Thursday)
%M Month name (January,…, %j Day of Year (001-366)
December)
%m Month, numeric (00,..,12) %H Hour (00..23)
%Y Year numeric (4 digits) %h Hour (01..12)

97
Example of some format strings
date_format String example
'%a %D %b %Y' Mon 24th Sep 2018
'%a %D %b %Y %H:%i' Mon 24th Sep 2018 12:30
%a %D %b %Y %T' Mon 24th Sep 2018 12:30:10
%a %b %e %Y' Mon Sep 24 2018
'%W %D %M %Y' Monday 24th September 2018
'%M %e, %Y' September 24, 2018

98
Date_sub()
• MySQL DATE_SUB() function subtract a time value (as interval) from a date.
– Syntax: DATE_SUB(date, INTERVAL expr unit)
– The unit of time (such as DAY, MONTH, YEAR, etc.)

– mysql> SELECT DATE_SUB('2025-01-29', INTERVAL 10 DAY);

2025-01-19

99
Datediff()
• DATEDIFF() returns the number of days between two dates or datetimes. This
function only calculates the date portion from each expression.
– Syntax DATEDIFF(expr1,expr2);
– mysql> SELECT DATEDIFF('2024-03-01 11:31:31','2024-02-20');

10

100
Dayname()
• DAYNAME() returns the name of the week day of a date specified in the argument.
– Syntax: DAYNAME(date1)
– mysql> SELECT DAYNAME('2024-03-01');

Friday

101
dayofweek
• DAYOFWEEK() returns the week day number (1 for Sunday,2 for Monday …… 7 for
Saturday ) for a date specified as argument.
– Syntax: DAYOFWEEK(date)
– mysql>SELECT DAYOFWEEK('2024-03-01');

102
Last_day()
• LAST_DAY() returns the last day of the corresponding month for a date or datetime
value. If the date or datetime value is invalid, the function returns NULL.
– Syntax: LAST_DAY(date1)
– mysql> SELECT LAST_DAY('2024-02-20');

2024-02-29

103
Dayofyear
• MySQL DAYOFYEAR() returns day of the year for a date. The return value is within
the range of 1 to 366.
– Syntax: DAYOFYEAR(date1)
– mysql> SELECT DAYOFYEAR('2024-02-20');

51

104
To_days()
• MySQL TO_DAYS() returns a number of days between a given date and year 0
– Syntax: TO_DAYS(date);
– mysql> SELECT TO_DAYS('2024-02-20');

739301

105

You might also like