mysql-rdbms-210325213847
mysql-rdbms-210325213847
▪ The most popular open source SQL database management system, is developed, distributed, and supported by
Oracle Corporation.
▪ It is written in C and C++.
▪ It is named after co-founder Monty Widenius’s daughter, My.
▪ The name of the MySQL Dolphin is Sakila.
Comments
Data Types
Type Details
BIT[(M)] ▪ The default is 1 if M is omitted.
- BIT, BIT(30) ▪ M indicates the number of bits per value, from 1 to 64.
BOOL ▪ Zero is considered false and nonzero values are considered true.
BOOLEAN
TINYINT[(M)] [UNSIGNED] ▪ 1 byte
Constraints
Constraints Description
NOT NULL ▪ In MySQL, NOT NULL constraint allows to specify that a column can not contain any NULL
value.
DEFAULT def_value ▪ Sets a default value for a column when no value is specified.
Ex:
• DEFAULT 0
• DEFAULT (RAND() * RAND())
• DEFAULT (CURRENT_TIMESTAMP)
• DEFAULT (CURRENT_TIMESTAMP) ON UPDATE CURRENT_TIMESTAMP
UNIQUE ▪ The UNIQUE index constraint in MySQL does not allow to insert a duplicate value in a
column.
CHECK (expr) ▪ The CHECK clause enables the creation of constraints to be checked for data values in table
rows.
▪ CHECK constraints are prohibited on columns used in foreign key referential actions.
▪ CHECK constraints are evaluated for INSERT, UPDATE, REPLACE, LOAD DATA statements and
an error (warning) occurs if a constraint evaluates to FALSE.
PRIMARY KEY ▪ A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table.
FOREIGN KEY ▪ A FOREIGN KEY in MySQL creates a link between two tables by one(or more) specific
column of both tables.
▪ The specified column in one table must be a PRIMARY KEY and referred by the column of
another table known as FOREIGN KEY.
SQL Statements
- Data Definition Statements (DDL)
- CREATE, ALTER, DROP statements
col1 datatype [NOT NULL] [DEFAULT def_val] [UNIQUE] [AUTO_INCREMENT] [PRIMARY KEY] [CHECK(expr)],
col2 datatype [NOT NULL] [DEFAULT def_val] [UNIQUE] [AUTO_INCREMENT] [PRIMARY KEY] [CHECK(expr)],
.
.
.
coln datatype [NOT NULL] [DEFAULT def_val] [UNIQUE] [AUTO_INCREMENT] [PRIMARY KEY] [CHECK(expr)],
);
- By default, tables are created in the default database, using the InnoDB storage engine.
- IF NOT EXISTS prevents an error from occurring if the table exists.
- If the constraint names are not defined, then MySQL automatically generates a constraint name.
- CASCADE: delete/update the child table matching rows when delete/update the parent table rows.
- SET NULL: sets the foreign key column to NULL when delete/update the parent table row.
- RESTRICT: rejects the delete/update operation for the parent table.
Bitwise
SELECT *
FROM employees
&, ~, |, ^, <<, >> WHERE DEPARTMENT_ID IN(10, 50, 100)
Arithmetic AND FIRST_NAME LIKE "l%"
AND SALARY BETWEEN 2000 AND 15000
AND COMMISSION_PCT IS NOT NULL
DIV (integer div), / (floating point div) AND MANAGER_ID>0 IS TRUE
- (minus), - (negative sign) AND LAST_NAME LIKE "___%"
%, MOD (modulus)
+ (plus)
* (multiplication)
Logical
AND, &&
OR, ||
NOT, !
XOR
Assignment
>, >=, <, <=, !=, <> (not equal), = (equality check), <=>
BETWEEN … AND …
NOT BETWEEN … AND …
IN(val1, val2, …)
NOT IN(val1, val2, … )
LIKE pattern
NOT LIKE pattern
here, % = 0 to many chars and _ = exactly 1 char
IS boolean
IS NOT boolean
IS NULL
IS NOT NULL
COALESCE(val1, val2, … …)
SQL Statements
- Data Manipulation Statements (DML)
- INSERT, UPDATE, DELETE statements
1. INSERT INTO tablename[(col1, col2, col3, ... ...)] VALUES(val1, val2, val3, ... ...);
3. UPDATE tablename
SET col1=val1, col2=val2, ... ...
WHERE condition;
CEIL(x)
- returns the smallest integer value not less than x
ROUND(x) / ROUND(x,D) SELECT ROUND(1.34,1), ROUND(1.35,1),
TRUNCATE(1.34,1), TRUNCATE(1.35,1)
- returns the argument x rounded to D(default 0) -- Output: 1.3 1.4 1.3 1.3
decimal places
TRUNCATE(x,D)
- returns the number x, truncated to D decimal
places
Page | 6 Mohammad Imam Hossain, Email: [email protected]
Other functions
POW(x,y), EXP(x), LOG(B,x),
SQRT(x), RAND(), CONV(x, from_base, to_base)
Other functions
PI(), DEGREES(x), RADIANS(x),
SIN(x), COS(x), TAN(x), COT(x),
ASIN(x), ACOS(x), ATAN(x)
UPPER(str)
- returns the string str with all
characters changed to uppercase.
REVERSE(str)
- returns the string str with the order of
the characters reversed.
CONCAT(str1, str2, str3, … …) SELECT CONCAT('MySQL',' ','is',' ','fun')
-- Output: MySQL is fun
- returns the string that results from
concatenating the arguments.
SUBSTR(str, pos) SELECT SUBSTR('abcdef',3), SUBSTR('abcdef',-3)
-- Output: cdef def
- returns a substring from string str
-- string indexing starts with 1
starting at position pos
RIGHT(str, len)
- returns the rightmost len characters
from the string str
LPAD(str, len, padstr) SELECT LPAD('abcd', 8, 'xyz'), RPAD('abcd',6,'x')
- returns the string str, left-padded with -- Output: xyzxabcd abcdxx
STR_TO_DATE(string, format)
- string to date SELECT STR_TO_DATE('May 01, 2013','%M %d,%Y')
-- Output: 2013-05-01
format =
%Y – YYYY, %y – yy
%M – January, %b – Jan, %m – 01..12, %c – 1..12
%D – 0th, 1st ; %d – 00, %e – 0
Page | 8 Mohammad Imam Hossain, Email: [email protected]
%H – 00..23, %k – 0..23, %h – 01 .. 12, %l – 1..12
%i – 00..59,
%s – 00..59
%p – ‘AM’, ‘PM’, %a – ‘Sun’ , %W – ‘Sunday’
LAST_DAY(date) – returns the last date of that month SELECT LAST_DAY('2019-12-01')
-- output: 2019-12-31
SQL Statements
- Data Manipulation Statements (DML)
- Basic Search Operations (SELECT, WHERE, ORDER BY, LIMIT clauses)
1. To show the whole database table data (all columns, all rows)
SELECT *
FROM tablename;
SELECT *
FROM tablename
WHERE condition;
6. Column aliasing (can be used in GROUP BY, ORDER BY, HAVING clauses)
Aggregate/Group Functions
1. AVG([DISTINCT] expr)
- Returns the average value of expr for each group.
- The DISTINCT option can be used to return the average of the distinct values of expr.
- If there are no matching rows, AVG() returns NULL.
2. SUM([DISTINCT] expr)
- Returns the sum of expr for each group.
- If the return set has no rows, SUM() returns NULL.
- The DISTINCT keyword can be used to sum only the distinct values of expr.
3. COUNT(expr)
- Returns a count of the number of non-NULL values of expr within each group.
- The result is a BIGINT value.
- If there are no matching rows, COUNT() returns 0.
4. COUNT(*)
- It is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain
NULL values.
5. COUNT(DISTINCT expr)
- Returns a count of the number of rows with different non-NULL expr values.
6. MAX(expr)
- Returns the maximum value of expr.
- If there are no matching rows, MAX() returns NULL.
7. MIN(expr)
- Returns the minimum value of expr.
- If there are no matching rows, MIN() returns NULL.
Note: You can only show the columns stated in group by statement i.e. col1 and col2
directly. All the other columns must be within group functions.
Note: Having condition may involve only col1 or, col2 and any other conditions that
use aggregate functions.
SQL Statements
- Data Manipulation Statements (DML)
- Table Join Operations (JOIN, LEFT JOIN clauses)
Types of Join
Notes:
a) For code portability across databases, it is recommended that you use LEFT JOIN instead of RIGHT JOIN.
b) Natural JOIN/ Natural LEFT JOIN is semantically equivalent to an INNER JOIN or a LEFT JOIN with a USING clause
that names all columns that exist in both tables.
c) The search_condition used with ON is any conditional expression of the form that can be used in a WHERE
clause.
d) In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other).
e) INNER JOIN and COMMA(,) are semantically equivalent in the absence of a join condition.
f) STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table.
1. Table aliasing/renaming
JOIN
tablename2 AS t2
ON join_condition
[WHERE condition]
...
...
JOIN
tablename2 AS t2
ON join_condition
JOIN
tablename3 AS t3
ON join_condition
[WHERE condition]
...
...
LEFT JOIN
tablename2 AS t2
ON join_condition
[WHERE condition]
...
...
Example:
DELETE FROM t1
WHERE s11 > ANY
(SELECT COUNT(*)
FROM t2
WHERE NOT EXISTS
(SELECT *
FROM t3
WHERE ROW(5*t2.s1,77)=
(SELECT 50,11*s1
FROM t4
UNION
SELECT 50,77
FROM (
SELECT *
FROM t5
) AS t5
)
)
);
a) A subquery can return a scalar (a single value), a single row (multi-column), a single column (multi-row), or multi-row
multi-column (derived table).
b) A subquery can contain many of the keywords that an ordinary SELECT can contain:
DISTINCT, GROUP BY, ORDER BY, LIMIT, joins, UNION constructs, comments, functions, and so on.
c) A subquery's outer statement can be any one of: SELECT, INSERT, UPDATE, DELETE, SET, or DO.
d) A subquery must always appear within parentheses.
Reference:
▪ https://dev.mysql.com/doc/refman/8.0/en/subqueries.html
1. Scalar Subquery:
▪ A subquery is a scalar subquery that returns a single value.
▪ A scalar subquery is a simple operand, and you can use it almost anywhere a single column value or literal is
legal.
▪ If the subquery result is empty, the result is NULL.
Example 1: Show the employee id, salary for only those employees having greater salary than the employee id 150.
Also show the salary of employee id 150 with each employee record.
SELECT EMPLOYEE_ID,
SALARY,
( SELECT SALARY
FROM employees
WHERE EMPLOYEE_ID=150
) AS "150 id's salary"
FROM employees
WHERE SALARY > ( SELECT SALARY
FROM employees
WHERE EMPLOYEE_ID=150
)
References:
▪ https://dev.mysql.com/doc/refman/8.0/en/scalar-subqueries.html
▪ https://dev.mysql.com/doc/refman/8.0/en/comparisons-using-subqueries.html
Column Subquery: When the subquery returns a Single Column but multiple rows.
Use operators:
▪ ANY – return TRUE if the comparison is TRUE for ANY of the values in the column that the subquery returns.
▪ ALL – return TRUE if the comparison is TRUE for ALL of the values in the column that the subquery returns.
▪ IN – it is equivalent to ( = ANY ) operator.
▪ SOME – it is equivalent to ANY operator.
Example 4(ALL operator): Show those employee details for only those employees receiving salary higher than all other
employee salaries of department number 50. Also show the highest salary of department number 50 with each
employee record.
SELECT e1.*,
( SELECT MAX(e3.SALARY)
FROM employees AS e3
WHERE e3.DEPARTMENT_ID=50
) AS 'max sal of dept no 50'
FROM employees AS e1
WHERE e1.SALARY > ALL( SELECT e2.SALARY
FROM employees AS e2
WHERE e2.DEPARTMENT_ID=50
)
▪ https://dev.mysql.com/doc/refman/8.0/en/any-in-some-subqueries.html
▪ https://dev.mysql.com/doc/refman/8.0/en/all-subqueries.html
Practices:
1. Find out those employee’s last name and salary who is assigned to the same job type as employee id 141.
2. Find out the employee (last name and salary) who receives the highest salary.
3. Find out the manager details who handles minimum no of employees.
4. Find out those employees who don't work in 'IT_PROG' job type and also receive lower salary than any other
employees in 'IT_PROG' job type.
2. Row Subquery: A row subquery is a subquery variant that returns a single row and can thus return more than one
column value.
Example 1: Show those employees employee id, first name, job id, department id, job id of employee number 150,
department id of employee number 150 who works in the same department and same job type as employee having
employee number 150.
SELECT e1.EMPLOYEE_ID, e1.FIRST_NAME, e1.JOB_ID, e1.DEPARTMENT_ID,
( SELECT JOB_ID
FROM employees
WHERE EMPLOYEE_ID=150
) AS "150 id's job_id",
( SELECT DEPARTMENT_ID
FROM employees
WHERE EMPLOYEE_ID=150
) AS "150 id's department_id"
FROM employees AS e1
WHERE (JOB_ID, DEPARTMENT_ID) = ( SELECT JOB_ID, DEPARTMENT_ID
FROM employees AS e2
WHERE EMPLOYEE_ID=150
)
Practice:
1. Find out those employees whose is assigned to the same job type as employee id 144 and receives the same
salary as employee id 144.
▪ https://dev.mysql.com/doc/refman/8.0/en/row-subqueries.html
3. Derived Table: A derived table is an expression that generates a table within the scope of a query FROM clause. A
subquery in a SELECT statement FROM clause is a derived table.
▪ [AS] tablename clause is mandatory because every table in a FROM clause must have a name.
▪ A derived table cannot normally refer to (depend on) columns of preceding tables in the same FROM clause.
▪ A derived table may be defined as a lateral derived table to specify that such references are permitted.
Example 1: Show the maximum value of the department wise total salary.
SELECT MAX(dt1.c1) AS 'max total salary of a dept'
FROM (SELECT SUM(e2.SALARY) AS c1
FROM employees AS e2
GROUP BY e2.DEPARTMENT_ID
) AS dt1
Example 2: For each employee show his employee id, total no of employees hired after him and total no of employees
hired before him.
SELECT h_after.af_id, h_after.AFTER, h_before.BEFORE
FROM ( SELECT e1.employee_id AS af_id,
count(*) AS "AFTER"
FROM employees e1
JOIN employees e2
ON e1.HIRE_DATE < e2.HIRE_DATE
GROUP BY e1.EMPLOYEE_ID
) AS h_after
JOIN
ON h_after.af_id = h_before.bf_id
Reference:
▪ https://dev.mysql.com/doc/refman/8.0/en/derived-tables.html
4. Correlated Subquery: A correlated subquery is a subquery that contains a reference to a table that also appears in
the outer query.
Example 1:
SELECT *
FROM t1
WHERE column1 = ANY (SELECT column1
FROM t2
WHERE t2.column2 = t1.column2
);
Example 2: Show those employee details receiving highest salary in his job type.
SELECT e1.EMPLOYEE_ID, e1.JOB_ID, e1.SALARY
FROM employees AS e1
WHERE SALARY=( SELECT MAX(SALARY)
FROM employees AS e2
WHERE e2.JOB_ID=e1.JOB_ID
)
Reference:
▪ https://dev.mysql.com/doc/refman/8.0/en/correlated-subqueries.html
Reference: https://dev.mysql.com/doc/refman/8.0/en/