v 1.0 oe nik 2013 1 dbman 2 sql introduction select basics select suffixes: from, order by, where
TRANSCRIPT
V 1.0
Introduction
• SQL = Structured Query Language• From the ’70s: IBM, first user: Oracle• Standards: SQL-86, SQL-89, SQL-92, SQL:1999,
SQL:2003, SQL:2008• CREATE, ALTER• SELECT• UPDATE, DELETE• Various prefixes, suffixes; different approaches;
different function names/parameters „SQL Dialects”
3OE NIK 2013
V 1.0
SQL Servers
• Oracle, IBM (DB2), Microsoft (MSSQL), Sybase (ASE, SQLAnywhere), Teradata
• PostgreSQL (~ Sun), MySQL ( Sun), Firebird, Interbase, MSACCESS
• Operating System: Oracle: Linux, Sun: Unix (Solaris), Microsoft: Windows Server, IBM: Unix (AIX)
• Development environments: Sun: Java, Microsoft: .NET, [Others: external libraries]
• Hardware: Sun: Sparc + Server/Workstation/ Storage, IBM: Datacenter, Server
4OE NIK 2013
V 1.0
20th of April, 2009.
• The contract is signed that means that Oracle buys the whole Sun Microsystems
• PostgreSQL, MySQL ( Sun), Firebird, Interbase, MSACCESS
• Operating Systems: Oracle: Linux, Sun: Unix (Solaris), Microsoft: Windows Server, IBM: Unix (AIX)
• Development environments: Sun: Java, Microsoft: .NET, [Others: external libraries]
• Hardware: Sun: Sparc + Server/Workstation/ Storage, IBM: Datacenter, Server
5OE NIK 2013
V 1.0
• „Oracle Corporation (NASDAQ:ORCL) announced today that it had completed its acquisition of Sun Microsystems, Inc.”
• „This time, the difficulty was persuading European antitrust regulators who were concerned about the fate under Oracle of the open-source MySQL database software business that was part of Sun.”
• „With the addition of servers, storage, Sparc processors, the Solaris operating system, Java, and the MySQL database to Oracle's portfolio of database, middleware, and business applications, we plan to engineer and deliver open and integrated systems -- from applications to disk -- where all the pieces fit and work together out of the box.”
• www.sun.com www.oracle.com/sun/
27th of January, 2010.
6OE NIK 2013
V 1.0
Sun?• OpenSolaris: KO ( OpenIndiana)• MySql: „alive?” ( MariaDB: LAMP, Google, Mozilla,
Wikimedia … Arch, Fedora, Gentoo, OpenSUSE, RedHat, Slackware)
• OpenOffice: KO ( LibreOffice, ApacheOO)• License changes, support changes ( obligatory HW
support) Oracle is an evil (? Cisco, MS ?), but important (!) company The presentations will focus on the Oracle and the MySQL
dialect – we will work with the ORACLE dialectWe will use the Oracle demo tables
7OE NIK 2013
V 1.0
Data Types(Oracle)• These types are used for all columns and function
parameters• Data types:
– char(N) – varchar(N) – varchar2(N) [255byte / 4K]– blob (vs. clob, ~2-4GB)– numeric(N[, M]) / number(N[, M]) / int, float– date / timestamp (time – not available in Oracle
instead usable: interval) alter session set NLS_DATE_FORMAT = 'YYYY-
MM-DD';
9OE NIK 2013
V 1.0
Data Types(MySQL)• char(N) – varchar(N) [rowsize: 65K]• blob (vs. text: tinytext, text, mediumtext, longtext,
max. 4GB)• tinyint (sbyte), smallint (integer), int, bigint (long),
float, double• date / time / datetime / timestamp• Others (year, enum, set, binary, bit, decimal,
numeric, bool – we will not use those)
10OE NIK 2013
V 1.0
Most simple queries
• MySQL:– From phpmyadmin or the command-line client– user: root, pw: empty; tables emp+dept– ora_MY_INIT.sql : import OR source \path\to\x.sql– show databases; use orademo; show tables;
• Oracle– From your browser or from the start menu
(command line)– work1 : magyar : Tigris-1– SQL Scripts / SQL Commands
• select ename from emp; • select * from emp; select * from dept;
12OE NIK 2013
V 1.0
SELECT• Select, order, filter, group the records the swiss
army knife of RDBMS systems
SELECT [prefixes: distinct, into, top, start at]
column1, …, columnN
FROMtable1, ...,tableN
[other suffixes: where, group by, having, union/minus/intersect, order by, limit, offset]
13OE NIK 2013
V 1.0
SELECTProcessing order of suffixes
1. FROM2. WHERE3. GROUP BY4. HAVING5. UNION/MINUS6. INTERSECT7. ORDER BY8. INTO
14OE NIK 2013
V 1.0
SELECTDisplayed order of suffixes
1. INTO2. FROM3. WHERE4. GROUP BY5. HAVING6. UNION/MINUS7. INTERSECT8. ORDER BY
15OE NIK 2013
V 1.0
Using aliases• Table-alias: obligatory for the whole query, the new
name must be used• Field-alias: Only formats/renames the output, the
original name/expression must be used in all suffixes (exception: ORDER BY)
• Oracle: “ for names, ‘ for strings• MSSQL: [] for names, ‘ for strings (possibly “)• MySQL: ` for names, ‘ or “ for strings• select `empno` as ID, ename as "Name", job as ′Job
name′, sal as Salary from emp as Worker;• Name (and alias) SHOULD NOT contain special
letters no need for [“`quoting`”] names!
16OE NIK 2013
V 1.0
Definition of stringsmysql> SELECT 'hello', '"hello"', '""hello""',
'hel''lo', '\'hello';
+-------+---------+-----------+--------+--------+
| hello | "hello" | ""hello"" | hel'lo | 'hello |
+-------+---------+-----------+--------+--------+
mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo", "\"hello";
+-------+---------+-----------+--------+--------+
| hello | 'hello' | ''hello'' | hel"lo | "hello |
+-------+---------+-----------+--------+--------+
17OE NIK 2013
V 1.0
Definition of stringsmysql> SELECT 'This\nIs\nFour\nLines';
+--------------------+
| This
Is
Four
Lines |
+--------------------+
mysql> SELECT 'disappearing\ backslash';
+------------------------+
| disappearing backslash |
+------------------------+
18OE NIK 2013
V 1.0
Table alias• select * from emp workers;• select * from dept departments;• select empno from emp;• select emp.empno from emp;• select workers.empno from emp workers;
It will be essential if the same table is used more than once (e.g. worker + boss)
20OE NIK 2013
V 1.0
ORDER BY• select empno, ename from emp order by ename;• select empno, ename from emp order by ename asc; • select empno, ename as NAME from emp order by name
desc;• select ename, sal from emp order by sal asc, ename
desc;
21OE NIK 2013
V 1.0
DISTINCTFilter out repeated output lines:• select mgr from emp order by mgr;• select distinct mgr from emp order by mgr;• select mgr, sal from emp order by mgr;• select distinct mgr, sal from emp order by mgr;
22OE NIK 2013
V 1.0
WHEREOperators
=, <, >, <=, >=, <>• select ename, sal from emp where sal>2000;Between• select ename, sal, comm from emp where sal
between 1000 and 2000;
23OE NIK 2013
V 1.0
WHERENull
• PASCAL: FALSE, 0, ""; ANSI C: 0 == ""• PHP: FALSE == 0 == ""; 0 === "" false• SQL: FALSE, unknown, 0, "", NULL• If there is NOTHING in the field, then it contains NULL• Every operation with NULL results in unknown/NULL
Three-valued-logic avoid! (see later)• select * from emp where comm is null;• select * from emp where comm is not null;
24OE NIK 2013
V 1.0
WHEREOperators
IN, ANY, ALL (non-subquery usage)• select ename, sal, comm from emp
where sal IN (3000, 5000);• select ename, sal, comm from emp
where sal < ANY (3000, 5000);• select ename, sal, comm from emp
where sal < ALL (3000, 5000);• select ename, sal, comm from emp
where comm in (NULL, 500); ???
25OE NIK 2013
V 1.0
WHERELike operator
Like: Comparison string: %=string, _=1 character• select ename, sal from emp where ename like '%E%'; --
upper, lower• select ename, sal from emp where ename like '%E_';• select ename, sal from emp where (sal>2000) and
(ename like '%E%');• select ename from emp where ename like '%\_%'
escape '\';
26OE NIK 2013
V 1.0
Field list – not always with fields onlyConstans, expressions, functions, variables:• select ename, ':' as colon, sal from emp;• select sal, sal+1000 as bigsal from emp;• Oracle> select ename, sysdate, sal from emp;• MySQL> select ename, NOW(), SYSDATE(), CURDATE(),
sal from emp;• Oracle> select ename||' - '||hiredate||' -- '||
sysdate||'.' as FULL from emp;• MySQL> select concat(ename, ' ', '\'s job is', ' ', job) as
full from emp;
27OE NIK 2013
V 1.0
Expressions in the field list
• select ename as Name, sal as Salary from emp;• select ename as Name, (sal+1000) as Salary from emp;• select ename as Name, sal as Salary, comm as Extra,
(sal+comm) as SumSal from emp;
28OE NIK 2013
V 1.0
Treating NULL values
• Oracle, Postgre, MSSQL: NVL, NVL2, Coalesce• MSSQL: ISNULL(p1, p2)• MySQL: Coalesce(p1, p2, p3, …)
IFNULL (p1, p2)• select ename as Name , sal as Salary, comm as Extra,
(sal+ifnull(comm, 0)) as SumSal from emp;• select ename as Name , sal as Salary, comm as Extra,
(sal+ifnull(comm, 0)) as SumSal, ifnull(mgr, 'NONE') as Boss from emp; -- type assignment with oralce+NVL, this can be a problem
29OE NIK 2013
V 1.0
Control flow functions
http://psoug.org/reference/decode_case.html
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
CASE, if(), ifnull()
30OE NIK 2013
V 1.0
String functions
http://psoug.org/reference/string_func.html , + INSTR, SUBSTR, NVL
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
• concat_ws(), concat(), instr(), length(), LIKE, lower()/upper(), lpad()/rpad(), ltrim()/rtrim()/trim(), replace(), strcmp(), substr()/substring()
• Row-level functions: select length(ename) as NameLength from emp;
• select ename, rpad('', round(sal/500)+1, '*') as graph from emp;
31OE NIK 2013
V 1.0
Numeric functions
http://psoug.org/reference/number_func.html ABS, COALESCE, LENGTH, MOD, NVL, POWER, ROUND, SQRT, TRUNC+ conversion functions
http://dev.mysql.com/doc/refman/5.0/en/numeric-functions.html
• abs(), ceil()/floor()/round(), conv(), mod(), pow(), rand(), sign(), sqrt()
• Operators: http://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html
32OE NIK 2013
V 1.0
Date functionshttp://psoug.org/reference/date_func.html
SYSDATE, TO_CHAR, TO_DATE• alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD'• select hiredate,(to_char(sysdate, 'YYYY')-
to_char(hiredate, 'YYYY')) as diff from emp;• select hiredate,months_between(sysdate, hiredate)/12
from emp;
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
• curdate(), date_format(), datediff(), extract(), now(), sysdate(), timediff(), unix_timestamp()
33OE NIK 2013
V 1.0
Date functions• select ename, extract(year from curdate()) - extract(year
from hiredate) as diff from emp;• MySQL> select ename, substr(curdate(), 1, 4) -
substr(hiredate, 1, 4) as diff from emp;• MySQL> select ename, round(datediff(curdate(),
hiredate)/365.25) as diff from emp;• MySQL> select ename,
round( (unix_timestamp(curdate()) - unix_timestamp(hiredate))/86400/365.25) as diff from emp;
• ORACLE> months_between()• MSSQL> datepart()
34OE NIK 2013
V 1.0
SELECTDisplayed order of suffixes
1. INTO2. FROM3. WHERE4. GROUP BY5. HAVING6. UNION/MINUS7. INTERSECT8. ORDER BY
35OE NIK 2013