Mysql PPT Ver8
Mysql PPT Ver8
Session 1
Introduction
So as a programmer:
a person should understand and be able to interact with a database is must, so than the
data which is collected from the UI is processed and stored permanently. (eg. Any
management systems, set top box, washing machine, mobile application etc.).
Introduction
We need databases because they organize data in a manner which allows us to store, query, sort,
and manipulate data in various ways. Databases allow us to do all this things.
Many companies collects data from different resource (like Weather data, Geographical data,
Finance data, Scientific data, Transport data, Cultural data, etc.)
What is Relation and
Relationship?
Relation and Relationship?
Relation (in Relational Algebra "R" stands for relation): In Database, a relation represents a
table or an entity than contain attributes.
Relationship: In database, relationship is that how the two entities are connected to each
other, i.e. what kind of relationship type they hold between them.
Remember: Note:
• Foreign Key is also know as • Table - The physical instantiation of a relation in the
database schema.
Reference/Referential key. • Relation - A logical construct that organizes data into rows
and columns.
File Systems is the traditional way to keep your data organized.
File System
vs
DBMS
struct Employee {
int emp_no;
struct Employee {
int emp_no;
File-oriented system
char emp_name[50]; char emp_name[50]; File Anomalies
int salary; int salary;
} emp[1000]; };
struct Employee emp[1000];
• Backup: It is possible to take faster and automatic back-up of database stored in files of computer-based
systems.
• Data retrieval: It is possible to retrieve data stored in files in easy and efficient way.
• Sharing: Data stored in files of computer-based systems can be shared among multiple users at a same time.
Disadvantage of file-oriented system
The biggest disadvantage of file-based storage is as follows.
• Data redundancy: It is possible that the same information may be duplicated in different files. This leads to data
redundancy results in memory wastage. (Suppose a customer having both kind of accounts- saving and current
account. In such a situation a customers detail are stored in both the file, saving.txt- file and current.txt- file ,
which leads to Data Redundancy.)
• Data inconsistency: Because of data redundancy, it is possible that data may not be in consistent state. (Suppose
customer changed his/her address. There might be a possibility that address is changed in only one file
(saving.txt) and other (current.txt) remain unchanged.)
• Limited data sharing: Data are scattered in various files and also different files may have different formats (for
example: .txt, .csv, .tsv and .xml) and these files may be stored in different folders so, due to this it is difficult to
share data among different applications.
• Data Isolation: Because data are scattered in various files, and files may be in different formats (for example: .txt,
.csv, .tsv and .xml), writing new application programs to retrieve the appropriate data is difficult.
• Data security: Data should be secured from unauthorized access, for example a account holder in a bank should
not be able to see the account details of another account holder, such kind of security constraints are difficult to
apply in file processing systems.
Relation Schema: A relation schema represents name of the relation with its attributes.
• e.g. student (roll_no, name, address, phone and age) is relation schema for STUDENT
DBMS
The database management system (DBMS) is the software that interacts with end users, applications, and the
database itself to store and analyze the data.
• database: Is the collection of related data which is organized, store and retrieve large amount of
data easily, which is stored in one or more data files by one or more users, it is called as structured
data.
• management system: is a software, designed to define, manipulate, retrieve and manage data in a
database.
Difference between File System and DBMS
• User locates the physical address of the files to access • In Database Management System, user is unaware of
data in File System. physical address where data is stored.
RDBMS supports
• client/server Technology
• Highly Secured
• Relationship (PK/FK)
Difference between DBMS and RDBMS
DBMS RDBMS
• DBMS has no support for distributed databases. • RDBMS supports distributed databases.
• Normalization cannot be achieved. • Normalization can be achieved.
• DBMS supports single user at a time. • RDBMS supports multiple users at a time.
• Data Redundancy is common in DBMS. • Data Redundancy can be reduced in RDBMS.
• DBMS provides low level of security during data • RDBMS has high level of security during data
manipulation. manipulation.
relational model concepts
and
properties of relational table
relational model concepts
Relational model organizes data into one or more tables (or "relations") of columns and rows. Rows are also
called records or tuples. Columns are also called attributes.
• Tables − In relational model, relations are saved in the form of Tables. A table has rows and columns.
• Attribute − Attributes are the properties that define a relation. e.g. (roll_no, name, address, phone and age)
• Tuple − A single row of a table, which contains a single record for that relation is called a tuple.
• Relation schema − A relation schema describes the relation name (table name) with its attribute (columns) names.
e.g. student(roll_no, name, address, phone and age) is relation schema for student relation.
• Attribute domain − Every attribute has some pre-defined datatypes, known as attribute domain.
• Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the
relation (table) uniquely.
properties of relational table
ID job firstName DoB salary Domain refers to all the valid values
1 manager Saleel Bagde yyyy-mm-dd ●●●●●● which a column may contain.
3 salesman Sharmin yyyy-mm-dd ●●●●●●
e.g.
• number, characters, or symbol
• images, audio, video, or signal
What is Entity Relationship
Diagram?
Entity Relationship Diagram (ER Diagram)
What is Entity?
Entity
All these entities have some attributes or properties that give them their identity.
What is an Attribute?
Entity
Attributes are the properties that define a relation.
e.g. student(ID, firstName, middleName, lastName, city)
Attribute
In some cases, you might not want a specific attribute to contain a null
value, but you don't want to require that the user or program always provide a
value. In this case, a default value might be appropriate. A default value is a
value that applies to an attribute if no other valid value is available.
Attributes
In Relation: EMP
Attributes
• Atomic Attribute: An attribute that cannot be divided into smaller independent attribute is known as atomic
attribute.
e.g. ID’s, age, gender, zip, marital status cannot further divide.
• Single Value Attribute: An attribute that has only single value is known as single valued attribute.
e.g. manufactured part can have only one serial number, voter card, blood group, price, quantity, branch can
have only one value.
• Stored Attribute: The stored attribute are such attributes which are already stored in the database and from
which the value of another attribute is derived.
e.g. (HRA, DA…) can be derive from salary, age can be derived from DoB, total marks or average marks of a
student can be derived from marks.
Composite VS Multi Valued
Attribute
Composite / Multi Valued Attributes
Composite Attribute
Person Entity
• Name attribute: ( firstName, middleName, and lastName )
• PhoneNumber attribute: ( countryCode, cityCode, and phoneNumber )
Non-prime attribute
An attribute, which is not a part of the prime-key (candidate key), is said to be a non-prime
attribute.
erdplus.com
Attribute
Composite
Attribute
Key Attribute
Weak
Relationship Relationship
Multivalued
Attribute
Entity Relationship Diagram
DoB
What is a degree, cardinality, domain and
union in database?
• Degree d(R) / Arity: Total number of attributes/columns present in a relation/table is called degree of the
relation and is denoted by d(R).
• Domain: Total range of accepted values for an attribute of the relation is called the domain of the
attribute. (Data Type)
• Union Compatibility: Two relations R and S are set to be Union Compatible to each other if and only if:
1. They have the same degree d(R).
2. Domains of the respective attributes should also be same.
Data integrity refers to the correctness
and completeness of data. A domain constraint and types
of data integrity constraints
Domain Constraint = data type + Constraints (not null/unique/primary key/foreign key/check/default )
e.g. custID INT, constraint pk_custid PRIMARY KEY(custID)
Three types of integrity constraints: entity integrity, referential integrity and domain integrity:
• Entity integrity: Entity Integrity Constraint is used to ensure the uniqueness of each record the table. There are
primarily two types of integrity constraints that help us in ensuring the uniqueness of each row, namely,
UNIQUE constraint and PRIMARY KEY constraint.
•
• Referential integrity: Referential Integrity Constraint ensures that there always exists a valid relationship
between two tables. This makes sure that if a foreign key exists in a table relationship then it should always
reference a corresponding value in the second table or it should be null.
• Domain integrity: A domain is a set of values of the same type. For example, we can specify if a particular
column can hold null values or not, if the values have to be unique or not, the data type or size of values that
can be entered in the column, the default values for the column, etc..
What is a domain constraint in database?
• Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY
/ FOREIGN KEY / CHECK / DEFAULT)
Data Domain refers to all the valid values which a column may contain and can be done by giving data type to
the column.
Keys are used to establish relationships between tables
and also to uniquely identify any record in the table. types of Keys?
r = Employee(EmployeeID, FullName, job, salary, PAN,
DateOfBirth, emailID, deptno)
• Candidate Key: are individual columns in a table that qualifies for uniqueness of all the rows. Here in Employee
table EmployeeID, PAN or emailID are Candidate keys.
• Primary Key: is the columns you choose to maintain uniqueness in a table. Here in Employee table you can
choose either EmployeeID, PAN or emailID columns, EmployeeID is preferable choice.
• Alternate Key: Candidate column other the primary key column, like if EmployeeID is primary key then , PAN
or emailID columns would be the Alternate key.
• Super Key: If you add any other column to a primary key then it become a super key, like EmployeeID +
FullName is a Super Key.
• Composite Key: If a table do not have any single column that qualifies for a Candidate key, then you have to
select 2 or more columns to make a row unique. Like if there is no EmployeeID, PAN or emailID columns, then
you can make FullName + DateOfBirth as Composite key. But still there can be a narrow chance of duplicate
row.
Candidate Key
Primary Key
Composite Key
Alternate Key
Degrees of relationship
The degree of relationship can be defined as the number of occurrences in
one entity that is associated with the number of occurrences in another entity.
Relationships
1. one-to-one (1:1)
2. one-to-many (1:M)
3. many-to-many (M:N)
one-to-one relationship
one-to-one relationship
A one-to-one relationship between two tables means that a row in one table can only relate to
zero/one row in the table on the other side of their relationship. This is the least common database
relationship.
A one-to-one relationship is a type of cardinality that refers to the relationship between two entities
R and S in which one element of entity R may only be linked to zero/one element of entity S, and
vice versa.
A one-to-one relationship is a type of cardinality that refers to the relationship between two entities
R and S in which one element of entity R may only be linked to zero/one element of entity S, and
vice versa.
Person-4 Passport-1
how to create one-to-one relationship
CREATE TABLE user (
userID INT PRIMARY KEY,
userName VARCHAR(40),
password VARCHAR(25),
email VARCHAR(128)
) ;
a one-to-many relationship is a type of cardinality that refers to the relationship between two entities R
and S in which an element of R may be linked to many elements of S, but a member of S is linked to
only one element of R.
a one-to-many relationship is a type of cardinality that refers to the relationship between two entities R
and S in which an element of R may be linked to many elements of S, but a member of S is linked to
only one element of R.
=
=
CREATE TABLE item (
how to create many-to-many relationship
item_ID INT PRIMARY KEY,
name VARCHAR(45),
description TEXT
);
CREATE TABLE orders (
orders_ID INT PRIMARY KEY,
orderdate DATETIME,
custID INT NOT NULL,
shipDate DATETIME,
total FLOAT(8,2),
constraint total_greater_zero CHECK(total >=
0)
);
CREATE TABLE orders_has_item (
orders_ID INT NOT NULL,
item_ID INT NOT NULL,
PRIMARY KEY(orders_ID, item_ID),
constraint fk_orders_has_item_orders FOREIGN
KEY(orders_ID)
REFERENCES orders(ID),
constraint fk_orders_has_item_item1 FOREIGN
how to create many-to-many relationship
CREATE TABLE blog (
ID INT PRIMARY KEY,
blog TEXT,
blogDate DATETIME
);
•Data objects
•The associations between different data objects
•The rules.
Data Modeling
Data modeling is a process used to define and analyze data requirements needed to
support the business processes within the scope of corresponding systems in
organizations.
Anomalies in DBMS
Something that deviates from what is standard, normal, or expected.
There are three types of anomalies that occur when the database is not normalized. These are –
• Insertion anomaly
• Updation anomaly
• Deletion anomaly.
Anomalies in DBMS - Example
student table.
• Insert anomaly: What if we want to add new branch in the student table? In this case as the student Rollno is
a primary key, is will not allow you to insert new branch. Also, if we have to insert data of 100 students of same
branch, then the branch information will be repeated for all those 100 students. This is Insertion anomalies.
• Update anomaly: What if Mr. X telephone number changes? In that case all the student records will have to
be updated, and if by mistake we miss any record, it will lead to data inconsistency. This is Updation anomaly.
• Delete anomaly: In our Student table, two different information are kept together, Student information and
Branch information. Hence, at the end of the academic year, if student records are deleted, we will also lose the
branch information. This is Deletion anomaly.
Normalization in DBMS
Normalization is the process of removing redundant data from the database by splitting the table
into two or more tables and defining relationships between these tables.
Problem
To understand normalization in database with example tables, let’s assume that we are supposed to store
the details of courses and instructors in a university.
At first, this design seems to be good. However, issues start to develop once we need to modify information.
For instance, suppose, if Prof. Ronald changed his mobile number. In such a situation, we will have to make
edits in 2 places. What if someone just edited the mobile number against CS101, but forgot to edit it for
CS154? This will lead to stale/wrong information in the database.
Solution
This problem, however, can be easily tackled by dividing our table into 2 simpler tables.
Table 1 (Instructor)
Table 2 (Course)
For a table to be in the First Normal Form, it should follow the following 4 rules:
Here, the issue is that in the first row, we are storing 2 courses against Prof. Ronald. A better method would
be to store the courses separately. This way, if we want to edit some information related to CS101, we do not
have to touch the data corresponding to CS154.
Let us take another example of storing student enrollment in various courses. Each student may enroll in
multiple courses. Similarly, each course may have multiple enrollments.
A sample table may look like this (student name and course code)
Enrollments
Third normal form avoids this by breaking this into separate tables
Course Code Course Venue Instructor's ID
CS101 Lecture Hall 18 1
CS152 Auditorium building, 2
CS154 Lecture Hall 19 1
CS189 Auditorium building #1 3
CS107 Lecture Hall #4 3
Here, the third column is the ID of the professor who’s taking the course.
Instructor's ID Instructor's Name Instructor’s Number Department
1 Prof. Ronald +1 6514821924 Mathematics Department
2 Prof. John +1 6519272918 Electronics Department
3 Prof. Smith +1 6519272919 Computer Science Department
MySQL
MySQL was created by a Swedish company - MySQL AB that was founded in 1995. It was acquired by Sun
Microsystems in 2008; Sun was in turn acquired by Oracle Corporation in 2010.
When you use MySQL, you’re actually using at least two programmes. One program is the MySQL
server (mysqld.exe) and other program is MySQL client program (mysql.exe) that
connects to the database server.
What is SQL?
What is SQL?
SQL (Structured Query Language) is a database language designed and developed for
managing data in relational database management systems (RDBMS). SQL is common
language for all Relational Databases.
What is SQL?
Remember:
• A NULL value is not treated as a blank or 0. Null or NULL is a special marker used in Structured Query
Language to indicate that a data value does not exist in the database.
• Degree d(R): Total no. of attributes/columns present in a relation/table is called degree of the relation and is
denoted by d(R).
• Cardinality |R|: Total no. of tuples present in a relation or Rows present in a table, is called cardinality of a
relation and is denoted by |R|.
Comments in MySQL
SHOW DATABASES;
SHOW SCHEMAS;
SHOW DATABASES LIKE 'U%';
SHOW SCHEMAS LIKE 'U%';
NULL means “no database is selected”. Issue the USE dbName command to select the database.
USE DATABASES
The USE db_name statement tells MySQL to use the db_name database as the default (current)
database for subsequent statements. The database remains the default until the end of the session or
another USE statement is issued.
USE DATABASES Syntax
USE db_name
Note:
• USE, does not require a semicolon.
USE db1
\U db1
CREATE DATABASE
CREATE DATABASE
CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE
privilege for the database.
\. file_name
source file_name
• \. 'D:\mysqldemobld7.sql'
• SOURCE 'D:\mysqldemobld7.sql'
• SOURCE
//infoserver1/infodomain1/Everyone/DBT/mysqldemobld7.sql
SELECT statement…
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy;
SELECT CLAUSE
The SELECT statement retrieves or extracts data from tables in the database.
• You can use one or more tables separated by comma to extract data.
• You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
• SELECT can also be used to retrieve rows computed without reference to any table e.g. SELECT 1 + 2;
Capabilities of
SELECT Statement
1. SELECTION
2. PROJECTION
3. JOINING
Capabilities of
SELECT Statement
SELECTION
Selection capability in SQL is to choose the rows in a table that you want to return
by a query.
R
EMPNO ENAME JOB HIREDATE DEPTNO
1 Saleel Manager 1995-01-01 10
2 Janhavi Sales 1994-12-20 20
3 Snehal Manager 1997-05-21 10
4 Rahul Account 1997-07-30 10
5 Ketan Sales 1994-01-01 30
Capabilities of
SELECT Statement
PROJECTION
Projection capability in SQL to choose the columns in a table that you want to
return by your query.
R
EMPNO ENAME JOB HIREDATE DEPTNO
1 Saleel Manager 1995-01-01 10
2 Janhavi Sales 1994-12-20 20
3 Snehal Manager 1997-05-21 10
4 Rahul Account 1997-07-30 10
5 Ketan Sales 1994-01-01 30
Capabilities of
SELECT Statement
JOINING
Join capability in SQL to bring together data that is stored in different tables by
creating a link between them.
R S
EMPNO ENAME JOB HIREDATE DEPTNO DEPTNO DNAME LOC
1 Saleel Manager 1995-01-01 20 10 HRD PUNE
2 Janhavi Sales 1994-12-20 10 20 SALES BARODA
3 Snehal Manager 1997-05-21 10 40 PURCHASE SURAT
4 Rahul Account 1997-07-30 20
5 Ketan Sales 1994-01-01 30
SELECT statement
SELECTION Process
PROJECTION Process
Column - ALIAS
A programmer can use an alias to temporarily assign another name to a column or table for the
duration of a SELECT query.
In the selection-list, a quoted column alias can be specified using identifier ( ` ) or string quote ( ' or " ) characters.
Note:
• Assigning an alias_name does not actually rename the column or table.
SELECT statement - ALIAS
SELECT A1 [ [as] alias_name], A2 [ [as] alias_name], . . ., AN FROM r
[ [as] alias_name]
Remember:
• A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name
and can be used in GROUP BY, HAVING, or ORDER BY clauses.
• The AS keyword is optional when aliasing a select_expr with an identifier.
• Standard SQL disallows references to column aliases in a WHERE clause.
• A table reference can be aliased using tbl_name alias_name or tbl_name AS alias_name
• If the column alias contains spaces, put it in quotes.
• Alias name is max 256 characters.
Column - EXPRESSIONS
"Strings are automatically converted to numbers and numbers to strings as necessary." This means
that in order to compare a string to a number, it tries to parse a number from the start of the string.
In this case there is no number there, so it converts to 0, and 0 = 0 is true.
SELECT statement - EXPRESSIONS
Column EXPRESSIONS
Note:
• You need not specify a tbl_name or db_name.tbl_name prefix for a column reference unless the reference
would be ambiguous.
• The identifier quote character is the backtick (`)
• DATEDIFF(CURDATE(), hiredate) / 365.25
DateTime Functions
NOW(), CURDATE(), CURTIME()
In MySQL, the CURDATE() returns the current date in 'YYYY-MM-DD'. CURRENT_DATE() and
CURRENT_DATE are the synonym of CURDATE().
In MySQL, the CURTIME() returns the value of current time in 'HH:MM:SS'. CURRENT_TIME() and
CURRENT_TIME are the synonym of CURTIME().
NOW(), CURDATE(), CURTIME()
• SELECT NOW()
• SELECT CURDATE()
• SELECT CURTIME()
Unit Value
MICROSECOND SECOND MINUTE HOUR DAY
WEEK MONTH QUARTER YEAR
MINUTE_SECOND HOUR_SECOND DAY_SECOND DAY_HOUR
HOUR_MINUTE DAY_MINUTE YEAR_MONTH
DAYOFMONTH(date) Returns the day of the month for date, in the range 1 to 31
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7
DAYOFWEEK(date)
= Saturday).
DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366
Takes a date or datetime value and returns the corresponding
LAST_DAY(date) value for the last day of the month. Returns NULL if the
argument is invalid.
Returns the month for date, in the range 1 to 12 for January to
MONTH(date)
December
•MONTHNAME(date)
SELECT DAYOFWEEK(NOW()), WEEKDAY(NOW());
Returns the full name of the month for date.
• SELECT DAYOFWEEK(ADDDATE(NOW(), INTERVAL 1 DAY)), WEEKDAY(ADDDATE(NOW(),
INTERVAL 1 DAY));
DateTime Functions
Syntax Result
Returns the weekday index for date (0 = Monday, 1 = Tuesday,
WEEKDAY(date)
… 6 = Sunday).
Returns the calendar week of the date as a number in the
WEEKOFYEAR(date)
range from 1 to 53.
Returns the quarter of the year for date, in the range 1 to
QUARTER(date)
4.
Returns the hour for time. The range of the return value is 0
HOUR(time)
to 23 for time-of-day values.
MINUTE(time) Returns the minute for time, in the range 0 to 59.
String Functions
String Functions
Syntax Result
Returns the numeric value of the leftmost character of the
string str. Returns 0 if str is the empty string. Returns NULL
ASCII(str) if str is NULL.
e.g.
• SELECT ASCII(ename) FROM emp;
CHAR() interprets each argument N as an integer and returns a
string consisting of the characters given by the code values of
those integers. NULL values are skipped.
CHAR(N, , . . .)
e.g.
• SELECT CHAR(65, 66, 67); / SELECT CAST(CHAR(65 66, 67) as
CHAR);
Returns the string that results from concatenating the
CONCAT(str1, arguments. CONCAT() returns NULL if any argument is NULL.
str2, . . .) e.g.
• SELECT CONCAT('Mr. ' , ename) FROM emp;
ELT() returns the Nth element of the list of strings: str1 if N
= 1, str2 if N = 2, and so on. Returns NULL if N is less than 1
or greater than the number of arguments.
e.g.
ELT(N, str1,
str2, • SELECT ELT(1, 'Bank', 'Of', 'India', 'Kothrud', 'Pune');
str3, . . .)
• SELECT ELT(1, ename, job, sal) FROM emp;
String Functions
Syntax Result
STRCMP() returns 0 if the strings are the same, -1 if the first
STRCMP(expr1,
argument is smaller than the second according to the current
expr2)
sort order, and 1 otherwise.
LCASE(str) Returns lower case string. LCASE() is a synonym for LOWER().
UCASE(str) Returns upper case string. UCASE() is a synonym for UPPER().
LENGTH(str) Returns the length of the string.
LPAD(str, len, Returns the string str, left-padded with the string padstr to a
padstr) length of len characters.
RPAD(str, len, Returns the string str, right-padded with the string padstr to
padstr) a length of len characters.
Returns the leftmost len characters from the string str, or
LEFT(str, len)
NULL if any argument is NULL.
Returns the rightmost len characters from the string str, or
RIGHT(str, len)
NULL if any argument is NULL.
LTRIM(str) Returns the string str with leading space characters removed.
RTRIM(str) Returns the string str with trailing space characters removed.
Returns
• SELECT * FROM emp1 WHERE the string
ename str with
= BINARY leading and trailing space
UPPER(ename);
TRIM(str)
characters
• SELECT * FROM emp1 removed.
WHERE ename = BINARY LOWER(ename);
String Functions
Syntax Result
Returns the position of the first occurrence of substring
INSTR(str, substr)
substr in string str.
Returns the string str with all occurrences of the string
REPLACE(str, from_str replaced by the string to_str. REPLACE() performs
from_str, to_str) a case-sensitive match when searching for from_str.
e.g.
• SELECT REPLACE('Hello', 'l', 'x');
Returns the string str with the order of the characters
REVERSE(str)
reversed.
SUBSTR() is a synonym for SUBSTRING().
SUBSTR(str, pos, len) e.g.
• SELECT SUBSTR ('This is the test by IWAY', 6);
• SELECT SUBSTR ('This is the test by IWAY', -4, 4);
MID(str, pos, len) MID function is a synonym for SUBSTRING.
• SELECT ename, job, IF(ISNULL(phone), '**********', RPAD(LEFT(phone, 4), 10,
'*')) FROM emp;
• SELECT `user name`, IF(LENGTH(SUBSTR(`user name`, INSTR(`user name`,"
")))=0,"Weak User", `user name`) R1 FROM emp;
• SELECT LENGTH('saleel') - LENGTH(REPLACE('saleel', 'e', ''));
• SELECT emailid, REVERSE(SUBSTR(REVERSE(emailid), 5)) FROM emp;
Mathematical Functions
Mathematical Functions
Syntax Result
ABS(x) Returns the absolute value of X.
CEIL(x) CEIL() is a synonym for CEILING().
CEILING(x) Returns CEIL value.
FLOOR(x) Returns FLOOR value.
MOD(n, m),
Returns the remainder of N divided by M. MOD(N,0) returns
n % m,
NULL.
n MOD m
POWER(x, y) This is a synonym for POW().
RAND() Returns a random floating-point value
Rounds the argument X to D decimal places. The rounding
ROUND(x) algorithm depends on the data type of X. D defaults to 0 if
ROUND(x, d) not specified. D can be negative to cause D digits left of
the decimal point of the value X to become zero.
Returns the number X, truncated to D decimal places. If D is
0, the result has no decimal point or fractional part. D can
TRUNCATE(x, d)
be negative to cause D digits left of the decimal point of
the value X to become zero.
Mathematical Functions
e.g.
• SELECT CEIL(1.23);
• SELECT CEIL(-1.23);
• SELECT FLOOR(1.23);
• SELECT FLOOR(-1.23);
• SELECT ROUND(-1.23);
• SELECT ROUND(-1.58);
• SELECT ROUND(RAND() * 100);
• SELECT FLOOR(RAND() * 899999 +100000) OTP;
• SELECT weight, TRUNCATE(weight, 0) AS kg, MID(weight, INSTR(weight, ".") + 1)
AS gms FROM mass_table;
Note:
• TABLE always displays all columns of the table.
• TABLE does not support any WHERE clause.
• TABLE can be used with temporary tables.
TABLE statement…
TABLE is a DML statement introduced in MySQL 8.0.19 which returns rows and columns of the named table.
TABLE statement
The TABLE statement in some ways acts like SELECT. You can order and limit the number of rows produced by TABLE
using ORDER BY and LIMIT clauses, respectively.
• TABLE emp;
• TABLE emp ORDER BY 2;
• TABLE emp ORDER BY 2 LIMIT 1, 2;
• TABLE t1 UNION TABLE t2;
SELECT statement… syntax
SELECT is used to retrieve rows selected from one or more tables (using JOINS), and can include
UNION statements and SUBQUERIES.
SELECT statement
syntax
modifiers
SELECT [ALL / DISTINCT / DISTINCTROW] identifier.* / identifier.A1 [ [as]
alias_name], identifier.A2 [ [as] alias_name], identifier.A3 [ [as]
alias_name], expression1 [ [as] alias_name], expression2 [ [as] alias_name]
. . .
• [ FROM <identifier.r1> [as] alias_name], <identifier.r2> [as]
alias_name], . . . ]
• [ WHERE < where_condition1 > { and | or } < where_condition2 > . . . ]
• [ GROUP BY < { col_name | expr | position }, . . . [ WITH ROLLUP ] > ]
• [ HAVING < having_condition1 > { and | or } < having_condition2
> . . . ]
Remember
•
:
[ ORDER BY < { col_name | expr | position } [ ASC | DESC ], . . . > ]
• ALL (modifier is default) specifies that all matching rows should be returned, including duplicates.
•• [ LIMIT
DISTINCT < { [offset,]
(modifier) row_count
specifies removal | rows
of duplicate row_count OFFSET
from the result set. offset } > ]
• DISTINCTROW (modifier) is a synonym for DISTINCT.
•
• [ { INTO OUTFILE 'file_name' | INTO DUMPFILE 'file_name' | INTO
It is an error to specify both modifiers.
var_name [, var_name], . . . } ]
WHERE GROUP BY HAVING ORDER BY LIMIT
LIMIT ORDER BY
Nulls by default occur at the top, but you can use IsNull to assign default values, that will put it in the position
you require. . The ISNULL() function tests whether an expression is NULL. If expression is a NULL value, the
ISNULL() function returns 1. Otherwise, it returns 0.
ORDER BY Clause
To sort a result, use an ORDER BY clause.
Remember:
• The default sort order is ascending ASC, with smallest values first. To sort in descending (reverse) order, add
the DESC keyword to the name of the column you are sorting by.
• You can sort on multiple columns, and you can sort different columns in different directions.
• If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be sorted by expression
in ascending order. This is equivalent to ORDER BY expression ASC.
• Within each value of A1, results are sorted by A2 then within each value of A2, results are
sorted by A3
SELECT - ORDER BY
The ORDER BY clause is used to sort the records in your result set.
WHERE Clause
The WHERE Clause is used when you want to retrieve specific information from a table excluding
other irrelevant data.
Note:
Expressions in WHERE clause can use.
• Arithmetic operators
• Comparison operators
• Logical operators
SELECT - WHERE
We can use a conditional clause called WHERE clause to filter out results. Using WHERE clause, we can
specify a selection criteria to select required records from a table.
Note:
• All comparisons return FALSE when either argument is NULL, so no rows are ever selected.
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
] comparison_operator:
2. 5. logical_operators
= | <=> | >= | > | <= | < | <> AND | && | OR | ||
| !=
What will be the result of the query below?
• Logical AND. Evaluates to 1 if all operands are nonzero and not NULL, to 0 if one or more operands are 0,
otherwise NULL is returned.
• Logical OR. When both operands are non-NULL, the result is 1 if any operand is nonzero, and 0 otherwise.
With a NULL operand, the result is 1 if the other operand is nonzero, and NULL otherwise. If both operands are
NULL, the result is NULL.
• Logical NOT. Evaluates to 1 if the operand is 0, to 0 if the operand is nonzero, and NOT NULL returns NULL.
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
]
Comparison Functions and Operators
IS NULL / IS UNKNOWN NULL value test
IS NOT NULL / IS NOT
NOT NULL value test
UNKNOWN
If expr is NULL, ISNULL() returns 1, otherwise it
ISNULL(expr)
returns 0.
LEAST(value1, With two or more arguments, returns the smallest
value2, . . .) argument.
GREATEST(value1, value2, . With two or more arguments, returns the largest
SELECT
. .) GREATEST(10, 20, 30), argument.
# 30
LEAST(10, 20, 30); # 10
3. boolean_
predicate:
IS [NOT] NULL
| expr <=> null
IS NULL / IS NOT NULL
• "IS NULL" is the keyword that performs the Boolean comparison. It returns true if the supplied
value is NULL and false if the supplied value is not NULL.
• “IS NOT NULL" is the keyword that performs the Boolean comparison. It returns true if the
supplied value is not NULL and false if the supplied value is null.
Note:
• IS UNKNOWN is synonym of IS NULL.
• IS NOT UNKNOWN is synonym of IS NOT NULL.
IS NULL / IS NOT NULL
SELECT * FROM emp WHERE comm = NULL; # Empty
set
IN
expr [NOT] IN expr AND
predicate
| expr [NOT] IN (subquery)
The IN statement is used in a WHERE clause to choose items from a set. The IN operator allows you
to determine if a specified value matches any value in a set of values or value returned by a
subquery.
SELECT . . . FROM r1
WHERE (
state = 'VT' OR
state = 'NH' OR • SELECT . . . FROM r1 WHERE state IN ('VT', 'NH',
state = 'ME' OR 'ME', 'MA', 'CT', 'RI');
state = 'MA' OR • SELECT . . . FROM r1 WHERE state IN
state = 'CT' OR
(SELECT . . . );
state = 'RI'
);
IN
syntax
column | expression IN ( v1, v2, v3, . . . )
column | expression IN (subquery)
Remember:
• If a value in the column or the expression is equal to any value in the list, the result of the IN operator is TRUE.
• The IN operator is equivalent to multiple OR operators.
• To negate the IN operator, you use the NOT IN operator.
• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
job IN ('salesman', 'manager');
Remember: IN
• On the left side of the IN() predicate, the row constructor contains only column references.
• On the right side of the IN() predicate, there is more than one row constructor.
Note:
• if any input to the BETWEEN or NOT BETWEEN is NULL, then the result is UNKNOWN.
e.g.
SELET empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp
WHERE sal BETWEEN 1000 AND NULL;
• SELECT * FROM salespeople WHERE FORMAT(comm, 2) > 0.1 AND FORMAT(comm, 2) <
0.26;
between
• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
sal BETWEEN 1000 AND 3000;
READ WHERE SELECT
FROM output
identifier.ename identifier.*
emp
LIKE 'a%'
4. predicate:
expr [NOT] LIKE (expr [,
expr] ...)
Like
The LIKE operator is a logical operator that tests whether a string contains a specified pattern or not.
Like - String Comparison Functions
syntax
column | expression LIKE 'pattern' [ESCAPE
escape_character]
Remember:
• % matches any number of characters, even zero characters.
• _ matches exactly one character.
• If we use default escape character '\', then don’t use ESCAPE keyword.
Note:
• The ESCAPE keyword is used to escape pattern matching characters such as the (%) percentage and
underscore (_) if they form part of the data.
• If you do not specify the ESCAPE character, \ is assumed.
like
• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
ename LIKE 'a%';
like
What will be the result of the query below?
Remember:
• LIMIT enables you to pull a section of rows from the middle of a result set. Specify two values: The number
of rows to skip at the beginning of the result set, and the number of rows to return.
Note:
• Limit value are not to be given within ( . . . )
• Limit takes one or two numeric arguments, which must both be non-negative integer value.
SELECT - LIMIT
SELECT A1, A2, A3, . . . FROM r
[ LIMIT { [offset,] row_count | row_count OFFSET offset } ]
You can specify an offset using OFFSET from where SELECT will start returning records.
By default offset is zero.
This variable does not apply to SELECT statement that executed in the stored procedures or functions.
• SET SQL_SELECT_LIMIT=2;
• SET SQL_SELECT_LIMIT=DEFAULT;
aggregate functions
COUNT(*)
Note:
• The aggregate functions allow you to perform the calculation of a set of rows and return a single value.
• The WHERE clause cannot refer to aggregate functions. WHERE SUM(sal) = 5000 # Error
• The HAVING clause can refer to aggregate functions. HAVING SUM(sal) = 5000 # No Error
• Nesting of aggregate function is also not allowed.
e.g.
SELECT MAX(COUNT(*)) FROM emp GROUP BY deptno;
• Blank space between aggregate functions like (SUM, MIN, MAX, COUNT) are not allowed.
e.g.
SELECT SUM (sal) FROM emp;
• The GROUP BY clause is often used with an aggregate function to perform calculation and return a single
value for each subgroup.
Things to… Remember: aggregate functions
TODO
AVG([DISTINCT] expr)
• If there are no matching rows, AVG() returns NULL.
• AVG() may take a numeric argument, and it returns a average of non-NULL values.
e.g.
• SELECT AVG(1) "R1";
• SELECT AVG(null) "R1";
• SELECT AVG(1) "R1" WHERE True;
• SELECT AVG(1) "R1" WHERE False;
• SELECT AVG(1) "R1" FROM emp;
• SELECT AVG(sal) "R1" FROM emp WHERE empno = -1;
• SELECT AVG(sal) "Avg Salary" FROM emp;
• SELECT job, AVG(sal) "Avg Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO sal = { 1, 2, -1,
SUM([DISTINCT] expr)
3, -2, 1 }
• SELECT SUM(sal)
• If there are no matching rows, SUM() returns NULL.
• SUM() may take a numeric argument , and it returns a sum of non-NULL values. "R1"
e.g.
• SELECT SUM(1) "R1";
• SELECT SUM(null) "R1";
• SELECT SUM(2 + 2 * 2);
• SELECT SUM(1) "R1" WHERE True;
• SELECT SUM(1) "R1" WHERE False;
• SELECT SUM(1) "R1" FROM emp;
• SELECT SUM(sal) "R1" FROM emp WHERE empno = -1;
• SELECT SUM(sal) "Total Salary" FROM emp;
• SELECT job, SUM(sal) "Total Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO
MAX([DISTINCT] expr)
• If there are no matching rows, MAX() returns NULL.
• MAX() may take a string, number, and date argument, and it returns a maximum of non-NULL values.
e.g.
• SELECT MAX(1) "R1";
• SELECT MAX(null) "R1";
• SELECT MAX('VIKAS');
• SELECT MAX(1) "R1" WHERE True;
• SELECT MAX(1) "R1" WHERE False;
• SELECT MAX(1) "R1" FROM emp;
• SELECT MAX(sal) "R1" FROM emp WHERE empno = -1;
• SELECT MAX(sal) "Maximum Salary" FROM emp;
• SELECT job, MAX(sal) "Maximum Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO
MIN([DISTINCT] expr)
• If there are no matching rows, MIN() returns NULL.
• MIN() may take a string, number, and date argument, and it returns a minimum of non-NULL values.
e.g.
• SELECT MIN(1) "R1";
• SELECT MIN(null) "R1";
• SELECT MIN(1) "R1" WHERE True;
• SELECT MIN(1) "R1" WHERE False;
• SELECT MIN(1) "R1" FROM emp;
• SELECT MIN(sal) "R1" FROM emp WHERE empno = -1;
• SELECT MIN(sal) "Minimum Salary" FROM emp;
• SELECT job, MIN(sal) "Minimum Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO
COUNT(DISTINCT expr)
• If there are no matching rows, COUNT() returns 0.
• Returns a count of the number of non-NULL values.
• COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they
contain NULL values.
• COUNT (*) is a special implementation of the COUNT function that returns the count of all the rows in a
specified table.
• COUNT (*) also considers Nulls and duplicates.
e.g.
• SELECT COUNT(*) "R1";
• SELECT COUNT(null) "R1";
• SELECT COUNT(*) "R1" WHERE True;
• SELECT COUNT(*) "R1" WHERE False;
• SELECT COUNT(0) FROM emp;
• SELECT COUNT(1) FROM emp;
• SELECT COUNT(*) FROM emp WHERE empno = -1;
• SELECT COUNT(comm) "R1" FROM emp;
• SELECT job, COUNT(*) "R1" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO
GROUP_CONCAT([DISTINCT] expr
[ORDER BY {unsigned_integer | col_name |
expr} [ASC | DESC] [,col_name . . .]]
[SEPARATOR str_val])
e.g.
• SELECT job, GROUP_CONCAT(ename) FROM emp GROUP BY job;
G G (r)
A1, A2, . . ., An, F1(A1), F2(A2), . . ., Fm(Am)
GROUP BY Clause
Remember:
• Standard SQL does not allow you to use an ALIAS in the GROUP BY clause, however, MySQL supports this.
Note:
• DISTINCT (if used outside an aggregation function) that is superfluous.
e.g.
SELECT DISTINCT COUNT(ename) FROM emp;
SELECT - GROUP BY
• Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names,
column aliases, or column positions. Column positions are integers and begin with 1
• If you use GROUP BY, output rows are sorted according to the GROUP BY columns as if you had an ORDER
BY for the same columns. To avoid the overhead of sorting that GROUP BY produces, add ORDER BY NULL.
• MySQL extends the GROUP BY clause so that you can also specify ASC and DESC after columns named in
the clause
• If a query includes GROUP BY but you want to avoid the overhead of sorting the result, you can suppress
sorting by specifying ORDER BY NULL.
For example:
• SELECT job, COUNT(*) FROM emp GROUP BY job ORDER BY NULL;
• SELECT * FROM emp ORDER BY FIELD (job, 'MANAGER',
'SALESMAN');
This function's will produce a single value for an
entire group or a table.
SELECT - GROUP BY
You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that
column.
r3 . . .
• SELECT job, SUM(sal) FROM emp GROUP BY job;
[GROUP
• SELECT BY {G1, G2, FROM
job, SUM(sal)
. .emp
. |GROUP
exprBY| job
position},
WITH
. . .
ROLLUP;
[WITH ROLLUP]]
READ GROUP BY SELECT
FROM jo output
identifier.job identifier.Job,
emp b
SUM(sal)
SELECT - GROUP BY
Examples:
HAVING Clause
The MySQL HAVING clause is used in the SELECT statement to specify filter conditions for a group
of rows. HAVING clause is often used with the GROUP BY clause. When using with the GROUP
BY clause, we can apply a filter condition to the columns that appear in the GROUP BY clause.
Note:
• HAVING is merged with WHERE if you do not use GROUP BY or Aggregate Functions (COUNT(), MIN(),
and so on).
SELECT - HAVING
SELECT G1, G2, . . . , F1(A1), F2(A2), . . . from r1, r2,
r3 . . .
Remember:
• WHERE clause can be used with - SELECT, UPDATE, and DELETE statements, where as HAVING
clause can only be used with the SELECT statement.
• WHERE clause filters rows before aggregation (GROUPING), where as, HAVING clause filters groups,
after the aggregations are performed.
• Aggregate functions (SUM , MIN, MAX, AVG and COUNT) cannot be used in the WHERE clause, unless
it is in a sub query contained in a WHERE or HAVING clause, whereas, aggregate functions can be used
in HAVING clause.
Note:
• The WHERE clause acts as a pre-filter where as HAVING clause acts as a post-filter.
WHERE Vs HAVING
WHERE VS HAVING
WHERE HAVING
Implemented in row operations. Implemented in column operations.
Single row Summarized row or group or rows.
It only fetches the data from particular rows or table It only fetches the data from grouped data according to
according to the condition. the condition.
Aggregate Functions ccannot appear in WHERE clause. Aggregate Functions Can appear in HAVING clause.
Used with SELECT and other statements such as Used with SELECT statement only.
UPDATE, DELETE or either one of them.
Pre-filter Post-filter
GROUP BY Comes after WHERE. GROUP BY Comes before HAVING.
window function
FIFA / Forbes window function
Note:
MySQL does not support these window function features.
• DISTINCT syntax for aggregate functions.
• Nested window functions
User-Defined Variables
User-Defined Variables
Remember:
• A user variable name can contain other characters if you quote it as a string or identifier (for example,
@'my-var', @"my-var", or @`my-var`).
• User-defined variables are session specific. A user variable defined by one client cannot be seen or used by
other clients.
• All variables for a given client session are automatically freed when that client exits.
• User variable names are not case sensitive. Names have a maximum length of 64 characters.
• If the value of a user variable is selected in a result set, it is returned to the client as a string.
• If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.
User-Defined Variables
You can store a value in a user-defined variable in one statement and refer to it later in another statement. This
enables you to pass values from one statement to another.
Sub-Queries
A subquery is a SELECT statement within another statement.
Note:
• You may use comparison operators such as <>, <, >, <=, and >= with a single row subquery.
• Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN, ANY, or
ALL operator in outer query to handle a subquery that returns multiple rows.
A subquery is a SELECT statement within another statement. Subqueries
Remember:
A subquery may occur in:
• A SELECT clause
• A FROM clause
• A WHERE clause
• A HAVING clause
Note:
A subquery's outer statement can be any one of :
• SELECT
• INSERT
• UPDATE
• DELETE
Single Row Subqueries
A single row subquery returns zero or one row to the outer SQL statement. You can place a
subquery in a WHERE clause, a HAVING clause, or a FROM clause of a SELECT statement.
• Subqueries with ALL, ANY, IN, or SOME – WHERE / HAVING clause (Multiple row subquery)
• Row Subqueries
The Subquery as Scalar Operand
The Subquery as Scalar Operand
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM r
Remember:
• A scalar subquery is a subquery that returns exactly one column value from one row.
• A scalar subquery is a simple operand, and you can use it almost anywhere a single column value is legal.
Note:
• If the subquery returns 0 rows then the value of scalar subquery expression is null.
• if the subquery returns more than one row then MySQL returns an error.
Think:
• SELECT (SELECT 1, 2); #error
• SELECT (SELECT ename, sal FROM emp); #error
• SELECT (SELECT * FROM emp); #error
• SELECT (SELECT NULL + 1);
• SELECT ename, (SELECT dname FROM dept WHERE emp.deptno = dept.deptno) R1 FROM
emp ;
The Subquery as Scalar Operand
e.g.
• SELECT (SELECT stdprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) AS "Standard Price", (SELECT minprice FROM price WHERE prodid = 100890
and enddate IS NOT NULL) AS "Minimum Price";
• SELECT (SELECT stdprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) - (SELECT minprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) AS "Price Difference";
Subquery in the FROM Clause
Subqueries in the FROM Clause
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM (subquery) [AS] name . . .
Note:
• Every table in a FROM clause must have a name, therefore the [AS] name clause is mandatory.
• SET @x :=0;
SELECT * FROM (SELECT @x := @x + 1 as R1, emp.* FROM emp) DT WHERE R1 = 5;
• SELECT * FROM (SELECT @cnt := @cnt + 1 R1, MOD(@cnt,2) R2, emp.* FROM emp, (SELECT
@cnt:=0) DT1 ) DT2 WHERE R2 = 0;
• SELECT MIN(R1) FROM (SELECT COUNT(job) R1 FROM emp GROUP BY job) DT;
• SELECT MAX(R1) FROM (SELECT COUNT(*) R1 FROM actor_movie GROUP BY actorid) DT
SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS
sum_column1
Comparisons using Subquery
Comparisons using Subqueries
Comparison Operators like : =, !=/<>, >, >=, <, <= ,<=>
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM r WHERE p =
(subquery)
Remember:
• A subquery can be used before or after any of the comparison operators.
• The subquery can return at most one value.
• The value can be the result of an arithmetic expression or a function.
Movie _Actor
• The ANY keyword, which must follow a comparison operator, means return TRUE if the comparison is TRUE
for ANY of the values in the column that the subquery returns.
• The word ALL, which must follow a comparison operator, means return TRUE if the comparison is TRUE for
ALL of the values in the column that the subquery returns.
• IN and =ANY are not synonyms when used with an expression list. IN can take an expression list, but = ANY
cannot.
empty table
The expression is TRUE, if table T2 is empty.
You can use a subquery after a comparison operator, followed by the keyword IN, ALL, ANY, or SOME.
• SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM emp WHERE deptno = 10 or
deptno = 20);
• SELECT * FROM emp WHERE sal >ALL (SELECT sal FROM emp WHERE ename = 'ADAMS' or
ename = 'TURNER');
• SELECT * FROM emp WHERE sal >ANY (SELECT sal FROM emp WHERE ename = 'ADAMS' or
ename = 'TURNER');
•SELECT
SELECT * FROM
* FROM emp WHERE
d1 WHERE sal
c1 not in >SOMEmin(c1)
(SELECT (SELECT sal
FROM FROM emp
d1 GROUP WHEREdname,
BY deptno, enameloc,=walletid)
'ADAMS' or
ORDER
BYename
deptno; = 'TURNER');
Row Subquery
Row Subqueries
Scalar or column Subqueries return a single value or a column of values. A row subquery is a subquery
variant that returns a single row and can thus return more than one column value. You can use = , >, <,
>=, <=, <>, !=, <=>
1. SELECT * from EMP where deptno, 1 = (SELECT deptno, 1 from DEPT where
deptno=10);
2. SELECT * FROM emp WHERE ROW (deptno, 1) = (SELECT deptno, 1 FROM dept WHERE
deptno = 10);
Subquery with EXISTS or NOT
EXISTS
Subqueries with EXISTS or NOT EXISTS
The EXISTS operator tests for the existence of rows in the results set of the subquery. If a subquery row value
is found, EXISTS subquery is TRUE and in this case NOT EXISTS subquery is FALSE.
• SELECT * FROM emp WHERE EXISTS (SELECT * FROM dept WHERE emp.deptno =
dept.deptno);
• SELECT * FROM emp WHERE NOT EXISTS (SELECT deptno FROM emp WHERE emp.deptno =
dept.deptno);
• SELECT * FROM emp m WHERE EXISTS (SELECT * FROM emp e WHERE e.mgr = m.empno);
• SELECT * FROM emp m WHERE NOT EXISTS (SELECT * FROM emp e WHERE e.mgr =
m.empno);
JOINS
JOINS
• Natural Join
• Simple Join
• Self Join
Cartesian or Product JOIN
• Cartesian/Product means Number of Rows present in Table 1 Multiplied by Number of Rows present in
Table 2.
• Cross Join in MySQL does not require any common column to join two table.
JOINS - Cartesian or Product
The CROSS JOIN gets a row from the first table (r1) and then creates a new row for every row in the second
table (r2). It then does the same for the next row for in the first table (r1) and so on.
r1 r2
Customer-1 Supplier-1 Customer-1 Supplier-1
Customer-1 Supplier-2
Cusomer-2 cross join Supplier-2 Customer-1 Supplier-3
= Cusomer-2 Supplier-1
Customer-3 Supplier-3
Cusomer-2 Supplier-2
Cusomer-2 Supplier-3
Customer-3 Supplier-1
Customer-3 Supplier-2
Customer-3 Supplier-3
JOINS - Cartesian or Product
The CROSS JOIN gets a row from the first table (r1) and then creates a new row for every row in the second
table (r2). It then does the same for the next row for in the first table (r1) and so on.
JOINS - Cartesian or Product
Cartesian or Product joins are joins without a join condition. Each row of one table is combined with each row of
another table. The result is referred to as a Cartesian product.
• Warehouse/ X
product
• Product/
sales_channel
• Cards
JOINS - Cartesian or Product
SELECT A1, A2, A3, . . . FROM r1, r2, . . .
• SELECT * FROM menucard, softdrink;
JOINS - Cartesian or Product
SELECT A1, A2, A3, . . . FROM r1, r2, . . .
• SELECT mnu.name, sftdrink.name, mnu.rate, sftdrink.rate, mnu.rate + sftdrink.rate
as "Total" FROM menucard mnu, softdrink sftdrink;
JOINS - Cartesian or Product
• SELECT name, COUNT(*) "Total Employees", rate * COUNT(*) "Total Cost" FROM emp,
softdrink GROUP BY name;
JOINS – Cross Join
The CROSS JOIN produced a result set which is the product of rows of two associated tables when no WHERE
clause is used with CROSS JOIN. In this join, the result set appeared by multiplying each row of the first table
with all rows in the second table if no condition introduced with CROSS JOIN.
envelope docs
Table Table
r1 r2
r1 = {1, 2, 3, 4}
r2 = {(1, a), (2, b), (1, c), (3, d), (2, e), (1, f)}
r1 = r2
R = {(1,1,a),
(2,2,b),
(1,1,c),
(3,3,d),
(2,2,e),
(1,1,f)}
JOINS – equi join
• SELECT * FROM emp , dept WHERE emp.deptno = dept.deptno;
tableA tableB JOINS – equi join
Table Table
Note:
• ON clause is optional, If not given then INNER JOIN works like CROSS JOIN.
JOINS – ON & USING clause example
The ON clause
The ON clause is used to join tables where the column names don’t match in both tables.
JOINING CONDITION
JOINING CONDITION
Inner JOIN
The inner join is one of the most commonly used joins in SQL. The inner join clause allows you to
query data from two or more related tables.
INNER JOIN returns rows when there is at least one
match in both tables.
JOINS – Inner Join
The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. An SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables.
The NATURAL JOIN is such a join that performs the same task as an INNER JOIN.
A NATURAL JOIN can be used with a LEFT OUTER join, or a RIGHT OUTER join.
Inner Join joins two table on the basis of the column which is Natural Join joins two tables based on same attribute
explicitly specified in the ON clause. name.
In Natural Join, The resulting table will contain all
In Inner Join, The resulting table will contain all the attribute
the attributes of both the tables but keep only one
of both the tables including duplicate columns also
copy of each common column
SYNTAX:
• SELECT * FROM r1 INNER JOIN r2 ON r1.A1 =
r2.A1; SYNTAX:
• SELECT * FROM r1 INNER JOIN r2 USING(A1, • SELECT * FROM r1 NATURAL JOIN r2;
[A2]);
Simple JOIN
TODO
JOINS – Simple Join
The SIMPLE JOIN is such a join that performs the same task as an INNER JOIN.
JOINING CONDITION
The ON clause is required for a left or right outer join.
Outer JOINS
In an outer join, along with rows that satisfy the matching criteria, we also include some or all rows
that do not match the criteria.
SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
SELECT * FROM orders ord LEFT OUTER JOIN employee emp ON emp.id = ord.employeeid;
JOINS – Left Outer Join
• SELECT * FROM student LEFT OUTER JOIN student_order ON student.id =
student_order.studentid ;
JOINS – Left Outer Join
The LEFT JOIN keyword returns all rows from the left table (r1), with the matching rows in the right table (r2).
The result is NULL in the right side when there is no match.
SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
WHERE r2. A1 IS NULL
SELECT * FROM orders ord LEFT OUTER JOIN employee emp ON emp.id = ord.employeeid
WHERE emp.id IS NULL;
JOINS – Left Outer Join
• SELECT * FROM student LEFT OUTER JOIN student_order ON student.id =
student_order.studentid WHERE student_order.studentID IS NULL;
JOINS – Left Outer Join
The LEFT JOIN keyword returns all rows from the left table (r1), with the matching rows in the right table (r2).
The result is NULL in the right side when there is no match.
SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 USING (A1, . . .)
SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
SELECT * FROM orders ord RIGHT OUTER JOIN employee emp ON emp.id =
ord.employeeid;
JOINS – Right Outer Join
• SELECT * FROM student RIGHT OUTER JOIN student_order ON student.id =
student_order.studentid;
JOINS – Right Outer Join
The RIGHT JOIN keyword returns all rows from the right table (r2), with the matching rows in the left table (r1).
The result is NULL in the left side when there is no match.
SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
WHERE r1. A1 IS NULL
SELECT * FROM orders ord RIGHT OUTER JOIN employee emp ON emp.id = ord.employeeid
WHERE ord.employeeid IS NULL;
JOINS – Right Outer Join
• SELECT * FROM student RIGHT OUTER JOIN student_order ON student.id =
student_order.studentid WHERE student.ID IS NULL;
JOINS – Right Outer Join
The RIGHT JOIN keyword returns all rows from the right table (r2), with the matching rows in the left table (r1).
The result is NULL in the left side when there is no match.
SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 USING (A1, . . .)
Self JOINS
TODO
JOINS – Self Join
A SELF JOIN is a join in which a table is joined with itself (which is also called Unary relationships), especially
when the table has a FOREIGN KEY which references its own PRIMARY KEY.
• (SELECT deptno FROM emp LIMIT 1) UNION (SELECT deptno FROM dept LIMIT 1);
• SELECT 'EMP' as 'Table Name', COUNT(*) FROM emp UNION SELECT 'DEPT', COUNT(*)
FROM dept UNION SELECT 'BONUS', COUNT(*) FROM bonus;
UNION
books newbooks Output
An INTERSECT query returns the intersection of 2 or more datasets. If a record exists in both data sets, it
will be included in the INTERSECT results.
Note:
• There is no INTERSECT operator in MySQL, you can easily simulate this type of query using either the IN
clause or the EXISTS clause.
• SELECT * FROM oldbook oldbk WHERE EXISTS (SELECT * FROM newbook newbk WHERE
oldbk.id = newbk.id and oldbk.name = newbk.name);
INTERSECT
books newbooks Output
• SELECT bookName, type FROM books WHERE EXISTS ( SELECT bookname, type FROM
newbooks WHERE books.bookName = newbooks.bookName);
• SELECT bookName, type FROM books WHERE bookName IN (SELECT bookName FROM
newbooks);
MINUS
The MINUS operator takes the distinct rows of one query and returns the rows that do not appear in a
second result set.
Note:
• There is no MINUS operator in MySQL, you can easily simulate this type of query using either the NOT IN
clause or the NOT EXISTS clause.
Note: MINUS
• There is no MINUS operator in MySQL, you can easily simulate this type of query using either the NOT IN
clause or the NOT EXISTS clause.
Output
e.g.
• SELECT bookName, type FROM books WHERE NOT EXISTS
(SELECT bookName, type FROM newbooks WHERE
books.bookName = newbooks.bookName);
INSERT ROWS
INSERT command inserts new rows into an existing table.
The affected-rows value for an INSERT can be obtained using the ROW_COUNT() function.
Column Values
Column List
e.g.
• INSERT INTO student VALUES (29, 'sharmin', 'patil', '1999-11-10',
'[email protected]');
• INSERT INTO student (ID, nameFirst, nameLast, DOB, emailID) VALUES (30, 'john',
'thomas', '1983-11-10', '[email protected]');
• INSERT INTO student (ID, nameFirst, emailID) VALUES (31, 'jack', '1980-01-14',
'[email protected]');
• INSERT INTO student (ID, nameFirst) VALUES (32, 'james'), (33, 'jr. james'),
INSERT ROWS using SET
DML- INSERT …SET
INSERT inserts new rows into an existing table. The INSERT ... SET forms of the statement insert rows based
on explicitly specified values.
Note:
• A SET clause indicates columns explicitly by name, together with the value to assign each one.
• The affected-rows value for an INSERT can be obtained using the ROW_COUNT() function.
INSERT ROWS using SELECT
INSERT ... SELECT
With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables.
• set @x := 40;
• INSERT INTO dept VALUES (@x := @x + 1 , 'HRD', 'BARODA', 'r57px33px’);
Note:
Here c1 column is a Primary Key
• UPDATE temp SET c1 = c1 - 1 ORDER BY c1 ASC; # In case
of decrement
Single-table UPDATE
• UPDATE temp SET c1 = c1 + 1 ORDER BY c1 DESC; # In case of
increment
• SET @x := 0;
• UPDATE emp SET id = @x:= @x+1;
Note:
• LIMIT clauses apply to single-table deletes, but not multi-table deletes.
DELETE command activates the trigger applied on the TRUNCATE command does not activate the triggers to
table and causes them to fire. fire.
DELETE command eliminate the tuples one-by-one. TRUNCATE delete the entire data page containing the
tuples.
DELETE command lock the row/tuple before deleteing it. TRUNCATE command lock data page before deleting
table data.
DELETE command acts slower as compared to TRUNCATE is faster as compared to DELETE.
TRUNCATE.
DELETE records transaction log for each deleted tuple. TRUNCATE record transaction log for each deleted data
page.
DELETE command can be followed either by COMMIT TRUNCATE command can't be ROLLBACK.
or ROLLBACK.
The char is a fixed-length character data type, CREATE TABLE TEMP (C1 CHAR(10), C2
The varchar is a variable-length character data
VARCHAR(10));
type.
TE TABLE `123` (c1 INT, c2 VARCHAR(10)); INSERT INTO TEMP VALUES('SALEEL',
'SALEEL’);
When CHAR values are retrieved, the trailing spaces are removed
In MySQL (unless the PAD_CHAR_TO_FULL_LENGTHSQL mode is enabled)
By default, trailing spaces are trimmed from CHAR column values on retrieval. If
PAD_CHAR_TO_FULL_LENGTH is enabled, trimming does not occur and retrieved CHAR values are
padded to their full length.
Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the
decimal point.
CREATE TABLE tasks ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255) NOT
NULL, completed BOOLEAN);
• INSERT INTO tasks VALUE(default, 'Task1', 0);
• INSERT INTO tasks VALUE(default, 'Task2', 1);
• INSERT INTO tasks VALUE(default, 'Task3', False);
• INSERT INTO tasks VALUE(default, 'Task4', True);
• INSERT INTO tasks VALUE(default, 'Task5', null);
• INSERT INTO tasks VALUE(default, 'Task6', default);
• INSERT INTO tasks VALUE(default, 'Task7', 1>2);
• INSERT INTO tasks VALUE(default, 'Task8', 1<2);
• INSERT INTO tasks VALUE(default, 'Task9', 12);
• INSERT INTO tasks VALUE(default, 'Task10', 58);
• INSERT INTO tasks VALUE(default, 'Task11', .75);
• INSERT INTO tasks VALUE(default, 'Task12', .15);
• INSERT INTO tasks VALUE(default, 'Task13', 'a' = 'a');
Note:
• BOOL and BOOLEAN are synonym of TINYINT(1)
• An ENUM column can have a maximum of 65,535 distinct elements. dataType – ENUM
• ENUM values are sorted based on their index numbers, which depend on the order in which the
enumeration members were listed in the column specification.
• Default value, NULL if the column can be NULL, first enumeration value if NOT NULL
• CREATE TABLE temp (col1 INT, COL2 ENUM('A','B','C') NULL);
• INSERT INTO temp(col1) VALUES (1);
• CREATE TABLE temp (col1 INT, col2 ENUM('A','B','C') NOT NULL);
• INSERT INTO temp(col1) VALUES (1);
• CREATE TABLE temp (col1 INT, col2 ENUM('') NOT NULL);
• INSERT INTO temp (col1) VALUES (1,'THIS IS THE TEST');
• SET column values that consist of multiple set members are specified with members separated
by commas (,).
JSON Datatype
Datatype – JSON
JSON (JavaScript Object Notation) documents.
• INSERT INTO e VALUES (' [{"empno" : "1004", "ename" : "ram" ,"phone" : [6672,
8811], "address" : "Paud Road"}, {"empno" : "1005", "ename" : "sham" ,"phone" :
[6672, 8843], "address" : "Paud Road"} ]');
Datatype – JSON … (Select)
MySQL supports a native JSON data type that enables efficient access to data in JSON (JavaScript Object
Notation) documents.
CREATE TABLE
Use a CREATE TABLE statement to specify the layout of your
table.
Remember:
• by default, tables are created in the default database, using the InnoDB storage engine.
• error occurs if the table exists
• error occurs if there is no default database
• error occurs if the database does not exist.
Create Table
syntax
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
e.g.
[table_options]
[partition_options] • CREATE TABLE student (
ID int,
create_definition: firstName
col_name column_definition VARCHAR(45),
lastName
column_definition: VARCHAR(45),
data_type [NOT NULL | NULL] [DEFAULT default_value] DoB DATE,
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] emailID
[COMMENT 'string'] VARCHAR(128)
[reference_definition] );
| data_type [GENERATED ALWAYS] AS (expression)
[VIRTUAL] [UNIQUE [KEY]] [COMMENT comment]
[NOT NULL | NULL] [[PRIMARY] KEY]
table_options:
ENGINE [=] engine_name show engines;
set default_storage_engine = memory;
• MEMORY tables are visible to
Create Table
another client.
• Structure is stored and rows will be show engines;
removed, after re-starting mysql set default_storage_engine = memory;
server.
• A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is
closed.
• Use TEMPORARY table with the same name as the original can be useful when you want to try some
statements that modify the contents of the table, without changing the original table.
• The permanent (original) table becomes hidden (inaccessible) to the client who creates the TEMPORARY
table with same name as the original.
• If you issue a DROP TABLE statement, the TEMPORARY table is removed and the original table reappears, it
is possible, only when then original tbl_name and temporary tbl_name are same.
• The original table also reappears if you rename the TEMPORARY table.
e.g. ALTER TABLE dept RENAME TO d;
Temporary
table_name
Temporary Table
e.g.
CREATE TEMPORARY TABLE STUDENT (
ID INT PRIMARY KEY,
namefirst VARCHAR(45),
namelast VARCHAR(45),
DOB DATE,
emailID VARCHAR(128)
);
CREATE TEMPORARY TABLE TEMP (
ID INT PRIMARY KEY,
firstName VARCHAR(45),
phone INT,
city VARCHAR(10) DEFAULT 'PUNE',
salary INT,
comm INT,
total INT GENERATED ALWAYS AS(salary + comm)
VIRTUAL
);
CREATE TEMPORARY TABLE ... LIKE
Use CREATE TABLE ... LIKE to create an empty table based on the definition of another table.
Remember:
• LIKE works only for base tables, not for VIEWS.
• You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the
current session, and is dropped automatically when the session is closed.
• Use TEMPORARY table with the same name as the original can be useful when you want to try some
statements that modify the contents of the table, without changing the original table.
Remember:
• There can be only one AUTO_INCREMENT column per table.
• it must be indexed.
• it cannot have a DEFAULT value.
• it works properly only if it contains only positive values.
• It applies only to integer and floating-point types.
• when you insert a value of NULL or 0 into AUTO_INCREMENT column, it generates next value.
• use LAST_INSERT_ID() function to find the row that contains the most recent AUTO_INCREMENT value.
• SELECT @@IDENTITY
• SELECT LAST_INSERT_ID()
• SET INSERT_ID = 7
auto_increment
The auto_increment specifies a auto_increment value for the column.
GENERATED column
Remember:
• Stored functions and user-defined functions are not permitted.
• Stored procedure and function parameters are not permitted.
• Variables (system variables, user-defined variables, and stored program local variables) are not permitted.
• Subqueries are not permitted.
• The AUTO_INCREMENT attribute cannot be used in a generated column definition.
• Triggers cannot use NEW.COL_NAME or use OLD.COL_NAME to refer to generated columns.
Note:
• The expression can contain literals, built-in functions with no parameters, operators, or references to any
column within the same table. If you use a function, it must be scalar and deterministic.
Virtual column - GENERATED ALWAYS
col_name data_type [GENERATED ALWAYS] AS (expression) [VIRTUAL | STORED] [NOT NULL | NULL]
[UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string']
• VIRTUAL: Column values are not stored, but are evaluated when rows are read, immediately after any
BEFORE triggers. A virtual column takes no storage.
• STORED: Column values are evaluated and stored when rows are inserted or updated. A stored column does
require storage space and can be indexed.
Note:
• The default is VIRTUAL if neither keyword is specified.
zerofill value
When you select a column with the type ZEROFILL it pads the displayed value of the field with zeros up to the
display width specified in the column definition.
Note:
• ZEROFILL attribute is use for numeric datatype.
• If you specify ZEROFILL for a column, MySQL automatically adds the UNSIGNED attribute to the column.
zerofill column
col_name data_type ZEROFILL
Note:
• If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the
column.
CONSTRAINTS
CONSTRAINT is used to define rules to allow or restrict what values can be stored in columns. The
purpose of inducing constraints is to enforce the integrity of a database.
CONSTRAINTS
To limit or to restrict or to check or to control.
Note:
• a table with a foreign key that references another table's primary key is MUL.
• If more than one of the Key values applies to a given column of a table, Key displays the one with the
highest priority, in the order PRI, UNI, and MUL.
Keys are used to establish relationships between tables
and also to uniquely identify any record in the table. types of Keys?
r = Employee(EmployeeID, FullName, job, salary, PAN,
DateOfBirth, emailID, deptno)
• Candidate Key: are individual columns in a table that qualifies for uniqueness of all the rows. Here in Employee
table EmployeeID, PAN or emailID are Candidate keys.
• Primary Key: is the columns you choose to maintain uniqueness in a table. Here in Employee table you can
choose either EmployeeID, PAN or emailID columns, EmployeeID is preferable choice.
• Alternate Key: Candidate column other the primary key column, like if EmployeeID is primary key then , PAN
or emailID columns would be the Alternate key.
• Super Key: If you add any other column to a primary key then it become a super key, like EmployeeID +
FullName is a Super Key.
• Composite Key: If a table do not have any single column that qualifies for a Candidate key, then you have to
select 2 or more columns to make a row unique. Like if there is no EmployeeID, PAN or emailID columns, then
you can make FullName + DateOfBirth as Composite key. But still there can be a narrow chance of duplicate
row.
Candidate Key
Primary Key
Composite Key
Alternate Key
Remember:
• A primary key cannot be NULL.
• A primary key value must be unique.
• A table has only one primary key.
• The primary key values cannot be changed, if it is referred by some other column.
• The primary key must be given a value when a new record is inserted.
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
PRIMARY KEY (column1, column2, . .
. column_n)
• CREATE TABLE vendors (
vendor_id INT,
vendor_name
VARCHAR(25),
address VARCHAR(255)
);
• ALTER TABLE vendors ADD PRIMARY KEY(vendor_id);
• ALTER TABLE vendors ADD constraint pk_vendor_id PRIMARY KEY(vendor_id);
syntax
ALTER TABLE table_name
DROP PRIMARY KEY
syntax
ALTER TABLE table_name
DROP PRIMARY KEY
Note:
• Unique key in a relation is always associated with an INDEX object.
Constraints – Add Unique Key
col_name data_type UNIQUE KEY
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
UNIQUE (column1, column2, . . .
column_n)
• CREATE TABLE shop (
ID INT,
shop_name VARCHAR(30)
);
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
UNIQUE (column1, column2, . . .
column_n)
• ALTER TABLE users DROP INDEX <COLUMN_NAME>;
• ALTER TABLE users DROP INDEX U_USER_ID; #CONSTRAINT NAME
Remember:
• A foreign key can have a different name from its primary key.
• DataType of primary key and foreign key column must be same.
• It ensures rows in one table have corresponding rows in another.
• Unlike the Primary key, they do not have to be unique.
• Foreign keys can be null even though primary keys can not.
Note:
• The table containing the FOREIGN KEY is referred to as the child table, and the table containing the
PRIMARY KEY (referenced key) is the parent table.
• PARENT and CHILD tables must use the same storage engine,
• and they cannot be defined as temporary tables.
Constraints – Foreign Key
A referential constraint could be violated in following cases.
• An INSERT attempt to add a row to a child table that has a value in its foreign key columns that does not match
a value in the corresponding parent table's column.
• An UPDATE attempt to change the value in a child table's foreign key columns to a value that has no matching
value in the corresponding parent table's parent key.
• An UPDATE attempt to change the value in a parent table's parent key to a value that does not have a
matching value in a child table's foreign key columns.
• A DELETE attempt to remove a record from a parent table that has a matching value in a child table's foreign
key columns.
Note:
• PARENT and CHILD tables must use the same storage engine,
• and they cannot be defined as temporary tables.
• If we don’t give constraint name. System will automatically generated the constraint name and
will assign to foreign key constraint. e.g. login_ibfk_1, login_ibfk_2, …..
Anomaly – (Primary Key/Foreign Key)
Remember:
student Table student_course Table
RollNo Name Mobile City State isActive RollNo CourceDuration CourceName
1 Ramesh ●●●● Pune MH 1 1 1.5 month RDBMS
2 Amit ●●●● Baroda GJ 1 2 1.2 month NoSQL
3 Rajan ●●●● Surat GJ 1 3 2 month Networking
4 Bhavin ●●●● Baroda GJ 1 1 2 month Java
5 Pankaj ●●●● Surat GJ 1 2 2 month .NET
Insertion anomaly:
• If we try to insert a record in Student_Course table with RollNo = 7, it will not allow.
• If you try to chance the RollNo from Student table with RollNo = 6 whose RollNo = 1 , it will not allow.
• If you try to chance the RollNo from Student_Course table with RollNo = 9 whose RollNo = 3 , it will not allow.
• If we try to delete a record from Student table with RollNo = 1, it will not allow.
Alter, Drop – (Primary Key/Foreign Key)
Remember:
student = { student_course = {
rollno INT, * (PK) rollno INT, * (FK)
name VARCHAR(10), courceduration VARCHAR(10),
mobile VARCHAR(10), courcename VARCHAR(10)
city VARCHAR(10), }
state VARCHAR(10),
isActive BOOL
}
DDL command could be violated in following cases.
Alter command:
• If we try to modify datatype of RollNo in Student or Student_Course table with VARCHAR, it will not allow.
• If we try to apply auto_increment to RollNo in Student table, it will not allow
• If we try to drop RollNo column from Student table , it will not allow.
Drop command:
• If we try to drop Student table, it will not allow.
Constraints – Foreign Key
A foreign key is a field in a table that matches another field of another table. A foreign key places constraints on data in the
related tables, which enables MySQL to maintain referential integrity.
Alter
Constraints – Add Foreign Key using Alter
You can use the ALTER TABLE statement to ADD FOREIGN KEY on existing column.
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
FOREIGN KEY (child_col1, child_col2, . . .
child_col_n)
REFERENCES parent_table (parent_col1,
parent_col2, . . .( parent_col_n); CREATE TABLE login (
CREATE TABLE users
ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userID INT,
password VARCHAR(255), loginDate DATE,
email VARCHAR(255) UNIQUE loginTime TIME
KEY ) ;
) ;
• ALTER TABLE login ADD FOREIGN KEY(userID) REFERENCES users(ID);
• ALTER TABLE login ADD constraint fk_userID FOREIGN KEY(userID) REFERENCES
users(ID);
syntax
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name
• constraint
SELECT name.
TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE FROM information_schema.table_constraints WHERE
TABLE_SCHEMA='DB2’;
On DELETE / On UPDATE – Foreign Key
SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child
table to NULL. If you specify a SET NULL action, make sure that you have not declared the columns in the child
table as NOT NULL.
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is
the same as omitting the ON DELETE or ON UPDATE clause.
NO ACTION: Is equivalent to RESTRICT. The MySQL Server rejects the delete or update operation for the parent
table if there is a related foreign key value in the referenced table.
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions
containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.
1. CREATE TABLE TEST (c1 INT, c2 INT, c3 INT,
check (c3 = SUM(c1)));
// ERROR
Check Constraint
Constraints – Check
CHECK condition expressions must follow some rules.
• Literals, deterministic built-in functions, and operators are permitted.
• Non-generated and generated columns are permitted, except columns with the AUTO_INCREMENT attribute.
• Sub-queries are not permitted.
• Environmental variables (such as CURRENT_USER, CURRENT_DATE, …) are not permitted.
• Non-Deterministic built-in functions (such as AVG, COUNT, RAND, LAST_INSERT_ID, FIRST_VALUE,
LAST_VALUE, ...) are not permitted.
• Variables (system variables, user-defined variables, and stored program local variables) are not permitted.
• Stored functions and user-defined functions are not permitted.
Note:
Prior to MySQL 8.0.16, CREATE TABLE permits only the following limited version of table CHECK constraint
syntax, which is parsed and ignored.
Remember:
If you omit the constraint name, MySQL automatically generates a name with the following convention:
• table_name_chk_n
Constraints – Check
col_name data_type CHECK(expr)
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
CHECK (conidiation)
Note:
• you can add or delete columns,
• create or destroy indexes,
• change the type of existing columns, or
• rename columns or the table itself.
Alter Table
syntax
ALTER TABLE tbl_name
[alter_specification [, alter_specification] . . .
Note:
• To convert a table from one storage engine to another, use an ALTER TABLE statement that indicates
the new engine:
• INSERT INTO vehicles VALUES (111, 2000, 'Honda', 'A1', 'silver', ' Honda was the
first Japanese automobile manufacturer to release a dedicated luxury brand, Acura,
in 1986.');
• INSERT INTO vehicles VALUES (112, 2002, 'Hyundai', 'AC1', 'white', ' Hyundai
operates the world's largest integrated automobile manufacturing facility in
Ulsan, South Korea which has an annual production capacity of 1.6 million
units.');
Change column
syntax
ALTER TABLE tbl_name [alter_specification [, alter_specification] ...]
alter_specification
• CHANGE [COLUMN] old_col_name new_col_name column_definition [ FIRST |
AFTER col_name ]
Change column
• CREATE TABLE vehicles ( • ALTER TABLE vehicles
vehicleID INT, CHANGE year model_year INT,
year SMALLINT, CHANGE color model_color
make VARCHAR(150), VARCHAR(20),
model VARCHAR(100), CHANGE note vehicleCondition
color VARCHAR(20), VARCHAR(150);
note VARCHAR(255)
);
Change column
• CREATE TABLE users ( • CREATE TABLE login (
ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userID INT,
password VARCHAR(25), loginDate DATE,
email VARCHAR(255) loginTime TIME,
) ; constraint fk_userID FOREIGN KEY(userID)
REFERENCES users(ID)
) ;
• INSERT INTO users VALUES (1, 'rajan', 'ranaj123', 'rajan447.gmail.com');
• INSERT INTO users VALUES (2, 'raj', 'raj', 'raj.gmail.com');
Note:
• All table data and the table definition are removed.
• DROP login;
• DROP TABLE users;
• DROP TABLE login, users;
TRUNCATE TABLE
Remember:
• DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
• DELETE operations can be rolled back, while DROP and TRUNCATE operations cannot be rolled back.
• The TRUNCATE TABLE statement removes all the data/rows of a table and resets the auto-increment value to
zero.
Truncate Table
Logically, TRUNCATE TABLE is similar to a DELETE statement that deletes all rows, or a sequence of DROP
TABLE and CREATE TABLE statements.
Remember:
• Truncate operations drop and re-create the table, which is much faster than deleting rows one by one.
• Truncate operations cause an implicit commit, and so cannot be rolled back.
• Truncate does not cause ON DELETE triggers to fire.
• Truncate cannot be performed for parent-child foreign key relationships.
• Truncate retain Identity and reset to the seed (start value) value.
• Cannot truncate a table referenced in a foreign key constraint.
DROP Vs TRUNCATE
DROP VS TRUNCATE
DROP TRUNCATE
The DROP command is used to remove table definition Whereas the TRUNCATE command is used to delete all
and its contents. the rows from the table.
In the DROP command, VIEW of table does not exist. In the TRUNCATE command, VIEW of table exist.
In the DROP command, integrity constraints will be In the TRUNCATE command, integrity constraints will
removed. not be removed.
In the DROP command, INDEX associated to the table In the TRUNCATE command, INDEX associated to the
will be removed. table will not be removed.
In the DROP command, TRIGGER associated to the table In the TRUNCATE command, TRIGGER associated to the
will execute. table will not execute.
In the DROP command, TRIGGER associated to the table In the TRUNCATE command, TRIGGER associated to the
will be removed. table will be not removed.
RENAME Table
Change the table name.
Views
Remember:
View
• it can be described as virtual table which derived its data from one or more than one table.
• it is stored in the database.
• it can be created using tables of same database or different database.
• it is used to implement the security mechanism in the SQL.
Rules:
• If a VIEW is defined as SELECT * on a table, new columns added to the table later do not become part of the
VIEW, and columns dropped from the table will result in an error when selecting from the VIEW.
• A VIEW must have unique column names with no duplicates, just like a base table. By default, the names of
the columns retrieved by the SELECT statement are used for the VIEW column names.
• The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY VIEW.
• You cannot associate a TRIGGER with a VIEW.
Note:
• If we drop the BASE TABLE, the VIEW will not be dropped.
View
Views are not updatable in the following cases:
UPDATE AND DELETE on VIEW (with check option given on view) will work only when the DATA MATCHES
IN WHERE CLAUSE.
desc INFORMATION_SCHEMA.VIEWS;
licence table Create View
// We may get Error: Can not insert into join view 'db5.v2' without fields list.
• INSERT INTO v2(cID, name, description) VALUES(5, 'neel', 'description Text 5');
e.g.
• DROP VIEW studentview;
• DROP VIEW studentid10view, studentviewwithcheck;
• DROP VIEW studentTotalMarksView, studentAddressView;
MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are stored in B-trees.
FULLTEXT indexes are created on text-based columns (CHAR, VARCHAR, or TEXT columns)
to help speed up queries and DML operations on data contained within those columns, omitting
any words that are defined as stopwords.
Index
• it is a schema object.
• it is used by the server to speed up the retrieval of rows.
• it reduces disk I/O(input/output) process.
• it helps to speed up select queries where clauses, but it slows down data input, with the update and the
insert statements.
• it can be created or dropped with no effect on the data.
Index
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the
first row and then read through the entire table to find the relevant rows. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look
at all the data. This is much faster than reading every row sequentially.
e.g.
e.g.
DROP INDEX drops the index named index_name from the table tbl_name.
.g.
DROP INDEX indexOnName ON emp;
DROP INDEX indexOnUniversity ON student_qualifications;
DROP INDEX uniqueIndexOnName ON emp;
Lock / unlock table
lock / unlock
MySQL enables client sessions to acquire table locks to prevent from modifying tables
Sessions holding a READ lock, DROP TABLE and TRUNCATE TABLE operations are
not permitted.
lock_type:
READ |WRITE
UNLOCK TABLES
UNLOCK TABLE
• mysqldump -uroot -p db1 >> d:\bk.sql
• mysqldump -u[username] -p[password] --all-databases > d:\db_backup.sql
• mysqldump -P 3306 -h 192.168.100.26 -usaleel -psaleel db_name >
db_backup.sql
• mysqldump --column-statistics=0 -P 3306 -h 192.168.100.26 -usaleel -
psaleel db_name > db_backup.sql
• mysql -P 3306 –h192.168.100.74 -uroot -proot db2 < d:\
backup_fileName.sql
• mysql -P 3306 –h192.168.100.74
db2 snapshots
-uroot -proot < d:\ backup_fileName.sql
To create a raw data snapshot of MyISAM tables, you can use standard copy tools such as cp or
copy, a remote copy tool such as scp or rsync, an archiving tool such as zip or tar, or a file system
snapshot tool such as dump, providing that your MySQL data files exist on a single file system. If
you are replicating only certain databases, copy only those files that relate to those tables.
CountryName,CapitalName,CapitalLatitude,CapitalLongitude,CountryCode,ContinentName,re
mark
Somaliland,Hargeisa,9.55,44.05,NULL,Africa,
South Georgia and South Sandwich Islands,King Edward Point,-54.283333,-
36.5,GS,Antarctica,
French Southern and Antarctic Lands,Port-aux-Français,-49.35,70.216667,TF,Antarctica,
Palestine,Jerusalem,31.76666667,35.233333,PS,Asia,
Aland Islands,Mariehamn,60.116667,19.9,AX,Europe,
Nauru,Yaren,-0.5477,166.920867,NR,Australia,
Saint Martin,Marigot,18.0731,-63.0822,MF,North America,
Tokelau,Atafu,-9.166667,-171.833333,TK,Australia,
• INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about
all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains
several read-only tables, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE
operations on them, and you cannot set triggers on them.
DATA DICTIONARY - INFORMATION_SCHEMA
Data Dictionary
INFORMATION_SCHEMA.COLUMNS
INFORMATION_SCHEMA.TABLES
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
INFORMATION_SCHEMA.STATISTICS
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
INFORMATION_SCHEMA.ROUTINES
INFORMATION_SCHEMA.PARAMETERS
INFORMATION_SCHEMA.TRIGGERS
Class Room
Session 1
PL/SQL
PL/SQL is a procedural language extension to Structured Query Language (SQL). The purpose of
PL/SQL is to combine database language and procedural programming language.
Note:
• Statements that return a result set can be used within a Stored Procedure but not within a Stored Function.
This prohibition includes SELECT statements that do not have an INTO var_list clause.
desc mysql.proc
CREATE FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
Parameter List
Argument List
Difference between Stored
Procedure and Function?
Stored Procedure and Function
• A FUNCTION always returns a value using the return statement. PROCEDURE may return one or more
values through OUT parameter(s) or may not return any at all.
• Functions are normally used for computations where as procedures are normally used for executing
business logic.
• A Function returns 1 value only. Procedure can return multiple values (max 1024).
• A function can be called directly by SQL statement like select func_name from dual while procedures
cannot.
The major difference is that UDFs can be used like any other expression within SQL
statements, whereas stored procedures must be invoked using the CALL statement.
Calling Procedure from Function and contrariwise
source file_name.sql
\. file_name.sql
The CALL statement invokes a stored procedure that was defined previously with CREATE PROCEDURE.
Stored procedures that take no arguments can be invoked without parentheses. That is, CALL sp_name and
CALL sp_name() are equivalent.
CALL sp_name([parameter[,...]])
CALL sp_name[()]
[begin_label:] BEGIN
• DROP PROCEDURE IF EXISTS procedurename;
[statement_list] delimiter $$
. . . . . CREATE PROCEDURE procedurename()
. . . . . begin
declare x BOOL default false;
. . . . .
begin
declare y BOOL default true;
END [end_label] SELECT x;
end ;
SELECT y;
end $$
delimiter ;
DECLARE variable_name datatype(size) [ DEFAULT de- Declaring variables
fault_value ];
1. declare x INT DEFAULT 0; DECLARE variable_name
SET x = 10; datatype(size)
Assigning variables
2. declare y INT;
SET y = 10; 1 DECLARE z INT;
2 SET z = 10;
Note:
DECLARE VARIABLES
• DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before
any other statements.
Remember:
• First, you specify the variable name after the DECLARE keyword. The variable name must follow the
naming rules of MySQL table column names.
• Second, you specify the data type of the variable and its size. A variable can have any MySQL data types
such as INT, VARCHAR , and DATETIME.
• Third, when you declare a variable, its initial value is NULL. You can assign the variable a default value
using the DEFAULT keyword.
Local Variable DECLARE and User-Defined Variables
Local variables are declared within stored procedures and are only valid within the BEGIN…END block
where they are declared. Local variables can have any SQL data type.
User variables in MySQL stored procedures, user variables are referenced with an ampersand (@) prefixed
to the user variable name.
Stored Procedure
A procedure is a group of PL/SQL statements that you can call by name.
Remember:
• It is not permitted to assign the value DEFAULT to stored procedure or function parameters
e.g.
PROCEDURE procedurename(in p_ID INT DEFAULT 10)
• Or stored program local variables
e.g.
SET var_name = DEFAULT some_value.
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
SELECT * FROM emp;
end $$
delimiter ;
mysql> SET @x = 10
mysql> CALL procudeureName(@x);
mysql> SELECT @x
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
CREATE TABLE temp (IN col1 INT);
end $$
delimiter ;
e.g.
DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(v_value INT)
begin
if v_value = 0 then
SELECT 'The enter value is 0' as "Message Box";
elseif v_value = 1 THEN
SELECT 'The enter value is 1' as "Message Box";
else
SELECT 'The enter value is neither 0 or 1' as "Message Box";
end if;
end $$
delimiter ;
LOOP
[begin_label:] LOOP ITERATE means "start the loop again."
LEAVE statement is used to exit the flow control construct that has the given label.
statement_list
END LOOP
[end_label]
• ITERATE label
e.g.
• LEAVE label
DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(v_value INT)
begin
declare x INT default 0;
lbl:loop
set x = x + 1;
SELECT x;
if x = v_value then
leave lbl;
end if;
end loop lbl;
end $$
delimiter ;
Cursor
Steps:
• This statement declares a cursor and associates it with a SELECT statement that retrieves the rows to be
traversed by the cursor.
DECLARE cursor_name CURSOR FOR select_statement
• This statement fetches the next row for the SELECT statement associated with the specified cursor (which
must be open), and advances the cursor pointer. If a row exists, the fetched columns are stored in the named
variables. The number of columns retrieved by the SELECT statement must match the number of output
variables specified in the FETCH statement.
FETCH [[NEXT] FROM] cursor_name INTO var_name [, var_name] ...
If no more rows are available, a No Data condition.
declare EXIT HANDLER FOR NOT FOUND SELECT "No more student found";
OPEN cur1;
loopLabel: LOOP
FETCH cur1 INTO v_ID, v_namefirst, v_namelast, v_dob, v_emailID;
SELECT v_ID, v_namefirst, v_namelast, v_dob, v_emailID;
END LOOP loopLabel;
CLOSE cur1;
end $$
delimiter ;
Cursor
Q2 Write a program to enter studentID and using cursor get his student qualification details.
DROP PROCEDURE if EXISTS getStudentQualification;
CREATE PROCEDURE getStudentQualification(v_ID INT)
b1:begin
declare x INT;
SELECT ID into x FROM student WHERE ID = v_ID;
if x is null then
SELECT "Student not found....";
else
b2: begin
declare v_name, v_college, v_university VARCHAR(128);
declare v_marks VARCHAR(45);
declare v_year INT;
declare cur1 cursor for SELECT name, college, university, marks, year FROM student_qualifications where studentID = x;
declare exit handler for NOT FOUND SELECT "Done";
OPEN cur1;
lbl:loop
FETCH cur1 INTO v_name, v_college, v_university, v_marks, v_year;
SELECT v_name, v_college, v_university, v_marks, v_year;
end loop lbl;
CLOSE cur1;
end b2;
end if
end b1 $$
delimiter ;
Note:
• By default, all parameters are IN parameters.
• You cannot specify IN , OUT or INOUT modifiers to the parameters.
FUNCTIONS
The RETURNS clause may be specified only for a FUNCTION, for which it is mandatory. It indicates the
return type of the function, and the function body must contain a RETURN value statement.
Remember:
ERROR 1415 (0A000): Not allowed to return a result set from a function
DESC INFORMATION_SCHEMA.TRIGGERS
TRIGGER
You put the trigger name after the CREATE TRIGGER statement. The trigger name should follow the naming
convention [trigger time]_[table name]_[trigger event], for example before_employees_update.
Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a
trigger. You use the BEFORE keyword if you want to process action prior to the change is made on the table
and AFTER if you need to process action after the change is made.
The trigger event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked. A trigger
only can be invoked by one event. To define a trigger that is invoked by multiple events, you have to define
multiple triggers, one for each event.
A trigger must be associated with a specific table. Without a table trigger would not exist therefore you have
to specify the table name after the ON keyword.
You place the SQL statements between BEGIN and END block. This is where you define the logic for the
trigger.
What is trigger_time and trigger_event ?
trigger_time : trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger
activates before or after each row to be modified.
trigger_event : trigger_event indicates the kind of operation that activates the trigger.
INSERT: The trigger activates whenever a new row is inserted into the table; for example, through
INSERT statements.
UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.
DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE
and REPLACE statements.
Remember:
• DROP TABLE and TRUNCATE TABLE statements on the table do not activate this trigger, because they
do not use DELETE.
• Dropping a partition does not activate DELETE triggers, either.
BEFORE and AFTER
• If a BEFORE trigger fails, the operation on the corresponding row is not performed.
• A BEFORE trigger is activated by the attempt to insert or modify the row or delete the row, regardless of
whether the attempt subsequently succeeds.
• An AFTER trigger is executed only if any BEFORE triggers and the row operation execute successfully.
• An error during either a BEFORE or AFTER trigger results in failure of the entire statement that caused
trigger invocation.
NEW and OLD
The OLD and NEW keywords enable you to access columns in the rows affected by a trigger. OLD and NEW
are MySQL extensions to triggers; they are not case sensitive.
A column named with OLD is read only. In a BEFORE trigger, you can also change its value with
SET NEW.col_name = value.
The trigger occurs. This can either be BEFORE or AFTER an INSERT, UPDATE or DELETE. A
BEFORE trigger must be used if you need to modify incoming data. An AFTER trigger must be
used if you want to reference the new/changed record as a foreign key for a record in another
table.
If you drop a table, any triggers for the table are also dropped.
As of MySQL 5.7.2, it is possible to define multiple triggers for a given table that have the same trigger event and
action time. For example, you can have two BEFORE UPDATE triggers for a table. By default, triggers that have the
same trigger event and action time activate in the order they were created.
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
SELECT 'Hello World'; #error
end $$
delimiter ;
ERROR 1415 (0A000): Not allowed to return a result set from a trigger
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername AFTER INSERT ON dept FOR EACH ROW
begin
INSERT INTO d1 VALUES (NEW.deptno, NEW.dname, NEW.loc, NEW.pwd);
end $$
delimiter ;
SQL Injection
TODO
Injection in Insert/Update
TODO
Load- XML
XML file
XML File
<?xml version="1.0" encoding="utf-16"?>
<employees>
<employee>
<id> be129 </id>
<firstname> Jane </firstname>
<lastname> Doe </lastname>
<title> Engineer </title>
</employee>
<employee>
<id> be130 </id>
<firstname> William </firstname>
<lastname> Defoe </lastname>
<title> Accountant </title>
</employee>
</employees>
Table structure for XML file and load XML file.
Example:
<employee>
<id> be130 </id>
<firstname> William </firstname>
<lastname> Defoe </lastname>
<title> Accountant </title>
</employee>
</employees>
Load and select data from external XML file
Example:
7. TODO
8. TODO
9. TODO
10. TODO
Interview questions
• What is the difference between CHAR and VARCHAR?
• What is the difference between DELETE TABLE and TRUNCATE TABLE commands in MySQL?
• What do you mean my Joins and explain different types of MySQL Joins?
select count(*), e.* from e group by empno, ename, job, mgr, hiredate, sal, comm, deptno, bonusid, `user name`, pwd;
IMP SQL statements
TABLET Id Name Ingredient Unit
Table 1 CROCIN PARACETAMOL 100mg
2 COMBIFLAM PARACETAMOL, IBUPROFEN 25mg
3 DIVON PLUS PARACETAMOL, DICLOFENAC 30mg
2. Square
"Live as if you were to die tomorrow.
Learn as if you were to live forever"
Input a = 10, find ascii of a variable and store in 65 array
65 a 10
<student2>
<RollNumber> 2 </RollNumber>
<Name> Vrushali </Name>
</student2>
<student3>
<RollNumber> 3 </RollNumber>
<Name> Sharmin </Name>
</student3>
<student4>
<RollNumber> 4 </RollNumber>
<Name> Ruhan </Name>
</student4>
</Students>");
• Display how many employees are working from every department?
• Display the department name where less the 3 employees are working?
data dictionary
information_schema.table_constraints;
information_schema.key_column_usage;
information_schema.referential_constraints
select north, south, east, west, case field('y’, north, south, east, west) when 1 then 'North' when 2 then 'South' when 3 then
'East' else 'West' end R1 from coalesce;