Sie sind auf Seite 1von 88

MySQL & SQL - Introduction

Course: NoSQL

NoSQ: MySQL-Introduction 1
Session-2: Agenda
• Introduction to MySQL
– Features
• Installation of MySQL
• Introduction to SQL
– DDL
– DML
– DCL
• Basic SQL Commands
– CREATE TABLE
– INSERT
– UPDATE
– DELETE
– COMMIT
• Basic Queries

NoSQ: MySQL-Introduction 2
MySQL
• Highlights
– First Released in 1995
– The most popular open source
relational database in the world.
– Thousands of downloads a day
– Millions of active installations
– Provides the date store for many open
source stacks
– Available under the GPL license and a
commercial license
– Complementary products, such as
client administration tools and MySQL
Cluster

NoSQ: MySQL-Introduction 3
The Number One Open Source Database...

NoSQ: MySQL-Introduction 4
MySQL – High Level Block Diagram
• Written in C, C++ and ASM
– 80% in C
– Parse tree and optimizer in C++
– String functionality in ASM on some
platforms

NoSQ: MySQL-Introduction 5
…and How it Got That Way
• Free to download and use
• Extremely easy to setup, use and maintain
– Created the “personal” RDBMS trend that is now followed by the large
proprietary databases
• Open code base, API and documentation
– Easy for communities to develop language bindings, such as PHP and Java
• New thinking
– Fresh code base, written from scratch to fulfill a specific need
– Defined new parameters of what an RDBMS is, and should do
• Brought the RDBMS to the masses
– MySQL has been belittled as a “SQL enabled file system”
– That’s not necessarily always a bad thing

NoSQ: MySQL-Introduction 6
Languages, Hardware and Operating Systems
• Languages
– C API: libmysql (MySQL AB)
– PHP extensions and PDO (community)
– Connector/JDBC (MySQL AB)
– Connector/.NET (MySQL AB)
– Connector/ODBC (MySQL AB)
– Perl DBD::DBI (community)
• Operating Systems
– Red Hat, SuSE, your Linux here
– FreeBSD, OpenBSD, NetBSD
– Windows, Mac
NoSQ: MySQL-Introduction 7
Main Features of MySQL
• Cross-platform support
• Stored procedures
– using a procedural language that closely adheres to SQL/PSM[68]
• Triggers
• Cursors
• Updatable views
• Online DDL when using the InnoDB Storage Engine.
• Information schema
• Performance Schema
– that collects and aggregates statistics about server execution and query
performance for monitoring purposes.
NoSQ: MySQL-Introduction 8
Main Features of MySQL – Cont’d…
• A set of SQL Mode options
– to control runtime behavior, including a strict mode to better adhere to
SQL standards.
• X/Open XA distributed transaction processing (DTP) support
– two phase commit, using the default InnoDB storage engine
• Transactions
– with savepoints when using the default InnoDB Storage Engine.
– The NDB Cluster Storage Engine also supports transactions.
• ACID compliance
– when using InnoDB and NDB Cluster Storage Engines.
NoSQ: MySQL-Introduction 9
Main Features of MySQL – Cont’d…
• SSL support
• Query caching
• Sub-SELECTs (i.e. nested SELECTs)
• Built-in replication support
– (i.e., master-master replication and master-slave replication) with one
master per slave, many slaves per master.
– Multi-master replication is provided in MySQL Cluster
• Full-text indexing and searching
• Embedded database library
• Unicode support
NoSQ: MySQL-Introduction 10
Main Features of MySQL – Cont’d…
• Partitioned tables with pruning of partitions in optimizer
• Shared-nothing clustering through MySQL Cluster
• Multiple storage engines
– allowing one to choose the one that is most effective for each table in the
application.
– Native storage engines
• InnoDB, MyISAM, Merge, Memory (heap), Federated, Archive, CSV, Blackhole, NDB
Cluster.
• Commit grouping
– gathering multiple transactions from multiple connections together to
increase the number of commits per second.

NoSQ: MySQL-Introduction 11
Features from 30,000 Feet – Cont’d…
• Prepared statements, binary client/server protocol
– Text protocol prior to 4.1
• OpenGIS (Geographical data)
• Internationalization, UTF-8
– Character set and collation specified at column level
• MySQL connectors (ODBC, JDBC, .NET, etc)
• MySQL Workbench for visual modeling, SQL development and
administration
• Written in C, C++ and ASM
– 80% in C
NoSQ: MySQL-Introduction 12
Data Models

NoSQ: MySQL-Introduction 13
MySQL - Deployment
• MySQL operates as a client-server system over TCP/IP network
• The server runs on a machine with an IP address, on a chosen TCP
port number.
• The default TCP port number for MySQL is 3306.
• Users can access the server via a client program, connecting to the
server at the given IP address and TCP port number.
• Client program could be
– SQL Workbench
– Java or PHP or Python program

NoSQ: MySQL-Introduction 14
MySQL – Client/Server Architecture

NoSQ: MySQL-Introduction 15
Client-Server : Starting-Connecting

NoSQ: MySQL-Introduction 16
Structured Query Language (SQL)
• The set of statements with which all programs and users access
data in RDBMS.
• SQL is a data sublanguage
• Main purpose is to provide an interface to a relational database.
• all statements are instructions to the database
• lets us work with data at the logical level
• Features
– It processes sets of data as groups rather than as individual units.
– It provides automatic navigation to the data.
– It uses statements that are complex and powerful individually, and that
therefore stand alone.
– Flow-control statements are commonly known as "persistent stored
NoSQ: MySQL-Introduction 17
SQL Cont’d…
• SQL provides statements for a variety of tasks, including:
– Querying data
– Inserting, updating, and deleting rows in a table
– Creating, replacing, altering, and dropping objects
– Controlling access to the database and its objects
– Guaranteeing database consistency and integrity
• SQL unifies all of the preceding tasks in one consistent language
• All programs written in SQL are portable

NoSQ: MySQL-Introduction 18
SQL Communication & Commands…

NoSQ: MySQL-Introduction 19
DDL & DML
• DDL • DML
– Specification notation for defining • Language for accessing and
database scheme manipulating the data organized by
– DDL compiler generates a set of tables appropriate data model
in a data dictionary
– Data dictionary contains metadata
• Two classes of languages:
(data about data) – Procedural - user specifies what data is
required and how to get those data
– Data storage and definition language -
special type of DDL in which storage – Non-procedural -- user specifies what
and access methods used by the data is required without specifying
DBMS are specified how to get those data

NoSQ: MySQL-Introduction 20
MYSQL Statements
• Data Definition Statements
– CREATE, ALTER, DROP, TRUNCATE, RENAME, GRANT, REVOKE
• Data Manipulation Statements
– INSERT, DELETE, UPDATE, CALL, DO, SELECT, LOAD DATA FILE
• Transactional and Locking Statements
– COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO SAVEPOINT, LOCK
TABLES, UNLOCK TABLES, SET TRANSACTION, START TRANSACTION

NoSQ: MySQL-Introduction 21
MYSQL Statements
• Replication Statements
– PURGE BINARY LOGS
– RESET MASTER
– SET sql_log_bin
– CHANGE MASTER TO
– CHANGE REPLICATION FILTER
– MASTER_POS_WAIT()
– RESET SLAVE
– SET GLOBAL sql_slave_skip_counter
– START SLAVE
– STOP SLAVE
NoSQ: MySQL-Introduction 22
Sample Tables

NoSQ: MySQL-Introduction 23
MySQL Datatypes
• Numeric
– Supports all SQL standard numeric types including exact number data type and approximate numeric data
types including integer, fixed-point and floating point
• String
– a string can hold anything from plain text to binary data such as images or files.
– Strings can be compared and searched based on pattern matching
• Date
– for date and time as well as the combination of date and time
• Boolean
– Does not have the built-in BOOLEANor BOOL data type.
– To represent Boolean values, use the smallest integer type which is TINYINT(1). In other words, BOOLEAN
and BOOL are synonyms for TINYINT(1).
• Spatial
– data types that contain various kinds of geometrical and geographical values
• JSON
– allows to store and manage (automatic validation) JSON documents more efficiently.

NoSQ: MySQL-Introduction 24
MySQL Data types

NoSQ: MySQL-Introduction 25
MySQL Vs Oracle – Numeric Datatypes

NoSQ: MySQL-Introduction 26
MySQL vs Oracle – Date Datatypes

MySQL Size Oracle

DATE 3 Bytes DATE

DATETIME 8 Bytes DATE

TIMESTAMP 4 Bytes DATE

TIME 3 Bytes DATE

YEAR 1 Byte NUMBER

NoSQ: MySQL-Introduction 27
MySQL vs Oracle – String

NoSQ: MySQL-Introduction 28
Operators Name Description
BETWEEN ... AND ... Check whether a value is within a range of values
COALESCE() Return the first non-NULL argument
= Equal operator
<=> NULL-safe equal to operator
> Greater than operator
>= Greater than or equal operator
GREATEST() Return the largest argument
IN() Check whether a value is within a set of values
INTERVAL() Return the index of the argument that is less than the first argument
IS Test a value against a boolean
IS NOT Test a value against a boolean
IS NOT NULL NOT NULL value test
IS NULL NULL value test
ISNULL() Test whether the argument is NULL
LEAST() Return the smallest argument
< Less than operator
<= Less than or equal operator
LIKE Simple pattern matching
NOT BETWEEN ... AND Check whether a value is not within a range of values
...
!=, <> Not equal operator
NOT IN() Check whether a value is not within a set of values
NOT LIKE Negation of simple pattern matching
STRCMP() Compare two strings

NoSQ: MySQL-Introduction 29
Basic Queries using SELECT command

NoSQ: MySQL-Introduction 30
Basic Queries - Examples
• Display all the information of the EMP table
– SELECT * FROM emp;
• Display all the information of the DEPT table
– SELECT* FROM dept;
• List the employees who are working for the deptno 10 or 20
– SELECT * FROM emp WHERE deptno =10 or deptno=20;
• List the employees who are working as managers
– SELECT * FROM emp WHERE job =‘MANAGER’;
• List employee number, name, sal, designation and deptno of all clerks working
in department number 30
– SELECT empno, ename, job, sal, deptno FROM emp WHERE job=‘CLERK’ AND deptno =
30;
• Display monthly and annual salaries of all employees
– SELECT empno, ename, job, deptno, sal AS MONTHLY, sal *12 as ANNUAL FROM emp;
NoSQ: MySQL-Introduction 31
Sample Tables

NoSQ: MySQL-Introduction 32
Basic Queries – Examples – Cont’d…
• Display employees whose annual salary is more than 30000
– SELECT empno, ename, job, deptno, sal AS MONTHLY, sal *12 as ANNUAL FROM emp
WHERE sal*12 > 30000;
• Display all the information of the all employees not earning commission
– SELECT * FROM emp WHERE comm IS NULL;
• Display all employees not working for dept 30 in descending order of salaries
– SELECT* FROM where deptno <> 30 ORDER BY sal desc;
• List first five employees
– SELECT * FROM emp LIMIT 5;
• List the employees were hired on 17th November, 1981
– SELECT * FROM emp WHERE hitedate=‘1987-11-17’;
• Display all details of JONES
– SELECT * FROM emp WHERE ename=‘JONES’;

NoSQ: MySQL-Introduction 33
Basic Queries – Examples – Cont’d…
• Display employees earning in a range of 1500 and 3000
– SELECT * from emp WHERE sal between 1500 and 3000;
• Display employees working in either in dept 10 or 20, not working as managers
but earning a salary more than 2500 in ascending order of salaries
– sELECT * from emp WHERE deptno in (10,20) and job <> 'MANAGER' and sal >2000
ORDER BY sal;;
• Display all employees whose names start with J
– SELECT* FROM where ename like ‘J%’;
• Display all employees whose names ends with ER
– SELECT * FROM emp where ename like ‘%ER’;;
• List the employees were hired in 1981 descending order of hiredate
– SELECT * FROM emp WHERE hiredate LIKE '%1981%' order by hiredate;
• List the employees were hired in the month of December
– SELECT * FROM emp WHERE hiredate LIKE ‘%12%;
NoSQ: MySQL-Introduction 34
Queries – Exercises
1. List the Empno, Ename, Sal, Daily sal and Annual Salary of all
employees in the asc order of Annual Salary
2. List the employees in the asc order of Designations of those joined
after the second half of 1981.
3. List the employees who are joined in the year 81
4. List the employees Who Annual sal ranging from 22000 and
45000.
5. List the employees whose names having a character set ‘ll’
together
NoSQ: MySQL-Introduction 36
MySQL & SQL - Queries
Course: NoSQL

NoSQ: MySQL-Introduction 37
Agenda
• String Functions
• Date Functions
• Aggregate Functions
• Sub Queries
• Joins

NoSQ: MySQL-Introduction 38
String Functions
• CONCAT(str1,str2,...)
– Returns the string that results from concatenating the arguments
– SELECT CONCAT (“HELLO “, ENAME) FROM EMP;
• CONCAT_WS(separator,str1,str2,.)
– CONCAT_WS() stands for Concatenate With Separator and is a special form of
CONCAT().
– SELECT CONCAT_WS ('**',ENAME, EMPNO) FROM EMP
• INSERT(str,pos,len,newstr)
– Returns the string str, with the substring beginning at position pos and len
characters long replaced by the string newstr.
– SELECT ENAME, INSERT(ENAME,LENGTH(ENAME)+1,10,'HELLO') FROM EMP
• INSTR(str,substr)
– Returns the position of the first occurrence of substring substr in string str.
– SELECT ENAME, INSTR(ENAME, 'I') 'POSITION OF I' FROM EMP
NoSQ: MySQL-Introduction 39
String Functions
• LEFT(str,len)
– Returns the leftmost len characters from the string str, or NULL if any
argument is NULL.
• LENGTH(str)
– Returns the length of the string str, measured in bytes.
– SELECT LENGTH(ENAME) FROM EMP;
• LPAD(str,len,padstr)
– Returns the string str, left-padded with the string padstr to a length of len
characters.
– SELECT LPAD(ENAME, 10, ‘*’) FROM EMP;
• LTRIM(str)
NoSQ: MySQL-Introduction 40
Date Functions
• CURDATE()
– Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD
format, depending on whether the function is used in a string or numeric
context.
– CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE()
– SELECT CURDATE() ‘TODAY’, TIME() ‘TIME’
• NOW()
• SYSDATE()
• DAY(), DAYNAME(), DAYOFWEEK(), DAYOFMONTH(), DAYOFYEAR()
• MONTH(), MONTHNAME(), QUARTER()
• TIME()
• YEAR()
NoSQ: MySQL-Introduction 41
Date Functions
• ADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days)
– When invoked with the INTERVAL form of the second argument,
ADDDATE() is a synonym for DATE_ADD()
• SUBDATE(date,INTERVAL expr unit), SUBDATE(expr,days)
– When invoked with the INTERVAL form of the second argument,
SUBDATE() is a synonym for DATE_SUB().
• LASTDATE(date)
– Takes a date or datetime value and returns the corresponding value for the last day of
the month.
– Returns NULL if the argument is invalid.

NoSQ: MySQL-Introduction 42
Date Functions
• DATEDIFF(expr1,expr2)
– DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to
the other. expr1 and expr2 are date or date-and-time expressions
• STR_TO_DATE(‘string’, ‘format’)
– SELECT STR_TO_DATE('2010-01-01','%Y-%m-%d');
– %Y – 4 digit year
– %y – 2 digit year
– %m – month number
– %d – day of the week
• ADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days)
– When invoked with the INTERVAL form of the second argument, ADDDATE() is a
synonym for DATE_ADD()
• SUBDATE(date,INTERVAL expr unit), SUBDATE(expr,days)
NoSQ: MySQL-Introduction 43
Date Functions
• EXTRACT(unit FROM date)
– The EXTRACT() function uses the same kinds of unit specifiers as
DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than
performing date arithmetic

NoSQ: MySQL-Introduction 44
Demo Samples
• SELECT NOW() Today, ADDDATE(NOW(), INTERVAL 6 MONTH)
'AFTER 5 MONTHS', ADDDATE(NOW(), INTERVAL 6 QUARTER)
'AFTER 5 quarters', ADDDATE(NOW(), INTERVAL 6 YEAR) 'AFTER 5
years‘

NoSQ: MySQL-Introduction 45
Aggregate Functions
• group (aggregate) functions that operate on sets of values
• Commonly used functions
– AVG()
– COUNT()
• Returns a count of the number of rows returned
– COUNT(DISTINCT)
• Returns the count of a number of different values
– GROUP_CONCAT()
• Returns a concatenated string
– MAX()
• Returns the maximum value
– MIN()
NoSQ: MySQL-Introduction 46
Aggregate Functions – Demo Samples
• SELECT deptno, AVG(sal) FROM EMP GROUP BY deptno;
• SELECT deptno, MIN(sal) FROM EMP GROUP BY deptno;
• SELECT deptno, MAX(sal) FROM EMP GROUP BY deptno;
• SELECT deptno, SUM(sal) FROM EMP GROUP BY deptno;
• SELECT deptno, count(*) FROM EMP GROUP BY deptno;
• SELECT deptno, COUNT(EMPNO) FROM EMP GROUP BY deptno;
• SELECT deptno, job, count(*), MIN(SAL), max(sal) FROM EMP
GROUP BY deptno, job;

NoSQ: MySQL-Introduction 47
Aggregate Functions – Demo Samples-Cont’d
• SELECT deptno, job, COUNT(*), MIN(sal), MAX(sal) FROM emp
WHERE job <>’CLERK’ AND deptno=20 GROUP BY deptno, job;
• SELECT deptno, job, COUNT(*), MIN(sal), MAX(sal) FROM emp
WHERE job <>’CLERK’ AND deptno=20 GROUP BY deptno, job
HAVING COUNT(*) > 1;
• SELECT deptno, job, COUNT(*), MIN(sal), MAX(sal) FROM emp
WHERE job <>’CLERK’ AND deptno=20 GROUP BY deptno, job
HAVING COUNT(*) > 1 ORDER BY deptno DESC

NoSQ: MySQL-Introduction 48
Sub-Queries
• Nested Query or also called as runtime view.
• Can be nested to n’th level
• Can be used in clauses of SELECT statement
• A sub query may occur in -
– A SELECT clause
– A FROM clause
– A WHERE clause
• The subquery can be nested inside a SELECT,INSERT,UPDATE,or DELETE
statement or inside another subquery.
• A subquery is usually added within the WHERE cause of another SQL
SELECT statement.
• Can use the comparison operators, such as >, <, or =.
NoSQ: MySQL-Introduction 49
Types of Subqueries
• Scalar subqueries
– Return only one column and one row of data
• Single-row subqueries
– Return one or more columns in one of data
• Multiple-row subqueriers
– Return one or more columns in one or more rows of data
• Correlated subqueries
– Return nothing, but they effect a join between the outer DML statement
and correlated subquery.

NoSQ: MySQL-Introduction 50
Scalar subqueries

NoSQ: MySQL-Introduction 51
2

1
NoSQ: MySQL-Introduction 52
Subquery

1
NoSQ: MySQL-Introduction 53
Sample Tables

NoSQ: MySQL-Introduction 54
Exercises based on Emp, Dept & Salgrade Tables
• List the details of the employees whose Salaries more than the employee
BLAKE
– SELECT * FROM EMP WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME=‘BLAKE’);
• List the employees who are senior to King
– SELECT * FROM EMP WHERE HIREDATE < (SELECT HIREDATE FROM EMP WHERE
ENAME=‘KING’);
• List the employees whose Sal is same as FORD or SMITH in desc order of Sal
– SELECT * FROM EMP WHERE SAL IN (SELECT SAL FROM EMP WHERE ENAME=‘FORD’
OR ENAME=‘SMITH’)
• List the employees Whose Jobs are same as ALLEN or Sal is more than MILLER
– SELECT * FROM EMP WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME=‘MILLER’)
AND JOB = (SELECT JOB FROM EMP WHERE ENAME = ‘ALLEN’)
• Find the name and Job of the employees who earn Max salary and
Commission.
– SELECT * FROM EMP WHERE SAL = (SELECT MAX(SAL) FROM EMP) AND COMM IS NOT
NULL;
NoSQ: MySQL-Introduction 55
Exercises based on Emp, Dept & Salgrade Tables
• Find the highest paid employee of sales department.
– SELECT * FROM EMP WHERE SAL = (SELECT MAX(SAL) FROM EMP WHERE
DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME=‘SALES’))
• List the employees who are senior to most recently hired employee
working under king.
– SELECT * FROM EMP WHERE HIREDATE < (SELECT MAX(HIREDATE) FROM EMP
WHERE MGR = (SELECT EMPNO FROM EMP WHERE ENAME=‘KING’))
• Find the total annual sal to distribute job wise in the year 81.
– SELECT JOB, SUM(SAL*12) FROM EMP WHERE HIREDATE LIKE ‘1981%’ GROUP
BY JOB;
• List the highest paid emp working under king.
– SELECT *FROM EMPWHERE (DEPTNO , HIREDATE) IN (SELECT DEPTNO,
MAX(HIREDATE) FROM EMP WHERE (DEPTNO,MGR) = (SELECT DEPTNO,
EMPNO FROM EMP WHERE ENAME = 'KING'));
NoSQ: MySQL-Introduction 56
Exercises based on Emp, Dept & Salgrade Tables
• From the employees hired in 1981, display number of employees hired in each
job
– SELECT JOB, COUNT(*)FROM EMP WHERE HIREDATE LIKE '1981%'GROUP BY JOB;
• From the employees hired in 1981, list employees who are earning the highest
in each job
– SELECT ENAME, JOB, SAL FROM EMP WHERE HIREDATE LIKE '1981%' AND (JOB, SAL) IN
(SELECT JOB, MAX(SAL) FROM EMP WHERE HIREDATE LIKE '1981%‘ GROUP BY JOB)
• List the employees in dept 20 whose sal is > the average sal of dept 10
employees
– SELECT EMPNO, ENAME, SAL, JOB FROM EMP WHERE DEPTNO = 20 AND SAL > (SELECT
AVG(SAL) FROM EMP WHERE DEPT=10);
• List the details of most recently hired emp of dept 30.
– SELECT * FROM EMP WHERE DEPTNO=30 AND HIREDATE IN (SELECT MAX(HIREDATE)
FROM EMP WHERE DEPTNO = 30);

NoSQ: MySQL-Introduction 57
Exercises based on Emp, Dept & Salgrade Tables
• Display departments with more than 3 employees
– SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*) > 3;
• Display employee(s) earning highest commission
– SELECT * FROM EMP WHERE COMM = (SELECT MAX(COMM) FROM EMP);
• Display the details of most experienced employee(s)
– SELECT * FROM EMP WHERE HIREDATE = (SELECT MIN(HIREDATE) FROM EMP);
• Display the details of least experienced employee(s) NOT working as clerk.
– SELECT * FROM EMP WHERE JOB <> ‘CLERK’ AND HIREDATE = (SELECT MAX(HIREDATE)
FROM EMP);
• Find all the emps who earn the minimum Salary for each job wise in ascending
order.
– SELECT * FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMP GROUP BY JOB)
ORDER BY SAL ASC;
NoSQ: MySQL-Introduction 58
Exercises based on Emp, Dept & Salgrade Tables
• Display department names that are giving grade 1 salaries
– SELECT DEPTNO, DNAME FROM DEPT WHERE DEPTNO IN (SELECT DEPTNO
FROM EMP WHERE SAL BETWEEN (SELECT LOSAL FROM SALGRADE WHERE
GRADE=1) AND (SELECT HISAL FROM SALGRADE WHERE GRADE=1));
• Display employee(s) earning the highest grade 2 salary
– SELECT EMPNO, ENAME, SAL FROM EMP WHERE SAL = (SELECT MAX(SAL)
FROM EMP WHERE SAL BETWEEN (SELECT LOSAL FROM SALGRADE WHERE
GRADE=2) AND (SELECT HISAL FROM EMP WHERE GRADE=2)
• Display employee(s) earning the highest grade 1 salary and working in
DALLAS
– SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE DEPTNO = (SELECT
DEPTNO FROM DEPT WHERE LOC=‘DALLAS’) AND SAL = (SELECT MAX(SAL)
FROM EMP WHERE SAL BETWEEN (SELECT LOSAL FROM SALGRADE WHERE
GRADE=1) AND (SELECT HISAL FROM SALGRADE WHERE GRADE=1))
NoSQ: MySQL-Introduction 59
• List the managers who are senior to KING and who are junior to
SMITH
– SELECT * FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP WHERE
HIREDATE < (SELECT HIREDATE FROM EMP WHERE ENAME = 'KING' ) AND
HIREDATE > (SELECT HIREDATE FROM EMP WHERE ENAME = 'SMITH'))
AND MGR IS NOT NULL;
• List the managers who are not working under the president.
– SELECT * FROM EMP WHERE EMPNO IN(SELECT MGR FROM EMP) AND
MGR NOT IN (SELECT EMPNO FROM EMP WHERE JOB = 'PRESIDENT')

NoSQ: MySQL-Introduction 60
Co-related sub queries
• List the employees whose salary is same as any one of the following.
– SELECT * FROM EMP E SAL IN (SELECT SAL FROM EMP WHERE E.EMPNO <> EMPNO);
• List the employees who joined on the same day
– SELECT * FROM EMP E HIREDATE IN (SELECT HIREDATE FROM EMP WHERE E.EMPNO
<> EMPNO);
• List the details of department what have more than one employee hired on the
same date
– SELECT DEPTNO, DNAMEFROM DEPTWHERE DEPTNO IN (SELECT DEPTNO FROM EMP
GROUP BY DEPTNO, HIREDATE HAVING COUNT(*) >1);
• List the employees who earn a salary more than average salary of his/her
department
– SELECT EMPNO, ENAME, SAL, JOB, DEPTNO FROM EMP E WHERE SAL > ( SELECT
AVG(SAL) FROM EMP WHERE DEPTNO = E.DEPTNO);

NoSQ: MySQL-Introduction 61
• List the managers whose sal is more than his employes avg salary.
– SELECT * FROM EMP M WHERE M.EMPNO IN (SELECT MGR FROM EMP)
AND M.SAL > (SELECT AVG(E.SAL) FROM EMP E WHERE E.MGR =
M.EMPNO )

NoSQ: MySQL-Introduction 62
MySQL – JOINS

NoSQ: MySQL-Introduction 63
MySQL - JOINS
• JOIN
– enables retrieval of records from two (or more) logically related tables in a
single result set.
– It is used to retrieve data from multiple tables.
• JOIN clauses
– are used to return the rows of two or more queries using two or more tables
that shares a meaningful relationship based on a common set of values.
• Join key or common key
– usually the same column name and datatype that appear in both the
participating tables being joined. These columns, or possibly a single column
from each table.
– Mostly but not all of the time, the join key is the primary key of one table and a
foreign key in another table

NoSQ: MySQL-Introduction 64
Primarily types of MySQL JOINS

NoSQ: MySQL-Introduction 65
CROSS JOIN
• produces a result set which is the
number of rows in the first table
multiplied by the number of rows in
the second table.
• This kind of result set is called as
Cartesian Product.
• SELECT *
FROM table1
CROSS JOIN table2;

NoSQ: MySQL-Introduction 66
CROSS JOIN - EXAMPLE

SELECT FOODS.ITEM_NAME,FOODS.ITEM_UNIT,
COMPANY.COMPANY_NAME,COMPANY.COMPANY_CITY
FROM FOODS
CROSS JOIN COMPANY;

NoSQ: MySQL-Introduction 67
CROSS JOIN - EXAMPLE

NoSQ: MySQL-Introduction 68
Joins – INNER JOIN
• The MySQL INNER JOIN is used to
return all rows from multiple tables
where the join condition is satisfied.
• It is the most common type of join.
• SELECT <col (s) list> FROM <table-1>
INNER JOIN <table-2,…,table-n> ON
<join-condition>

NoSQ: MySQL-Introduction 69
Inner Join

NoSQ: MySQL-Introduction 70
NoSQ: MySQL-Introduction 71
• If we want all records for a doctor who are specialized in special1 and seat in his
chamber on Wednesday (WED) in his schedule time, the following SQL can be used-
• SELECT A.DOCID, A.DNAME, B.DESC,C.TDAY,C.SIT_TIM
FROM DOCTORS A
INNER JOIN SPECIALIZE B ON A.DOCID=B.DOCID
INNER JOIN TIMESCHEDULE C ON A.DOCID=C.DOCID
WHERE A.DOCID=1 AND C.TDAY='WED';

NoSQ: MySQL-Introduction 72
Step-1
• SELECT A.DOCID,A.DNAME,B.DESC
FROM DOCTORS A
INNER JOIN SPECIALIZE B
ON A.DOCID=B.DOCID;

NoSQ: MySQL-Introduction 73
Step-2
• SELECT A.DOCID, A.DNAME, B.DESC,
C.TDAY, C.SIT_TIME
FROM DOCTORS A
INNER JOIN SPECIALIZE B
ON A.DOCID=B.DOCID
INNER JOIN TIMESCHEDULE C
ON A.DOCID=C.DOCID;

NoSQ: MySQL-Introduction 74
Step-3
• SELECT A.DOCID, A.DNAME, B.DESC,
C.TDAY, C.SIT_TIME

FROM DOCTORS A

INNER JOIN SPECIALIZE B


ON A.DOCID=B.DOCID

INNER JOIN TIMESCHEDULE C


ON A.DOCID=C.DOCID

WHERE A.DOCID=1 AND


C.TDAY='WED';
NoSQ: MySQL-Introduction 75
JOINS – LEFT [OUTER ] JOIN
• The LEFT OUTER JOIN returns all
rows from the left hand table
specified in the ON condition and
only those rows from the other
table where the join condition is
fulfilled.
• SELECT <col (s) list> FROM
<table-1> LEFT JOIN
<table-2,…,table-n> ON
<join-condition>

NoSQ: MySQL-Introduction 76
Left Outer Join

NoSQ: MySQL-Introduction 77
JOINS – RIGHT [OUTER ] JOIN
• The MySQL Right Outer Join returns
all rows from the RIGHT-hand table
specified in the ON condition and
only those rows from the other
table where he join condition is
fulfilled.
• SELECT <col (s) list> FROM
<table-1 > RIGHT JOIN
<table-2,…,table-n> ON
<join-condition>

NoSQ: MySQL-Introduction 78
RIGHT JOIN

NoSQ: MySQL-Introduction 79
RIGHT JOIN - EXAMPLE
• SELECT TABLE112.ID, TABLE112.BVAL1,
TABLE112.BVAL2, TABLE111.ID,
TABLE111.AVAL1
FROM TABLE112
RIGHT OUTER JOIN TABLE111
ON TABLE112.BVAL1=TABLE111.AVAL1;

NoSQ: MySQL-Introduction 80
RIGHT JOIN – EXAMPLE EXPLAINED…
• SELECT TABLE112.ID,
TABLE112.BVAL1, TABLE112.BVAL2,
TABLE111.ID, TABLE111.AVAL1
FROM TABLE112
RIGHT OUTER JOIN TABLE111
ON
TABLE112.BVAL1=TABLE111.AVAL1

NoSQ: MySQL-Introduction 81
NoSQ: MySQL-Introduction 82
QUERIES USING JOINS
• List empno, ename, deptno, dname
– SELECT EMPNO, ENAME, D.DEPTNO, DNAME FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO;
• Display empno, ename, deptno, department name and salary grade of all
employees
– SELECT EMPNO, ENAME, D.DEPTNO, DNAME, SAL, GRADEFROM EMP E
INNER JOIN DEPT D ON E.DEPTNO = D.DEPTNO INNER JOIN SALGRADE S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL ORDER BY D.DEPTNO;
• List the employee number, name, designation, salary, manager number,
dept number, name, and salary grade of the all the employees belonging
to KING’s dept.
– SELECT E.EMPNO, E.ENAME, E.JOB, E.MGR, E.SAL, S.GRADE, D.LOC, D.DNAME
FROM EMP E INNER JOIN DEPT D ON E.DEPTNO = D.DEPTNO INNER JOIN
SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISAL
NoSQ: MySQL-Introduction 83
• Display the grade, number of employees, and max salary of each
grade.
– SELECT S.GRADE ,COUNT(*), MAX(SAL) FROM EMP E INNER JOIN
SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISAL GROUP BY
S.GRADE;
• List the most senior employee(s) working under the KING and
grade is more than 3.
– SELECT * FROM EMP WHERE HIREDATE IN (SELECT MIN(HIREDATE)
FROM EMP WHERE EMPNO IN (SELECT EMPNO FROM EMP E INNER JOIN
SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISAL AND S.GRADE IN (4
, 5))) AND MGR IN (SELECT EMPNO FROM EMP WHERE ENAME =
'KING');
NoSQ: MySQL-Introduction 84
QUERIES USING JOINS
• List the employees who are belonging DALLAS or CHICAGO with the
grade same as ADAMS or experience more than SMITH.
– SELECT * FROM EMP E INNER JOIN DEPT D ON E.DEPTNO = D.DEPTNO
INNER JOIN SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISALWHERE
ENAME NOT IN ('ADAMS' , 'SMITH') AND D.LOC IN ('DALLAS' , 'CHICAGO')
AND (S.GRADE IN (SELECT S.GRADE FROM EMP E INNER JOIN
SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISAL AND E.ENAME =
'ADAMS') OR DATEDIFF(SYSDATE(), HIREDATE) > (SELECT
DATEDIFF(SYSDATE(), HIREDATE) FROM EMP WHERE ENAME = 'SMITH'));

NoSQ: MySQL-Introduction 85
QUERIES USING JOINS – CONTD…
• List the emp whose salary is less his manager but more than any
other manager.
– SELECT DISTINCT W.EMPNO,W.ENAME,W.SAL FROM (SELECT
W.EMPNO,W.ENAME,W.SAL FROM EMP W INNER JOIN EMP M ON
W.MGR = M.EMPNO AND W.SAL<M.SAL) W, (SELECT * FROM EMP
WHERE EMPNO IN (SELECT MGR FROM EMP)) A WHERE W.SAL > A.SAL;
– (OR) SELECT * FROM EMP W,EMP M WHERE W.MGR = M.EMPNO AND
W.SAL < M.SAL AND W.SAL > ANY (SELECT SAL FROM EMP WHERE EMPNO
IN (SELECT MGR FROM EMP));

NoSQ: MySQL-Introduction 86
QUERIES USING JOINS – CONTD…
• List the manager number, name and the number of employees working for those managers in
the ascending of manager numbers
– SELECT W.MGR ,COUNT(*) FROM EMP W,EMP M WHERE W.MGR = M.EMPNO GROUP BY W.MGR ORDER
BY W.MGR ASC;
• List the employees who are senior to their own manager.
– SELECT E.EMPNO, E.ENAME, E.MGR, E.HIREDATE, M.EMPNO AS MGREMPO, M.ENAME AS
MGRENAME, M.HIREDATE AS MGRHIREDATE FROM EMP AS E INNER JOIN EMP AS M ON E.MGR
= M.EMPNO AND E.HIREDATE > M.HIREDATE;;
• List out the Names and Salaries of the employees along with their manager names and salaries
for those employees who earn more salary than their Manager.
– SELECT E.EMPNO, E.ENAME, E.MGR, E.HIREDATE, M.EMPNO AS MGREMPO, M.ENAME AS
MGRENAME, M.HIREDATE AS MGRHIREDATEFROM EMP AS E INNER JOIN EMP AS M ON E.MGR =
M.EMPNO AND E.HIREDATE < M.HIREDATE;
• List out the Names and Salaries of the employees along with their manager names and salaries
for those employees who earn more salary than their Manager
– SELECT R.EMPNO, R.ENAME, R.MGR, R.HIREDATE, MAX(R.SAL) FROM (SELECT E.EMPNO,
E.ENAME, E.MGR, E.HIREDATE, E.SAL FROM EMP AS E INNER JOIN EMP AS M ON E.MGR =
M.EMPNO AND E.HIREDATE < M.HIREDATE) R;

NoSQ: MySQL-Introduction 87
• Display departments without employees
– SELECT E.EMPNO, E.ENAME, D.DEPTNO, D.DNAME FROM DEPT D LEFT
JOIN EMP E ON E.DEPTNO=D.DEPTNO;

NoSQ: MySQL-Introduction 88

Das könnte Ihnen auch gefallen