References

Database Management System

Nemi Chandra Rathore Department of Computer Science Central University of South Bihar, Gaya

April 5, 2020

Nemi Chandra Rathore MySQL: An Introduction 1/85 References Outline

History of Introduction to MySQL MySQL Architecture Installing and configuring MySQL References

Nemi Chandra Rathore MySQL: An Introduction 2/85 References History of Databases[5]

Based on Data Models history of databases development can be divided into three eras. 1 Navigational 2 Relational 3 Post-Relational Integrated data store (IDS), first general-purpose DBMS designed by Charles Bachman atGE. IDS was based on network model. Bachman received Turing Award in 1973 for his work in area.

Nemi Chandra Rathore MySQL: An Introduction 3/85 References History of Databases..

In 1966 IBM developed their own DBMS known as Information Management System(IMS)1 which was based on hierarchical model. American Airlines and IBM jointly developed SABRE (Semi-Automatic Business Research Environment) for making airline reservations. In 1970, Edgar Codd while working at IBM proposed a new model called Relational in his famous paper titled “A Relational Model of Data for Large Shared Data Banks".

1NASA’s Apollo space program. Nemi Chandra Rathore MySQL: An Introduction 4/85 References History of Databases..

In 1973 the System R project was started at IBM. The outcome of the project would later become the widely used Structured (SQL) database upon its release in 1981. Oracle (as “Relational , Inc.”) were first to commercialize the technology in 1979. Following Codd’s paper two people at University of California, Berkeley, Eugene Wong and Michael Stonebraker started a project known as INGRES in early 1970.

Nemi Chandra Rathore MySQL: An Introduction 5/85 References History of Databases..

RDBM Systems were an efficient way to store and process structured data. With time the processing speeds got faster, and “unstructured” data (art, photographs, music, etc.) became much more common place. NoSQL2 databases is essentially the rejection of the ‘relational structuring of data’ inherent to RDBMS[1]. The NoSQL model is non-relational and uses a “distributed” database system

2Not only SQL Nemi Chandra Rathore MySQL: An Introduction 6/85 References History of Databases..

It allows ad-hoc changes and dynamism demanded by a growing enterprise than the relational database does. Unstructured data is both non-relational and schema-less. Relational Database Management Systems simply were not designed to handle this kind of data.

Nemi Chandra Rathore MySQL: An Introduction 7/85 References MySQL Brief History

MySQL was created by a Swedish company, MySQL AB (now owned by since 2010), founded by David Axmark, Allan Larsson and Michael “Monty” Widenius in May-1995. MySQL (officially pronounced as “My-S-Q-L”, ) is an open-source relational database management system (RDBMS) written inC and C++. It is named after co-founder ’s daughter, ‘My’.

Nemi Chandra Rathore MySQL: An Introduction 8/85 References Features

MySQL is offered under two different editions: the open source MySQL Community Server and the proprietary Enterprise Server. Enterprise Server is differentiated by a series of proprietary extensions which install as server plugins. Major features as available in MySQL 5.6: 1 A broad subset of ANSI SQL 99, as well as extensions. 2 Cross-platform support. 3 Stored procedures,Triggers, Cursor, updatable views. 4 Online DDL when using the InnoDB Storage Engine 5 SSL Support 6 Query Caching 7 Unicode Support etc.

Nemi Chandra Rathore MySQL: An Introduction 9/85 References MySQL Architecture

MySQL architecture consists of 5 following components: 1 The Query Engine 2 The Storage Manager 3 The Buffer Manager 4 The Transaction Manager 5 The Recovery Manager In addition to these five primary sub-systems MySQL architecture contains following 2 support sub-systems: 1 Process Manager 2 Function Libraries

Nemi Chandra Rathore MySQL: An Introduction 10/85 References MySQL Architecture: The Query Engine

The Query Engine: This sub-system consists of following 3 interrelated components: 1 The Syntax Parser: It parses the SQL query and decomposes it in a form understandable by MySQL Engine. 2 The Query Optimizer: It generates an optimal execution plan for the query. 3 The Execution Component: It interprets the execution plan and makes request to other components to retrieve desired data.

Nemi Chandra Rathore MySQL: An Introduction 11/85 References MySQL Architecture: The Storage Manager

The Storage Manager: It interfaces with the Operating System to write data to the disk efficiently. With the help of Function Libraries it write the data in the tables, indexes, logs and internal system data. The Query : It caches the result of frequent queries and returns the resulted records if the same query is submitted again. It results in reduction in response time.

Nemi Chandra Rathore MySQL: An Introduction 12/85 References MySQL Architecture.....

The Buffer Manager: Handles all memory management issues regarding request for data between the Query Engine and the Storage Manager. The Transaction Manager: Facilitates concurrency in data access among transactions. Has a Lock Manager sub-component to avoid any concurrent access anomaly.

Nemi Chandra Rathore MySQL: An Introduction 13/85 References MySQL Architecture.....

The Recovery Manager: Creates logs and other related information to ensure recovery from any failure. So far only InnoDB andBDB table handlers provide recovery management. The MyISAM handler doesn’t provide transactional recovery. The Process Manager: Manages user connections . Provides synchronization among competing tasks and process via modules for multi-threading, thread locking and performing thread-safe operations.

Nemi Chandra Rathore MySQL: An Introduction 14/85 References MySQL Architecture.....

Function Libraries: This component contains general purpose routines used by other subsystems. Includes routine’s for string manipulation, sorting operations and operating system specific functions such as memory management and file I/O.

Nemi Chandra Rathore MySQL: An Introduction 15/85 References MySQL Architecture: Storage engines

Storage engines: Storage engines are MySQL components that handle the SQL operations for different table types InnoDB is the default and most general-purpose storage engine. To determine which storage engines your server supports, use the SHOW ENGINES statement.

Nemi Chandra Rathore MySQL: An Introduction 16/85 References MySQL Architecture: Storage engines

InnoDB (the default one): 1 InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data. 2 uses row-level locking 3 stores user data in clustered indexes to reduce I/O for common queries based on primary keys 4 To maintain data integrity, supports FOREIGN KEY referential-integrity constraints. MyISAM 1 Uses table-level locking that limits the performance in read/write workloads

Nemi Chandra Rathore MySQL: An Introduction 17/85 References MySQL Architecture: Storage engines

Memory 1 Stores all data in RAM, for fast access in environments that require quick look-ups of non-critical data. 2 Its use cases are decreasing; InnoDB with its buffer pool memory area provides a general-purpose and durable way to keep most or all data in memory, 3 NDBCLUSTER provides fast key-value lookups for huge distributed data sets. CSV 1 Its tables are really text files with comma-separated values, and are used to exchange data with scripts and applications. 2 use CSV tables during the import or export stage. Archive: These compact, unindexed tables are intended for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information.

Nemi Chandra Rathore MySQL: An Introduction 18/85 References MySQL Architecture: Storage engines

Archive 1 These compact, unindexed tables are intended for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information. Blackhole: 1 The Blackhole storage engine accepts but does not store data, similar to the Unix /dev/null device. Queries always return an empty set. 2 These tables can be used in replication configurations where DML statements are sent to slave servers, but the master server does not keep its own copy of the data.

Nemi Chandra Rathore MySQL: An Introduction 19/85 References MySQL Architecture: Storage engines

NDB 1 NDB (also known as NDBCLUSTER): This clustered is particularly suited for applications that require the highest possible degree of uptime and availability. Merge: 1 Enables a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as one object. 2 Good for VLDB (Very Large Database) environments such as data warehousing.

Nemi Chandra Rathore MySQL: An Introduction 20/85 References MySQL Architecture: Storage engines

Federated: 1 Offers the ability to link separate MySQL servers to create one logical database from many physical servers. 2 Very good for distributed or data mart environments. Example: 1 This engine serves as an example in the MySQL source code that illustrates how to begin writing new storage engines. 2 It is primarily of interest to developers. The storage engine is a “stub” that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them.

Nemi Chandra Rathore MySQL: An Introduction 21/85 References Installing MySQL on Ubuntu

First update your system using following commands in the given sequence: 1 sudo apt-get update 2 sudo apt-get upgrade Now Install MySQL as follows: 1 sudo apt-get install -server The standard tool for interacting with MySQL is the mysql client, which installs with the mysql-server package and can be accessed through a terminal.

Nemi Chandra Rathore MySQL: An Introduction 22/85 References Creating a user with administrative privileges

First login as root user: $mysql − u root − p; Create a user ’ravi’ identified by password of your choice.

mysql > create user ravi@localhost identified by 0abc12340;

Grant administrative privileges to the user ’ravi’:

mysql > grant all privileges on ∗ . ∗ to ravi with grant option;

Save the updates made to the privileges:

mysql > flush privileges;

Nemi Chandra Rathore MySQL: An Introduction 23/85 References Creating and using a database in MySQL

Getting existing databases: mysql > show databases;

Create your database as follows: mysql > create database dbname

To work with an existing database you need to select it using following command. mysql > use dbname;

You can see the list of all the tables in your database as follows: mysql > show tables;

Nemi Chandra Rathore MySQL: An Introduction 24/85 References Creating and using a database in MySQL

Getting list of existing MySQL users :

mysql > select ∗ from mysql.user;

The above query show all the columns of the table mysql.user. A more better way is as follows:

mysql > select host, user, authentications tring from mysql.user;

You can see the list of all the columns in the table mysql.user:

mysql > desc mysql.user;

Nemi Chandra Rathore MySQL: An Introduction 25/85 References MySQL Data Types

MySQL supports a number of SQL data types in several categories: Numeric types String (character and byte) types Date and Time types Spatial types JSON data type

Nemi Chandra Rathore MySQL: An Introduction 26/85 References MySQL Data Types: Numeric Types

MySQL Numeric Types are as follows: 1 BIT (m): A bit-field type. M indicates the number of bits per value, from1 to 64. The default is1. 2 TINYINT (M3): A very small integer. The signed range is -128 to 127. The unsigned range is0 to 255. 3 BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of0 is considered false. Nonzero values are considered true. 4 SMALLINT(M): A small integer. The signed range is -32768 to 32767. The unsigned range is0 to 65535.

3The M indicates the column display width, it doesn’t affect the range of the field. Nemi Chandra Rathore MySQL: An Introduction 27/85 References MySQL Data Types: Numeric Types

1 MEDIUMINT(M 4): A medium-sized integer. The signed range is -8388608 to 8388607. The unsigned range is0 to 16777215. 2 INT (M)/ INTEGER(M): A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned range is0 to 4294967295. 3 BIGINT(M): A large integer. The signed range is -9223372036854775808 to 9223372036854775807. The unsigned range is0 to 18446744073709551615.

4M, denotes the number of digits to be used, if number has less then M digits, zeros are added to the left Nemi Chandra Rathore MySQL: An Introduction 28/85 References MySQL Data Types: Numeric Types

Type Storage Minimum value Maximum Value (Bytes) (Signed/ Unsigned) (Signed/Unsigned) TINYINT 1 −128 (0) 127 (255) SMALLINT 2 -32768 (0) 32767 (65535) MEDIUMINT 3 -8388608 (0) 8388607 (16777215) INT 4 -2147483648 (0) 2147483647 (4294967295) BIGINT 8 −263 (0) 263 − 1 (264 − 1)

Table: MySQL Data types

Nemi Chandra Rathore MySQL: An Introduction 29/85 References MySQL Data Types: Numeric Types

1 DECIMAL[(M[,D])]: A packed “exact” fixed-point number. M is the total number of digits (the precision) and D is the number of digits after the decimal point (the scale). The maximum number of digits (M) for DECIMAL is 65. The maximum number of supported decimals (D) is 30. Default for D is 0 and M is 10. 2 The decimal point and (for negative numbers) the “ − ” sign are not counted in M. 3 FLOAT(M,D): A small (single-precision) floating-point number. Permissible values are -3.402823466E+38 to -1.175494351E-38,0, and 1.175494351E-38 to 3.402823466E+38. 4 A single-precision floating-point number is accurate to approximately 7 decimal places

Nemi Chandra Rathore MySQL: An Introduction 30/85 References MySQL Data Types: Numeric Types

DOUBLE[(M,D)]: A normal-size (double-precision) floating-point number. Permissible values are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0, and 2.2250738585072014E-308 to 1.7976931348623157E+308 FLOAT(p): A floating-point number. Here p represents the precision in bits MySQL uses p to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT with no M or D values. If p is from 25 to 53, the data type becomes DOUBLE with no M or D values.

Nemi Chandra Rathore MySQL: An Introduction 31/85 References MySQL Data Types: String Types

CHAR(M): A fixed-length string of character. VARCHAR(M): A variable-length string of length at most M. The range of M is 0 to 65, 535. MySQL stores VARCHAR values as a 1-byte5 or 2-byte6 length prefix plus data. The length prefix indicates the number of bytes in the value. MySQL uses utf8 as this predefined character set. TINYBLOB/TINYTEXT: A BLOB column with a maximum length of 255 bytes. Each value is stored using a 1-byte length prefix that indicates the number of bytes in the value.

5if length is less than 256 6if lenght is greater than 255 Nemi Chandra Rathore MySQL: An Introduction 32/85 References MySQL Data Types: String Types

BLOB/TEXT: A field with a maximum length of 65535 characters.(216 − 1) Bytes. MEDIUMBLOB/MEDIUMTEXT- A BLOB or TEXT column with a maximum length of 16777215 characters (224 − 1) Bytes. LONGBLOB/LONGTEXT- A BLOB or TEXT column with a maximum length of 4294967295 characters (232 − 1) Bytes. ENUM: ENUM, is used to create a list of items from which the value must be selected. Ex. ENUM (’A’, ’B’, ’C’). Note: The difference between BLOB & TEXT is that sorts and comparisons on stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields.

Nemi Chandra Rathore MySQL: An Introduction 33/85 References MySQL Data Types: String Types

1 SET: A set. A string object that can have zero or more values, each of which must be chosen from the list of values ’. 2 SET values are represented internally as integers. 3 A SET column can have a maximum of 64 distinct members. 4 A table can have no more than 255 unique element list definitions among its ENUM and SET columns considered as a group.

Nemi Chandra Rathore MySQL: An Introduction 34/85 References MySQL Data Types: Date & Time

DATE: A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. DATETIME: A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers. (YYYYMMDDHHMMSS). TIME - Stores the time in HH:MM:SS format. YEAR(M) - Stores a year in 2-digit or 4-digit format.

Nemi Chandra Rathore MySQL: An Introduction 35/85 References SQL

SQL is a Standard Query Language for any RDBMS.

Nemi Chandra Rathore MySQL: An Introduction 36/85 References DDL: Creating tables and populating them. [3]

You can use a script that contains DDL commands to create a set of tables into the database using any one of the following command:(Assume file is in current directory:) mysql>source filename; or use mysql> \. filename; You can also use a sql script containing set of insert commands to insert records into tables. You can make a copy of the existing tables using any of the following queries: Following query copies the data and the structure, but not the indexes: create table {new_table} select * from {old_table}; And following query copies the structure and indexes, but not the data: create table {new_table} like {old_table};

Nemi Chandra Rathore MySQL: An Introduction 37/85 References DDL: Creating tables and populating them. [3]

You can also use a text file containing the records to load records in a table using load command. Example: mysql>Load Data Local Infile filepath Into Table tablename Line Terminated By (line termiation chars); Note: Use for NULL value in table in text file and YYYY-MM-DD as the date format.

Nemi Chandra Rathore MySQL: An Introduction 38/85 References DDL: Creating tables and populating them. [3]

To copy a table with indexes and triggers do these 2 queries: Create table newtable like oldtable; Insert into newtable select * from oldtable; To copy just structure and data use this one: Create table newtable as select * from oldtable;

Nemi Chandra Rathore MySQL: An Introduction 39/85 References Integrity Constraints

Integrity Constraints are the rules imposed over a to avoid accidental changes that may lead to the database in an inconsistent state. You might require to insure minimum balance of 1000 rs in an account in a bank database. Salary of an employee can not be null. Marks of a student can not be negative. Grade obtained by a student should belong to a set of possible grade values. For example from set {F , C, B, B+, A, A+}

Nemi Chandra Rathore MySQL: An Introduction 40/85 References Integrity Constraints

Unique Constraint: Defines candidate keys Primary Key Constraint: Defines Primary Key Foreign Key Constraint: Creates Set-subset dependency. Business Constraint/Check Constraint: Not Null constraint: Disallows insertion of null value in a specified column DEFAULT - Sets a default value for a column when no value is specified

Nemi Chandra Rathore MySQL: An Introduction 41/85 References Integrity Constraints: Classification

Integrity constraints can be classified into two classes on the basis of how they are specified at the time of creating a table: Column Constraints Not Null constraint Default Constraints Table and column Constraints Primary Key Constraint Unique Constraint Check Constraint Foreign Key constraint Single Relation and Two Relation Constraint: Foreign Key constraint is a Two Relation Constraint and the rest are Single Relation constraints.

Nemi Chandra Rathore MySQL: An Introduction 42/85 References Unique Constraint and Not Null Constraint

The Unique constraint ensures that all values of a set of column are different for every pair of rows in a table.

1 Create table Persons ( ID int Not Null, LastName varchar(255) Not Null, FirstName varchar(255), constraint UC_Person Unique (ID, LastName) ); 2 Create table Persons ( ID int Not Null, LastName varchar(255) Not Null, FirstName varchar(255), Age int, Unique (ID) ); 3 Create table Persons (ID int Not Null unique, LastName varchar(255) Not Null);

Nemi Chandra Rathore MySQL: An Introduction 43/85 References Primary keys Constraint

Primary keys must contain Unique values, and cannot contain Null values. A table can have only one primary key, which may consist of single or multiple fields.

1 Create table Persons ( ID int, LastName varchar(255) Not Null, FirstName varchar(255), [Constraint PK_Person] Primary key (ID) ); 2 Create table Persons ( ID int Primary Key, LastName varchar(255) Not Null, FirstName varchar(255));

Nemi Chandra Rathore MySQL: An Introduction 44/85 References Check Constraint

The Check constraint is used to impose certain organizational policies or business requirements.

1 Create table Persons ( ID int Not Null, LastName varchar(255) Not Null, FirstName varchar(255), Age int Check (Age>=18) ); 2 Create table Persons ( ID int Not Null, LastName varchar(255) Not Null, FirstName varchar(255), Age int, City varchar(255), Constraint CHK_Person Check (Age>=18 AND City!=’Gwalior’) );

Nemi Chandra Rathore MySQL: An Introduction 45/85 References Default Constraint

The Default constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified.

1 Create table Instructor ( ID int Primary Key, Name varchar(40), Dept_name varchar(50) default ’Comp. Sci.’, salary float(10,2) default 80000 );

Nemi Chandra Rathore MySQL: An Introduction 46/85 References Foreign Key Constraint

A Foreign Key is a field (or collection of fields) in one table that refers to the Primary key in another table. A Foreign Key is a key used to link two tables together. The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

1 Create Table Instructor ( ID int Primary Key, Name varchar(40), Dept_name varchar(50), salary float(10,2), [Constraint FK_Deptname] Foreign Key (Dept_name) References Department(dept_name) ); 2 Create Table Instructor ( ID int Primary Key, Name varchar(40), Dept_name varchar(50) references Department(dept_name), salary float(10,2),);7 7Foreign key as a column constraint Nemi Chandra Rathore MySQL: An Introduction 47/85 References Foreign Key Constraint

The column in parent table corresponding to the foreign key is refereed as Reference key. For example column dept_name in the table Department in the example in the previous slide is called the reference key. Every value in the foreign key should appear in the corresponding reference key. A record in the child table that contains a value in the foreign key that doesn’t appear in the reference key, is referred to as a dangling tuple. The presence of a dangling tuple in the child table indicates the presence of inconsistency in the database.

Nemi Chandra Rathore MySQL: An Introduction 48/85 References Foreign Key Constraint: Cascading Action

Due to dependency of records, a deletion in parent table may create a number of dangling tuples in the child table that also need to be deleted. This action may result in cascading delete/update operation in child table. For example if a department is deleted from the table Department then corresponding records in the instructor table need to be deleted to maintain database consistency. The cascading actions can be specified with in the table definition with the foreign key constraints.

Nemi Chandra Rathore MySQL: An Introduction 49/85 References Foreign Key Constraint: Cascading Action

Create Table Instructor ( ID int Primary Key, Name varchar(40), Dept_name varchar(50), salary float(10,2), Foreign Key (Dept_name) References Department(dept_name) on delete cascade on update cascade, ...... ); Alternate actions are On delete set null On delete set default

Nemi Chandra Rathore MySQL: An Introduction 50/85 References Integrity Constraint :: Assertion

The Check clause does not support complex predicate so SQL standard defines another kind of Integrity Constraint named as assertion. An assertion is a predicate expressing a condition that we wish the database always to satisfy. The syntax to define an assertion is as follows: create assertion < assertion − name > check < predicate >;

Nemi Chandra Rathore MySQL: An Introduction 51/85 References Integrity Constraint :: Assertion

For example one may wish to have that the value of the column total_credits should be equal to the total of all the credits that a student has earned. Create assertion credits_earned_constraint check (not exists (select ID from student where tot cred <> (select sum(credits) from takes natural join course where student.ID = takes.ID and grade is not null and grade <> ’F’ ) The high overhead of testing and maintaining assertions has led some system developers to omit support for general assertions.

Nemi Chandra Rathore MySQL: An Introduction 52/85 References Integrity Constraint :: Triggers

A trigger is a statement that the system executes automatically as a side effect of a modification to the database. A trigger has two elements: An event that causes the trigger to be textcolormagentachecked and a condition that must be satisfied for trigger execution to proceed. The actions to be taken when the trigger executes.

Nemi Chandra Rathore MySQL: An Introduction 53/85 References Integrity Constraint :: Triggers

The following trigger update the total credits earned by a students create trigger credits_earned after update of takes on (grade) referencing new row as nrow referencing old row as orow for each row when nrow.grade <> ’F’ and nrow.grade is not null and (orow.grade = ’F’ or orow.grade is null) begin atomic update student set tot_cred= tot_cred+(select credits from course where course.course_id= nrow.course_id) where student.id = nrow.id; end;

Nemi Chandra Rathore MySQL: An Introduction 54/85 References DDL: Modifying Schema

Alter Table command is used to modify schema of a table. You can use this command to 1 Add a new column using :: ADD < column_name > [FIRST|AFTER column_name ]; 2 Modify a column using :: Modify < column_name > [FIRST|AFTER column_name ]; 3 Drop a column using :: Drop Column < column_name >; 4 Rename a column using :: CHANGE [FIRST|AFTER ]; 5 Rename table using :: Alter Table < table_name > RENAME TO ; 6 You can also add/drop integrity constraint, index, column’s default value. 7 You can also change the Storage Engine of a column using this command.

Nemi Chandra Rathore MySQL: An Introduction 55/85 References DQL: Requesting data from database

SQL offers Select clause with some additional clauses to retrieve data from your database. General Syntax of SQL query is as follows: Select [all|distinct][5] [attributes list]/∗[6] From

[1] Where [2] Group by [3] Having [4] Order by [Asc|Desc][7];

Nemi Chandra Rathore MySQL: An Introduction 56/85 References SQL Operators : Arithmetic Operators

These operators allow you to do Arithmetic operation on numeric attributes listed in Select Clause.

Operator Description + Addition − Subtraction ∗ Multiplication / Division % Modulo

Table: Arithmetic Operators

Nemi Chandra Rathore MySQL: An Introduction 57/85 References SQL Operators: Comparison Operators

These operators compare one Column of a table against a value.

Operator Description < Less than <= Less than or equal to > Greater than >= Greater than = Equal to <> Not equal to

Table: Comparison Operators

Nemi Chandra Rathore MySQL: An Introduction 58/85 References DQL: SQL Operators: Logical operators

Logical operators allows you to combine one or more comparison expressions .

Operator Description AND TRUE if all the conditions separated by AND is TRUE OR TRUE if any of the conditions separated by OR is TRUE NOT Displays a record if the condition(s) is NOT TRUE Between TRUE if the operand is within the range of comparisons IN TRUE if the operand is equal to one of a list of expressions LIKE TRUE if the operand matches a pattern EXISTS TRUE if the subquery returns one or more records ANY TRUE if any of the subquery values meet the condition SOME TRUE if any of the subquery values meet the condition ALL TRUE if all of the subquery values meet the condition

Table: Logical Operators

Nemi Chandra Rathore MySQL: An Introduction 59/85 References SQL Operators : Bitwise Operators

There operators allows to operate on bits..

Operator Description & Bitwise AND | Bitwise OR ∼ Bitwise Not ∧ Bitwise XOR << Left shift >> Right shift BIT _COUNT () Return the number of bits that are set

Table: Arithmetic Operators

Nemi Chandra Rathore MySQL: An Introduction 60/85 References Join Operation

In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other). In standard SQL, they are not equivalent.

Figure: Join Operation in MySQl

Nemi Chandra Rathore MySQL: An Introduction 61/85 References University

Figure: A Sample University Database Schema

Nemi Chandra Rathore MySQL: An Introduction 62/85 References DQL: Requesting data from database

Every SQL query outputs a relation that can contain duplicate records. You can use distinct to remove duplicates. Example : Select distinct dept_name from instructor; To allow duplicate you can use all which is also the default. Example : Select all dept_name from instructor;

Nemi Chandra Rathore MySQL: An Introduction 63/85 References DQL: Requesting data from database in chunks[4]

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two nonnegative integer (constants) arguments (except when using prepared statements). The first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return8. SELECT ∗ FROM tbl LIMIT 5, 10; ( Retrieve total 10 rows, 6 to 15)

8The offset of the initial row is 0 (not 1) Nemi Chandra Rathore MySQL: An Introduction 64/85 References DQL: Requesting data from database in chunks

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter (retrieves all rows from the 96th row to the last):

SELECT ∗ FROM tbl LIMIT 95, 18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set ( Retrieve first 5 rows): SELECT ∗ FROM tbl LIMIT 5;

LIMIT row_count is equivalent to LIMIT 0, row_count.

Nemi Chandra Rathore MySQL: An Introduction 65/85 References DQL: Requesting data from database in chunks

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter (retrieves all rows from the 96th row to the last):

SELECT ∗ FROM tbl LIMIT 95, 18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set ( Retrieve first 5 rows): SELECT ∗ FROM tbl LIMIT 5;

LIMIT row_count is equivalent to LIMIT 0, row_count.

Nemi Chandra Rathore MySQL: An Introduction 66/85 Privileges Provided by MySQL are of following types: 1 Administrative privileges - These are global privileges. 2 Database privileges - can be granted for specific databases, or globally so that they apply to all databases. 3 Privileges for database objects such as tables, indexes, views, and stored routines.

References Access Control in MySQL

MySQL access control involves two stages when you run a client program that connects to the server: 1 Stage 1: The server accepts or rejects the connection based on your authentication result. 2 Stage 2: Assuming that you can connect, the server checks each statement you issue to determine whether you have sufficient privileges to perform it.

Nemi Chandra Rathore MySQL: An Introduction 67/85 References Access Control in MySQL

MySQL access control involves two stages when you run a client program that connects to the server: 1 Stage 1: The server accepts or rejects the connection based on your authentication result. 2 Stage 2: Assuming that you can connect, the server checks each statement you issue to determine whether you have sufficient privileges to perform it. Privileges Provided by MySQL are of following types: 1 Administrative privileges - These are global privileges. 2 Database privileges - can be granted for specific databases, or globally so that they apply to all databases. 3 Privileges for database objects such as tables, indexes, views, and stored routines.

Nemi Chandra Rathore MySQL: An Introduction 67/85 The MySQL server reads the contents of these tables into memory when it starts and reloads them when some changes happens with them. A user who creates a new relation is given all privileges on that relation automatically

References Access Control in MySQL....

Information about account privileges is stored in the user, db, tables_priv, columns_priv, and procs_priv tables in the mysql system database.

Nemi Chandra Rathore MySQL: An Introduction 68/85 References Access Control in MySQL....

Information about account privileges is stored in the user, db, tables_priv, columns_priv, and procs_priv tables in the mysql system database. The MySQL server reads the contents of these tables into memory when it starts and reloads them when some changes happens with them. A user who creates a new relation is given all privileges on that relation automatically

Nemi Chandra Rathore MySQL: An Introduction 68/85 References Access Control in MySQL....

1 Forms of authorization on parts of the database: Read - allows reading, but not modification of data. Insert - allows insertion of new data, but not modification of existing data. Update - allows modification, but not deletion of data. Delete - allows deletion of data. 2 Forms of authorization to modify the database schema: Index - allows creation and deletion of indices. Resources - allows creation of new relations. Alteration - allows addition or deletion of attributes in a relation. Drop - allows deletion of relations.

Nemi Chandra Rathore MySQL: An Introduction 69/85 References MySQL: Granting Authorization.

The grant statement is used to confer authorization grant on to < user list > is a list of user-ids. < privilege list > is a list of privileges or public, which allows all valid users the privilege granted. A role (will discuss this later) Example: GRANT ALL PRIVILEGES ON ∗ . ∗ TO ‘rakesh0@‘localhost0 WITH GRANT OPTION; Granting a privilege on a view does not imply granting any privileges on the underlying relations. The grantor of the privilege must already hold the privilege on the specified item (or be the ).

Nemi Chandra Rathore MySQL: An Introduction 70/85 may be all to revoke all privileges the revokee may hold.

References MySQL: Revoking Authorization.

The revoke statement is used to revoke authorization. revoke on from

Example: revoke select on branch from U1, U2, U3;

If includes public, all users lose the privilege except those granted it explicitly. If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation. All privileges that depend on the privilege being revoked are also revoked.

Nemi Chandra Rathore MySQL: An Introduction 71/85 References Access Control in MySQL: Some Common Permissible Privileges

Table: Permissible Privileges for GRANT and REVOKE

Privilege Column Context ALL [PRIVILEGES] Synonym for all privileges Server administration CREATE Create_priv Databases, tables, or indexes CREATE USER Create_user_priv Server administration CREATE VIEW Create_view_priv Views DROP Drop_priv Databases, tables, or views GRANT OPTION Grant_priv Databases, tables, or stored routines INDEX Index_priv Tables INSERT Insert_priv Tables or columns DELETE Delete_priv Tables UPDATE Update_priv Tables or columns

Nemi Chandra Rathore MySQL: An Introduction 72/85 References Access Control in MySQL: All Permissible Privileges

Table: Permissible Privileges for GRANT and REVOKE

Privilege Column Context ALL [PRIVILEGES] Synonym for all privileges Server administration CREATE ROUTINE Create_routine_priv Stored routines CREATE TABLESPACE Create_tablespace_priv Server administration CREATE TEMPORARY TABLES Create_tmp_table_priv Tables CREATE USER Create_user_priv Server administration CREATE VIEW Create_view_priv Views DELETE Delete_priv Tables DROP Drop_priv Databases, tables, or views EVENT Event_priv Databases EXECUTE Execute_priv Stored routines FILE File_priv File access on server host GRANT OPTION Grant_priv Databases, tables, or stored routines INDEX Index_priv Tables

Nemi Chandra Rathore MySQL: An Introduction 73/85 References Access Control in MySQL: Permissible Privileges...

Table: Permissible Privileges for GRANT and REVOKE...

Privilege Column Context LOCK TABLES Lock_tables_priv Databases PROCESS Process_priv Server administration PROXY See proxies_priv table Server administration REFERENCES References_priv Databases or tables RELOAD Reload_priv Server administration REPLICATION CLIENT Repl_client_priv Server administration REPLICATION SLAVE Repl_slave_priv Server administration SELECT Select_priv Tables or columns SHOW DATABASES Show_db_priv Server administration SHOW VIEW Show_view_priv Views SHUTDOWN Shutdown_priv Server administration SUPER Super_priv Server administration TRIGGER Trigger_priv Tables USAGE Synonym for “no privileges” Server administration

Nemi Chandra Rathore MySQL: An Introduction 74/85 References Access Control in MySQL: Roles

A MySQL role is a named collection of privileges. The following list summarizes role management capabilities provided by MySQL: CREATE ROLE and DROP ROLE enable roles to be created and removed. GRANT and REVOKE enable privilege assignment and revocation for user accounts and roles. SHOW GRANTS displays privilege and role assignments for user accounts and roles. SET DEFAULT ROLE specifies which account roles are active by default.

Nemi Chandra Rathore MySQL: An Introduction 75/85 References Access Control in MySQL: Roles

Creating Roles: CREATE ROLE ’app_developer’, ’app_designer’, ’app_tester’;

Granting privileges to roles: GRANT ALL ON app_db.* TO ’app_developer’; GRANT SELECT ON app_db.* TO ’app_designer’; GRANT INSERT, UPDATE, DELETE ON app_db.* TO ’app_tester’;

Nemi Chandra Rathore MySQL: An Introduction 76/85 References Access Control in MySQL: Roles

Granting Roles to users (suppose we have users with name Amit, Jay, and Ravi GRANT ’app_developer’ TO ’Amit’@’localhost’; GRANT ’app_desigher ’ TO ’Jay’@’localhost’ , ’Ravi’@’localhost’; GRANT ’app_designer’, ’app_tester’ TO ’Amit’@’localhost’;

Nemi Chandra Rathore MySQL: An Introduction 77/85 References Access Control in MySQL: Roles

Checking Role Privileges SHOW GRANTS FOR ’Amit’@’localhost’; It shows each granted role without “expanding” it to the privileges the role represents. To show role privileges as well, add a USING clause naming the granted roles for which to display privileges. SHOW GRANTS FOR ’Amit’@’localhost’ USING ’app_designer’;9

9Assuming Amit has role App Designer Nemi Chandra Rathore MySQL: An Introduction 78/85 References Access Control in MySQL: Roles

Activating Roles Roles granted to a user account can be active or inactive within account sessions. If a granted role is active within a session, its privileges apply; otherwise, they do not. To see the currently active rile use the following: SELECT CURRENT_ROLE();

Nemi Chandra Rathore MySQL: An Introduction 79/85 References Dates in MySQL

MySQL DATE is one of the five temporal data types used for managing date values[2]. MySQL uses yyyy-mm-dd format for storing a date value that is fixed and can’t be changed. However, you may follow the standard date format and use the DATE_FORMAT function to format the date the way you want. The DATE values range from 1000 − 01 − 01 to 9999 − 12 − 31

Nemi Chandra Rathore MySQL: An Introduction 80/85 References Back-up/Export database

To a given list of databases mysqldump − u [username] − p [password] − −databases[database_name] > [dump_file.sql] Note: Database list should be separated by spaces. To backup all databases mysqldump − u [username] − p [password] − −all − databases > [dump_file.sql]

Nemi Chandra Rathore MySQL: An Introduction 81/85 References Back-up/Export database

To backup database structure only mysqldump − u [username] − p [password] − −no − data [database_name] > [dump_file.sql] To backup data only mysqldump − u [username] − p [password] − −no − create − info [database_name] > [dump_file.sql] Export multiple tables of the database mysqldump − u [username] − p [password][database_name] table − 1 table − 2‘... table − n > [dump_file.sql]

Nemi Chandra Rathore MySQL: An Introduction 82/85 References MySQL: Limitations

Like other SQL databases, MySQL does not currently comply with the full SQL standard for some of the implemented functionality. Up until MySQL 5.7, triggers are limited to one per action / timing. 10 No triggers can be defined on views. MySQL database’s inbuilt functions like UNIX_TIMESTAMP() will return 0 after 03:14:07 UTC on 19 January 2038.

10meaning that at most one trigger can be defined to be executed after an INSERT operation, and one before INSERT on the same table. Nemi Chandra Rathore MySQL: An Introduction 83/85 References ReferencesI

Avant.org. 2018. URL: http://avant.org/project/history-of-databases/. http://www.mysqltutorial.org. 2019. URL: http://www.mysqltutorial.org/mysql-date/. MySQL Tutorial (Official). 2018. URL: https: //dev.mysql.com/doc/refman/5.7/en/tutorial.html. Stackoverflow.com. 2018. URL: https://stackoverflow.com/questions/tagged/mysql. Wikipedia. 2018. URL: https://en.wikipedia.org/wiki/Database.

Nemi Chandra Rathore MySQL: An Introduction 84/85 References

Thanks for Listening.

Nemi Chandra Rathore MySQL: An Introduction 85/85