๋ฐ˜์‘ํ˜•
JuneBee
JuneBee
JuneBee
์ „์ฒด ๋ฐฉ๋ฌธ์ž
์˜ค๋Š˜
์–ด์ œ
  • ๋ถ„๋ฅ˜ ์ „์ฒด๋ณด๊ธฐ (103)
    • ๐Ÿ‘” JOB (10)
      • ์ „ํ˜• ํ›„๊ธฐ (10)
    • ๐ŸŽฎ GAME (9)
      • ์ ค๋‹ค | ์™•๊ตญ์˜ ๋ˆˆ๋ฌผ ๊ฒŒ์ž„ ์ผ๊ธฐ (9)
    • ๐Ÿ““ STUDY (60)
      • JAVA (15)
      • TIL (2)
      • FASTCAMPUS (32)
      • ํ™˜๊ฒฝ์„ค์ • (2)
      • YOCTO (1)
      • OS (4)
      • ๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ ์ธ ์•ก์…˜ (2)
    • ๐ŸŽงDAILY (6)
    • ๐Ÿ‡ฉ๐Ÿ‡ช GERMAN (18)
      • ๋Œ€ํ•™์› ์ง€์› (3)
      • ์ง€์› ํ›„๊ธฐ (11)
      • ๋…์ผ์–ด ์‹œํ—˜ (4)

๋ธ”๋กœ๊ทธ ๋ฉ”๋‰ด

  • ํ™ˆ
  • ์ผ์ƒ

๊ณต์ง€์‚ฌํ•ญ

์ธ๊ธฐ ๊ธ€

ํƒœ๊ทธ

  • ๋ฐฑํŠธ๋ž˜ํ‚น
  • ๊ฒŒ์ž„์ผ๊ธฐ
  • ํŒจ์บ ์ฑŒ๋ฆฐ์ง€
  • ์ ค๋‹ค
  • ์™•๊ตญ์˜๋ˆˆ๋ฌผ
  • ์ž๋ฃŒ๊ตฌ์กฐ
  • Java
  • ํŒจ์ŠคํŠธ์บ ํผ์Šค
  • ์ง์žฅ์ธ์ž๊ธฐ๊ณ„๋ฐœ
  • ์™•๋ˆˆ
  • C/C++
  • ํ•œ๋ฒˆ์—๋๋‚ด๋Š”์ฝ”๋”ฉํ…Œ์ŠคํŠธ369JavaํŽธ์ดˆ๊ฒฉ์ฐจํŒจํ‚ค์ง€Online.
  • ํŒจ์ŠคํŠธ์บ ํผ์Šคํ›„๊ธฐ
  • B1
  • ๋ชจํ—˜์ผ๊ธฐ
  • ์ทจ์—…์ค€๋น„
  • ๋…์ผ์œ ํ•™
  • ๋…์ผ
  • ์„์‚ฌ
  • bruteforce
  • SSAFY
  • ํฌ๋ฃจ์Šค์นผ
  • ์ •๋ ฌ
  • ์ง์žฅ์ธ์ธ๊ฐ•
  • ์œ ํ•™
  • sort
  • ๋…์ผ์–ด
  • ์‹ธํ”ผ
  • telc
  • ํ”Œ๋ ˆ์ด์ผ๊ธฐ

์ตœ๊ทผ ๋Œ“๊ธ€

์ตœ๊ทผ ๊ธ€

ํ‹ฐ์Šคํ† ๋ฆฌ

hELLO ยท Designed By ์ •์ƒ์šฐ.
JuneBee

JuneBee

ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 7์ผ์ฐจ
๐Ÿ““ STUDY/FASTCAMPUS

ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 7์ผ์ฐจ

2021. 11. 7. 19:53
728x90
๋ฐ˜์‘ํ˜•

๋‚ ์งœ : 2021๋…„ 11์›” 7์ผ
์‹œ์ฒญ ๊ฐ•์˜ ; SQL CH02

SQL ๊ณต๋ถ€๋ฅผ ํ•ด์•ผํ•ด์„œ ์˜ค๋Š˜์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ฐ•์˜๊ฐ€ ์•„๋‹ˆ๋ผ SQL ๊ฐ•์˜๋ฅผ ๋“ค์—ˆ๋‹ค.

๊ธฐ๋ณธ์ ์ธ ๊ธฐ๋Šฅ๋“ค์„ ์•Œ๋ ค์ฃผ์…จ๋Š”๋ฐ, ๋‚˜๋Š” MySQL์„ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์—, https://www.mysqltutorial.org/ ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ์ •๋ฆฌํ•ด ๋ณด์•˜๋‹ค.

 

<1> Querying Data

๐Ÿ“Œ
SELECT FROM:
  • Use the SELECT statement to select data from a table.
  • Use the SELECT * to select data from all columns of a table.

SELECT:

  • MySQL SELECT statement doesn’t require the FROM clause
  • Use the dual table if you want to use the FROM clause but don’t want to reference a table. (dual์€ dummy table์ž„)
  • Assign an alias to a column to make it more readable.

1. Select

In MySQL, SELECT statement is used to query data from the table.

SELECT select_list #case not sensitive
FROM table_name; 

 

Example

Retrieve Data from single Column

select lastName;
from employees;
 

Receive Data from multiple Columns

select lastName,
			 firstName,
			 jobTitle
from employees;
 

Retrive all

select * from employee;s

2. Creating Table

Create

In MySQL, you can create using

CREATE

keyword

create table members(
	member_id int auto_increment,
	name varchar(100),
	primary key (member_id)
);

Insert

In MySQL, you can insert data using

INSERT INTO

keyword

insert into members(name) -- ๋‹ค๋Ÿ‰์˜ name ์ถ”๊ฐ€
values('John'),('Jane'),('David');

<2> Sorting Data

๐Ÿ“Œ
ORDER BY:
  • Use the ORDER BY clause to sort the result set by one or more columns.
  • Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.
  • The ORDER BY clause is evaluated after the FROM and SELECT clauses.
  • In MySQL, NULL is lower than non-NULL values

1. Order By

When using

SELECT

statement, the order of rows in the result set is unspecified. In order to sort the dataset, use

ORDER BY

clause.

select select_list
from table_name
order by
	column1 [ASC|DESC],
	column2 [ASC|DESC],
	...;

Ascending

Ascending order → ๋ช…์‹œํ•˜์ง€ ์•Š์œผ๋ฉด ๊ธฐ๋ณธ์ ์œผ๋กœ ASC์ด๋‹ค

Descending

ORDER BY column1 DESC;

Sort Result set by one column

select first_name,
			 last_name,
from employees
order by last_name;
 

Sorting multiple columns

select first_name,
			 last_name,
			 hire_date
from employees
order by 
				last_name ASC
				hire_date DESC;
				
 

Sorting result set

You can also sort result expression using

order by

clause

select first_name,
			 last_name,
			 salary*commision_pct AS '๋ˆ๋ˆ'
from employees
order by 
		salary*commission_pct DESC;
 
๐Ÿ“Œ
1. As ๋Š” ์ƒ๋žต ๊ฐ€๋Šฅํ•œ ํ‚ค์›Œ๋“œ 2. ๋งŒ์ผ ๋„์–ด์“ฐ๊ธฐ๋‚˜ ํŠน์ˆ˜ ๋ฌธ์ž๊ฐ€ ์žˆ๋‹ค๋ฉด ' '๋กœ ๋ฌถ๊ธฐ

2. Field () Function

	FIELD(str1, str2, ....)  -- syntax

Field() function returns position of the string in the str1, str2, ... list.

Example:

	SELECT FIELD ('B','A','B','C');
	SELECT FEILD('D','A','B','C');

Sort data using a custom list

EXAMPLE 1:

Suppose that you want to sort the sales orders based on their statuses in the following order:

  • In Process
  • On Hold
  • Canceled
  • Resolved
  • Disputed
  • Shipped
SELECT 
    orderNumber, status
FROM
    orders
ORDER BY FIELD(status,
        'In Process',
        'On Hold',
        'Cancelled',
        'Resolved',
        'Disputed',
        'Shipped');

๋ฆฌ์ŠคํŠธ: status๋ฅผ order ํ•ด๋ผ. ์–ด๋А ์ˆœ์œผ๋กœ? ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์ˆœ์œผ๋กœ

EXAMPLE2 :

Employees ์•ˆ์˜ Salary๋ฅผ job_id, hire_date ์ˆœ์œผ๋กœ order ํ•ด๋ผ

select first_name, -- ํ…Œ์ด๋ธ” column์— ๋ณด์ผ ๋‚ด์šฉ
			 last_name,
			 job_id,
			 hire_date,
			 salary
from employees      -- from which table?
order by field(     -- order salary:
				 salary,
				 job_id,    -- by 1. job_id
				 hire_date  -- and 2. hire_date
	);

Order by and Null

In mySQL, NULL comes before non-null values.

  1. Order By [ASC] : null comes on top
  1. Order By [DESC] : null comes last

 

<3> Filtering Data

1. Where

Specify a search condition for the row returned by query

SELECT select_list
FROM   table_name
WHERE  search_condition;

Equality Operator

SELECT last_name,
			 first_name,
			 job_id
FROM   employees
WHERE  job_id='IT_PROG';

JOB ID๊ฐ€ IT PROG์ธ ์ง์›๋“ค์„ ์„ ํƒ

AND Operator

job_id๊ฐ€ IT PROG ์ด๊ณ (AND), ์—ฐ๋ด‰์ด 5000 ์ด์ƒ์ธ ์ง์›

SELECT last_name,
			 first_name,
			 job_id,
			 salary
FROM   employees
WHERE  job_id='IT_PROG'
			 AND salary>5000;

 

OR Operator

job_id๊ฐ€ IT PROG ์ด๊ฑฐ๋‚˜(OR) FI ACCOUNT ์ด๊ณ (AND), ์—ฐ๋ด‰์ด 5000 ์ด์ƒ์ธ ์ง์›

SELECT last_name,
			 first_name,
			 job_id,
			 salary
FROM   employees
WHERE  (job_id='IT_PROG'
				OR
			  job_id='FI_ACCOUNT') 
			  AND salary >5000;
 

BETWEEN Operator

Between Operator returns true if a value is in a range

expression BETWEEN A and B -- syntax

employee id ๊ฐ€ 100-110 ์ธ ์ง์›๋“ค

SELECT employee_id,
			 first_name,
			 last_name
FROM employees
WHERE employee_id BETWEEN 100 AND 110
ORDER BY employee_id;
 

LIKE Operator

LIKE Operator evalutaes to TRUE if a value matches a specified pattern → Pattern์€ % ์™€ _ ์™€์ผ๋“œ ์นด๋“œ๋กœ ์ •์˜๋œ๋‹ค.

  1. % : matches any string of zero or more characters (ํฌํ•จ)
  1. _ : matches any single character (๋ฒˆ์งธ)

%Son : ์„ฑ์ด son์œผ๋กœ ๋๋‚˜๋Š” ์ด๋ฆ„

SELECT 
    first_name, 
    last_name
FROM
    employees
WHERE
    last_name LIKE '%son'
ORDER BY first_name;

%se% :์„ฑ์— se๋ฅผ ๋ฌธ์ž์—ด๋กœ ํฌํ•จํ•˜๋Š” ์ด๋ฆ„

SELECT 
    first_name, 
    last_name
FROM
    employees
WHERE
    last_name LIKE '%se%'
ORDER BY first_name;

%s_ : ์„ฑ์˜ ๋์—์„œ ๋‘๋ฒˆ์งธ ๊ธ€์ž๊ฐ€ s์ธ ์ด๋ฆ„

SELECT 
    first_name, 
    last_name
FROM
    employees
WHERE
    last_name LIKE '%s_'
ORDER BY first_name;

IN Operator

IN Operator returns true if a value matches any value in a list

value IN (val1, val2...) -- syntax

๋ถ€์„œ ๋ฒˆํ˜ธ๊ฐ€ 10,90,100์ธ ์ง์›์„ ๊ณ ๋ฅด์‹œ์˜ค.

SELECT 
    first_name, 
    last_name, 
    department_id
FROM
    employees
WHERE
    department_id IN (60,90,100)
ORDER BY 
    department_id;

The following table shows the comparison operators that you can use to form the expression in the WHERE clause.

WHERE ์ ˆ์˜ Operators

Operator Description
= Equal to. You can use it with almost any data type.
<> or != Not equal to
< Less than. You typically use it with numeric and date/time data types.
> Greater than.
<= Less than or equal to
>= Greater than or equal to

NOT EQUAL Operator(<>)

<> : ~ ๊ฐ€ ์•„๋‹Œ

SELECT 
    last_name, 
    first_name, 
    job_id
FROM
    employees
WHERE
    job_id <> 'IT_PROG';

 

2. DISTINCT

SELECT DISTINCT ์ ˆ→ remove duplicate rows

#SYNTAX
SELECT DISTINCT select_list
FROM            table_name
WHERE           search_condition
ORDER BY        sort_expression;

One column

WIthout Distinct vs With Disctinct → ์ค‘๋ณต๋œ lastname ์ด ์ œ๊ฑฐ๋œ๋‹ค

SELECT 
    last_name
FROM
    employees
ORDER BY 
    last_name;

^ DISTINCT๊ฐ€ ์•ˆ์“ฐ์ž„: Grant ๋ž€ ์„ฑ์ด ์ค‘๋ณต๋œ ๋งŒํผ ํ…Œ์ด๋ธ”์— ๋ณด์—ฌ์ค€๋‹ค

 
SELECT 
    DISTINCT last_name
FROM
    employees
ORDER BY 
    last_name;

^ When Distinct is used: Grant only appears once on the table

 

NULL Values

When you specify a column with

NULL values

in the Distinct Clause → it

only keeps one null values

๐Ÿ“Œ You can also do this:

WHERE State IS NOT NULL

Using Not Null with where condition gives same result with saying, select distinc state

Where์˜ ์ˆ˜ํ–‰๋ฌธ์ด ๋” ๋จผ์ €๊ธฐ ๋•Œ๋ฌธ์—, ์ฝ”๋“œ๋ฅผ ์งค ๋•Œ ์–ด๋А๊ฒŒ ๋” ํšจ์œจ์ ์ธ์ง€๋ฅผ ์ƒ๊ฐํ•˜๋ฉฐ ์งœ์•ผํ•œ๋‹ค.

 

Multiple Column

You can use multiple columns in the distinct clause, and it will use combination of values in theses columns → So yes, if both column and row contents are same it will omit one but else if theres multiple on columns & each rows are unique → it will still display multiples columns but with unique rows

SELECT DISTINCT job_id, first_name,last_name
FROM employees
ORDER BY last_name;

 

Yes, there are multiple SA_REP → but Ellen and Sundar are distinct

And Yes, there are two Cambrault but the are different person

→ In mySQL, when you use distinct on multiple columns it use combination of values so they are all at the end, unique

3. AND OPERATOR

WHERE ์ ˆ์—์„œ๋„ ๋‹ค๋ฃจ์—ˆ์ง€๋งŒ, AND OPERATOR can be combined into multiple boolean expressions to filter data. AND returns 0,1, or NULL

	A AND B --syntax

MySQL์—์„œ Null ์ด๋ž€: ์•Œ ์ˆ˜ ์—†๋Š” ์ˆ˜๋ฅผ ๋œปํ•œ๋‹ค.

๋”ฐ๋ผ์„œ, true & null ์€ ์•Œ ์ˆ˜ ์—†์ง€๋งŒ, false & null ์€ false ๊ฐ€ ๋˜๋Š” ๊ฒƒ์ด๋‹ค

Short-Circuit Evaluation:

	SELECT 1 = 0 AND 1 / 0;  -- and ์—ฐ์‚ฐ์˜ short circuit evaluation
	SELECT 1 = 2 OR  1 / 0;  -- or ์—ฐ์‚ฐ์˜ short circuit evaluation

4. OR OPERATOR

	A OR B --syntax

์•ž์„œ AND์—์„œ ์„ค๋ช…ํ–ˆ๋˜๊ฒƒ๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ, MySQL์—์„œ NULL์€ ์•Œ ์ˆ˜ ์—†๋Š” ์ˆ˜์ด๋‹ค. ๋”ฐ๋ผ์„œ, OR ์—ฐ์‚ฐ์—์„œ ์•Œ์ˆ˜์—†๋Š”์ˆ˜ or true๋Š” ํ•˜๋‚˜๋ผ๋„ true์ด๋ฏ€๋กœ true, ์•Œ์ˆ˜์—†๋Š”์ˆ˜ or false๋Š” ์•Œ์ˆ˜์—†๋Š”์ˆ˜์˜ ๊ฐ’์„ ๋ชจ๋ฅด๊ธฐ๋•Œ๋ฌธ์— ์•Œ์ˆ˜ ์—†๋Š” ์ˆ˜ ์ฆ‰ null์„ returnํ•œ๋‹ค

5. IN Operator

IN Operator allows you to determine if a value matches any value in a list of values

→ value=value1 OR value =value2 OR value=value3 OR...์„ ๋ฌถ์€๊ฒƒ์ด๋ผ๊ณ  ๋ณด๋ฉด ๋œ๋‹ค → value in (value1,value2,value3...)

WHERE ์ ˆ์ด๋‚˜ SELECT์ ˆ์—์„œ ์ฃผ๋กœ ์“ฐ์ธ๋‹ค

SELECT 
    officeCode, 
    city, 
    phone
FROM
    offices
WHERE
    country = 'USA' OR country = 'France';
SELECT 
    officeCode, 
    city, 
    phone
FROM
    offices
WHERE
    country IN ('USA', 'France');

์œ„์˜ ๋‘ ์ฝ”๋“œ๋Š” ๊ฐ™์€ ์ฝ”๋“œ์ด๋‹ค

6. NOT IN Operator

	value NOT IN (value1, value2, value3 ...) -- syntax
	value <> value1 AND value<> value2 <> value<> value3  -- Use <>
	NOT(value= value1 OR value =value2 OR value=value3.....) --USE NOT OR

NOT IN ์„ ์“ฐ๋ฉด ์‰ฝ๊ฒŒ ๋ฌถ์„ ์ˆ˜ ์žˆ๋‹ค. <>์€ ํ•˜๋‚˜์ผ๋•Œ๋งŒ ์“ฐ์ž..

7. BETWEEN

	value BETWEEN val1 AND val2;    --BETWEEN A AND B
	value >= val1 AND value<=val2
	value NOT BETWEEN val1 AND val2 --NOT BETWEEN A AND B
	value <val2 OR value>val1
๐Ÿ“Œ
BETWEEN์˜ ์‘์šฉ - DATES

๋งŒ์ผ, ๋‚ ์งœ๊ฐ€ range ์•ˆ์— ๋“œ๋Š”์ง€ ๋ณด๊ณ  ์‹ถ์„ ๋•Œ:

SELECT 
   orderNumber,
   requiredDate,
   status
FROM 
   orders
WHERE 
   requireddate BETWEEN 
     CAST('2003-01-01' AS DATE) AND 
     CAST('2003-01-31' AS DATE);

→used CAST() to cast the literal string '2003-01-01' into a DATE value:

8. LIKE

๐Ÿ“Œ
[SUMMARY]
  • Use the LIKE operator to test if a value matches a pattern.
  • The % wildcard matches zero or more characters.
  • The _ wildcard matches a single character.
  • Use ESCAPE clause specifies an escape character other than the default escape character (\).
  • Use the NOT operator to negate the LIKE operator.

LIKE๋Š” ํŒจํ„ด์„ ์ฐพ์„ ๋•Œ ์“ฐ์ธ๋‹ค

% Wilde Card

  1. 'A%' : A ์œผ๋กœ ์‹œ์ž‘
SELECT 
    employeeNumber, 
    lastName, 
    firstName
FROM
    employees
WHERE
    firstName LIKE 'a%'; -- Firstname์ด a ๋กœ ์‹œ์ž‘ํ•˜๋Š” ์‚ฌ๋žŒ (๋Œ€์†Œ๋ฌธ์ž x)
  1. '%A' : A ์œผ๋กœ ๋๋‚จ
SELECT 
    employeeNumber, 
    lastName, 
    firstName
FROM
    employees
WHERE
    firstName LIKE '%son'; -- Firstname์ด son ๋กœ ๋๋‚˜๋Š” ์‚ฌ๋žŒ
  1. '%A%' : A๊ฐ€ ๋ฌธ์ž์—ด ์ค‘๊ฐ„์— ํฌํ•จ๋จ
SELECT 
    employeeNumber, 
    lastName, 
    firstName
FROM
    employees
WHERE
    firstName LIKE '%so%'; -- Firstname์— so ๊ฐ€ ๋“ค์–ด๊ฐ€๋Š” ์‚ฌ๋žŒ

_ Wild Card

  1. 'A_B' : AaB, AbB, AcB,AdB.... ๋“ฑ ์ค‘๊ฐ„์— ๋“ค์–ด๊ฐ€๋Š”๊ฑด ์ƒ๊ด€ ์—†์Œ
SELECT 
    employeeNumber, 
    lastName, 
    firstName
FROM
    employees
WHERE
    firstName LIKE 't_m'; -- tom, tim ๋“ฑ firstname์— t_m์ธ ๋ฌธ์ž์—ด

NOT

NOT Operator์„ ์“ฐ๋ฉด, ์ด๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ๋ฌธ์ž์—ด์ด ๋‚˜์˜ด

ESCAPE

Pattern ์ด %๋‚˜ _ ๋“ฑ์˜ ์บ๋ฆญํ„ฐ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ์„ ๋•Œ, escape์ ˆ์„ ์“ด๋‹ค

→ ๋ฐฑ๋ถ„์œจ %๋ผ๋ฉด : %_20%๋ผ๊ณ  ํ•œ๋‹ค๋ฉด 20์„ ํฌํ•จํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์ฐพ๊ฒŒ๋œ๋‹ค. ์ด๋•Œ backslash๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ %\_20%๋ผ๊ณ  ํ‘œํ˜„ํ•˜๋ฉด ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ํ•œ๋‹ค

%์™€ _ ๋ฟ๋งŒ์•„๋‹ˆ๋ผ $๊ฐ™์€ SPECIAL CHARACTERES๋„ ํฌํ•จํ•œ๋‹ค

SELECT 
    productCode, 
    productName
FROM
    products
WHERE
    productCode LIKE '%$_20%' ESCAPE '$';

9. LIMIT

use LIMIT to constrain the number of rows returned by SELECT statement

# SYNTAX
SELECT select_list
FROM   table_name
LIMIT  [offset,] row_count; 
-- offset: specifies the offset of the first row to return (0๋ถ€ํ„ฐ ์‹œ์ž‘)
-- row_count: specifies the maximum number of rows to return

Example:

Get Highest / Lowest rows

SELECT
	employee_id,
	start_date,
	end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 5;

์ผ ๊ฒฝ๋ ฅ์ด ๊ฐ€์žฅ ํฐ ์‚ฌ๋žŒ top (highest) 5๋ช…์„ ์‚ฐ์ถœ

Pagination

When you display data on the screen, you foten want to divide rows into pages, where each page contains a limited number of rows liek 10 or 20

You can use LIMIT to do so:

  1. Use COUNT(*) aggregate function to get the total rows
SELECT COUNT(*)
FROM   employees;
  1. Use LIMIT to get rows of page 1 which contains frist alphabetically sorted 10 employees
SELECT first_name,
		   last_name
FROM   employees
ORDER BY last_name
LIMIT 10;
 

3. Use LIMIT to get second page →11~20:

SELECT first_name,
		   last_name
FROM   employees
ORDER BY last_name
LIMIT 10 ,10;
 

GET Nth Highest or Lowest Value

  1. Nth : LIMIT n-1,1 returns 1 row starting at the row nn-1์ธ ์ด์œ : index๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค
# SYNTAX
SELECT select_list
FROM table_name
ORDER BY sort_expression
LIMIT n-1, 1;

Find employee with second-highest work experience:

n: 2๋ฒˆ์งธ → n-1 =1

SELECT
	employee_id,
	start_date,
	end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 1,1;

Find top 3 employees with highest work experience:

 

SELECT
	employee_id,
	start_date,
	end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 0,3;

→ ํ•˜์ง€๋งŒ, ์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” LIMIT3; ๊ณผ ๋™์ผํ•œ function์ž„

LIMIT & DISTINCT clauses

If you use LIMIT clause with the DISTINCT clause → MySQL immediately stops seraching when it finds the number of unique rows specified in the LIMIT clause

-- Syntax:
SELECT DISTINCT row_name
FROM            table_name
WHERE           row_name is something
LIMIT           limit_number;

Example:

SELECT DISTINCT
    state
FROM
    customers
WHERE
    state IS NOT NULL
LIMIT 5;
 

10. IS NULL

๐Ÿ“Œ
IS NULL:
  • Use the IS NULL operator to test if a value is NULL or not. The IS NULL operator returns one if a value is NULL.
  • The IS NOT NULL returns one if a value is not NULL

Test whether a value is NULL or not by using IS NULL operator

MySQL์—์„œ์˜ null ์€ ์•Œ ์ˆ˜ ์—†๋Š” ๊ฐ’์ด๋‹ค. → false ๊ฐ€ ์•„๋‹ˆ๋‹ˆ ํ˜ผ๋ˆ x

value is null -- syntax
value is not null

SELECT 1 is null, -- 0
			 0 is null, -- 0
			 null is null -- 1(true)

To be Compatible with ODBC programs, MySQL supports some specialized features of the IS NULL operator → Date ('0000-00-00') and @@sql_auto_is_null variable

DATE

  1. If a DATE or DATETIME column has a NOT NULL constraint and contains a special date '0000-00-00', you can use the IS NULL operator to find such rows.
CREATE TABLE IF NOT EXISTS projects ( -- project ํ…Œ์ด๋ธ” ๋งŒ๋“ค๊ธฐ
    id INT AUTO_INCREMENT,
    title VARCHAR(255),
    begin_date DATE NOT NULL,         -- date ์— not null function ์ฃผ๊ธฐ
    complete_date DATE NOT NULL,
    PRIMARY KEY(id)
);
  1. Insert some rows
INSERT INTO projects(title,begin_date, complete_date) -- ํ…Œ์ด๋ธ”์— ๊ฐ’ ์ถ”๊ฐ€
VALUES('New CRM','2020-01-01','0000-00-00'),          -- 0000-00-00 : null date
      ('ERP Future','2020-01-01','0000-00-00'),
      ('VR','2020-01-01','2030-01-01');
  1. Use IS NULL operator to select rows with the values in the complete_date column is 0000-00-00
SELECT * 
FROM projects
WHERE complete_date IS NULL; -- date๊ฐ€ null ์ธ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ๋Š”๋‹ค: 0000-00-00์ธ ๋‚ ์งœ

@@sql_auto_is_null

If the variable @@sql_auto_is_null is set to 1, you can

get the value of an auto_increment columnafter executing an INSERT statement by using the IS NULL operator

.

  1. Set variable @@sql_auto_is_null to 1
SET @@sql_auto_is_null = 1;
  1. Insert new row into the project table:
INSERT INTO projects(title,begin_date, complete_date)
VALUES('MRP III','2010-01-01','2020-12-31');
  1. Use IS NULL operator to get the generated value of the id column
SELECT 
    id
FROM
    projects
WHERE
    id IS NULL;

 

<4> Joining Tables

1. Alias

๐Ÿ“Œ
Alias๋Š” ์ฟผ๋ฆฌ์— ๊ฐ€๋…์„ฑ์„ ๋”ํ•ด์ค€๋‹ค

Alias for Columns

# Syntax
-- 1: 
SELECT 
   [column_1 | expression] AS descriptive_name
FROM table_name;
-- 2: As ์ƒ๋žต
SELECT 
   [column_1 | expression] AS descriptive_name
FROM table_name;
-- 3: `` ๋‚˜ '' ๋กœ ๋ฌถ๊ธฐ
SELECT 
   [column_1 | expression] AS `descriptive_name`
FROM table_name;

Concat_WS()

๐Ÿ“Œ
CONCAT_WS() : Concatenate Strings with a separator syntax: CONCAT_WS(seperator,string1,string2, ... );
SELECT
			CONCAT_WS(',' ,last_name,first_name)
FROM  employees;

CONCAT_WS () ๋ฅผ ์“ฐ๊ณ  ๋‚œ ํ›„, table column์˜ ์ด๋ฆ„์„ ์‚ดํŽด๋ณด๋ฉด, SELECT ์•ˆ์˜ ๊ตฌ์ ˆ์ด ๊ทธ๋Œ€๋กœ ๋“ค์–ด๊ฐ€์žˆ๋Š”๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค → ๊ฐ€๋…์„ฑ์„ ๋”ํ•ด์ฃผ๊ธฐ ์œ„ํ•ด Alias ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค

SELECT
			CONCAT_WS(',' ,last_name,first_name) `FULL NAME`
FROM  employees;

Alias for Table

๐Ÿ“Œ
Alias For Table Name: ์ฃผ๋กœ, INNER JOIN, LEFT JOIN, RIGHT JOIN clauses ์™€ subqueries์—์„œ ์“ฐ์ธ๋‹ค

Table ๋ช…๋„ alias๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ค๋ฅด๊ฒŒ ํ‘œ๊ธฐํ•  ์ˆ˜ ์žˆ๋‹ค

# Sytax:
table_name AS table_alias

# refer table column:
table_alias.column_name

[์˜ˆ์‹œ] employees์— e๋ผ๋Š” alias๋ฅผ ์ฃผ์—ˆ๋‹ค

→ ํ™œ์šฉ : table column์„ ์‰ฝ๊ฒŒ refer ํ•  ์ˆ˜ ์žˆ๋‹ค

SELECT * FROM employees e;
SELECT 
			 e.first_name,
			 e.last_name
FROM   employees e
ORDER BY e.first_name;

WHY? Why do we use Table Alias???

 

Both Customers table and Orders table have customerNumbers. Thus, if we use without alias we will get an error : Error Code: 1052. Column 'customerNumber' in on clause is ambiguous

Thus, we need to use table alias

SELECT
	customerName,
	COUNT(o.orderNumber) total
FROM
	customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
GROUP BY
	customerName
ORDER BY
	total DESC;

2. Join

Introduction to MySQL Join clauses

A relational database consists of multiple related tables linking together using common columns, which are known as foreign key columns. Because of this, data in each table is incomplete from the business perspective.

On above database, to get complete order information → we need BOTH orders and orderDetails

→ That's when this "Join" Kicks in

MySQL supports :

Inner Join, Left Join, Right Join, and Cross Join

 

Let's create a sample table

 
 
-- Create Member and Committees Table 
CREATE TABLE members (
    member_id INT AUTO_INCREMENT,
    name VARCHAR(100),
    PRIMARY KEY (member_id)
);

CREATE TABLE committees (
    committee_id INT AUTO_INCREMENT,
    name VARCHAR(100),
    PRIMARY KEY (committee_id)
);
-- Insert Name Data
INSERT INTO members(name)
VALUES('John'),('Jane'),('Mary'),('David'),('Amelia');

INSERT INTO committees(name)
VALUES('John'),('Mary'),('Amelia'),('Joe');
-- Query Data
SELECT * FROM members;
SELECT * FROM committees;

3. Inner Join

Inner Join clause joins two tables based on a condition which is known as a join predicate.

The inner join clause compares each row from the first table with every each row from the second table. If values from both row satisfy : inner join clause creates a new row whose column contains all the cloumns of two rows from both table. → Inner Join clause includes only matching rows from both tables

# Basic Syntax:
SELECT select_list
FROM t1                           -- table ์„ ํƒ
INNER JOIN t2 ON join_condition1  -- INNER JOIN A ON B
INNER JOIN t3 ON join_condition2
...;

๐Ÿ“Œ

์ฆ‰, row ๊ฐ’์ด ๊ฐ™์€ ์• ๋“ค์„ ํ•ฉ์ณ์„œ ์ƒˆ ํ…Œ์ด๋ธ”์„ ๊ฐ€์ ธ์˜จ๋‹ค
SELECT 
    m.member_id, 
    m.name AS member, 
    c.committee_id, 
    c.name AS committee
FROM
    members m
INNER JOIN committees c ON c.name = m.name;

์ปจ๋””์…˜์— = ์ด์“ฐ์ธ๋‹ค๋ฉด → USING() ์‚ฌ์šฉ

  • inner join
  • left join
  • right join
  • cross join

If the join condition uses equality operator(=) and column names in both tables used for matching are the same → use

USING

instead

SELECT column_list
FROM table_1
INNER JOIN table_2 USING (column_name);
SELECT 
    m.member_id, 
    m.name AS member, 
    c.committee_id, 
    c.name AS committee
FROM
    members m
INNER JOIN committees c USING(name);
SELECT 
    productCode, 
    productName, 
    textDescription
FROM
-- products t1
-- INNER JOIN productlines t2 
-- ON t1.productline = t2.productline; -> = ๋“ค์–ด๊ฐ„ ์• ๋“ค์€ using ์œผ๋กœ ๋Œ€์ฒด
products
INNER JOIN productLines USING (productline); --JOIN table using (varname)
           

JOIN Multiple tables

SELECT 
    orderNumber,
    orderDate,
    customerName,
    orderLineNumber,
    productName,
    quantityOrdered,
    priceEach
FROM
    orders
INNER JOIN orderdetails 
    USING (orderNumber)
INNER JOIN products 
    USING (productCode)
INNER JOIN customers 
    USING (customerNumber)
ORDER BY 
    orderNumber, 
    orderLineNumber;

4. Left Join

Left join selects data strating from the left table. For each row in the left table, the left join compares with every row in the right table.

→ Left join selects all data from the left table whether there are matching row exists in the right table or not

SELECT column_list 
FROM table_1 
LEFT JOIN table_2 ON join_condition;

๐Ÿ“Œ ์ฆ‰, Left Join์€ ์™ผ์ชฝ ํ…Œ์ด๋ธ”์„ ์œ ์ง€ํ•œ ์ฑ„๋กœ ์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”๊ณผ ๋น„๊ต (์˜ค๋ฅธ์ชฝ์— ๊ฐ’์ด ์—†์œผ๋ฉด null)

SELECT 
    m.member_id, 
    m.name AS member, 
    c.committee_id, 
    c.name AS committee
FROM
    members m
LEFT JOIN committees c USING(name);

5. Right Join

The right join clause is similar to the left join clause except that the treatment of left and right tables is reversed. The right join starts selecting data from the right table instead of the left table.

# Syntax
SELECT column_list 
FROM table_1 
RIGHT JOIN table_2 ON join_condition;

๐Ÿ“Œ ์ฆ‰, Right Join์€ ์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”์„ ์œ ์ง€ํ•œ ์ฑ„๋กœ ์™ผ์ชฝ ํ…Œ์ด๋ธ”๊ณผ ๋น„๊ต (์™ผ์ชฝ์— ๊ฐ’์ด ์—†์œผ๋ฉด null)

Committee(์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”)์€ ์ „๋ถ€ ์กด์žฌ (๋น„๊ต ๊ธฐ์ค€)

SELECT 
    m.member_id, 
    m.name AS member, 
    c.committee_id, 
    c.name AS committee
FROM
    members m
RIGHT JOIN committees c USING(name); -- ==> committees c on c.name = m.name

6. Cross Join

Unlike the inner join, left join, and right join, the cross join clause does not have a join condition.

The cross join makes a Cartesian product of rows from the joined tables. The cross join combines each row from the first table with every row from the right table to make the result set.

์ฒซ๋ฒˆ์งธ ํ…Œ์ด๋ธ”์ด n rows, ๋‘๋ฒˆ์งธ ํ…Œ์ด๋ธ”์ด m rows๊ฐ€ ์žˆ์—ˆ๋‹ค๋ฉด, cross join์€ ์ด nxm rows ๋ฅผ returnํ•œ๋‹ค

# syntax
SELECT select_list
FROM table_1
CROSS JOIN table_2;
SELECT 
    m.member_id, 
    m.name AS member, 
    c.committee_id, 
    c.name AS committee
FROM
    members m
CROSS JOIN committees c;

7. Self-join

๐Ÿ“Œ
you must use table aliases to not repeat the same table name twice in a single query.

There is a special case that you need to join a table to itself → The self join is often used to query hierarchical data or to compare a row with other rows within the same table.

SELF JOIN USING INNER JOIN

 
 

๊ฐ™์€ ํ…Œ์ด๋ธ” ๋‚ด์—์„œ, Manager๋‹น ๋ถ€ํ•˜ ๋ฆฌ์ŠคํŠธ ๋ฝ‘์•„๋‚ด๊ธฐ

SELECT 
    CONCAT(m.lastName, ', ', m.firstName) AS Manager,
    CONCAT(e.lastName, ', ', e.firstName) AS 'Direct report'
FROM
    employees e
INNER JOIN employees m ON 
    m.employeeNumber = e.reportsTo
ORDER BY 
    Manager;

Self Join using Left join

SELECT
			INFULL(CONCAT(m.lastname,', ',m.first_name), 'Top Manager') AS 'Manager',
			CONCAT(e.lastname,', ',e.first_name) AS 'Direct Report'
FROM employees e
LEFT JOIN employees m --์™ผ์ชฝ์— ์žˆ์„ ๊ธฐ์ค€์ : managers
 on m.employeeNumber = e.reportsto
ORDER BY mangager DESC;

Self join to compare successive rows

In this example, the table customers is joined to itself using the following join conditions:

  • c1.city = c2.city makes sure that both customers have the same city.
  • c.customerName > c2.customerName ensures that no same customer is included.
SELECT 
    c1.city, 
    c1.customerName, 
    c2.customerName
FROM
    customers c1
INNER JOIN customers c2 ON 
    c1.city = c2.city
    AND c1.customername > c2.customerName
ORDER BY 
    c1.city;

<5> Grouping Data

1. Group By

๐Ÿ“Œ
Use the GROUP BY clause to group rows into subgroups.
# Syntax: 
SELECT  c1, c2,..., cn, aggregate_function(ci)
FROM    table
WHERE   where_conditions
GROUP BY c1 , c2,...,cn;

Simple Group By Example

SELECT status
FROM   orders
GROUP BY status;
 

GROUP BY๋ฅผ ์“ฐ์ง€ ์•Š๊ณ , SELECT DISTINCT status ๋ฅผ ์จ๋„ ์œ„์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค

Use Group by with aggregate functions

SELECT 
    status, COUNT(*)
FROM
    orders
GROUP BY status;
 
 
 

์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ํ…Œ์ด๋ธ”์—์„œ status: order quantities ๊ฐ€์ ธ์˜ค๊ธฐ

SELECT 
    status, 
    SUM(quantityOrdered * priceEach) AS amount --quantityOrdered๋ž‘ priceEach๋Š” ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ
FROM
    orders --from: ํ˜„์žฌ ํ…Œ์ด๋ธ”
INNER JOIN orderdetails --inner join : ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”
    USING (orderNumber) --using :ํ˜„์žฌ ํ…Œ์ด๋ธ”๊ณผ์˜ ๊ณตํ†ต ์š”์†Œ -> order number
GROUP BY  --group by: status๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌถ์„ ๊ฑฐ์•ผ
    status;

Using Group by with expression

SELECT 
    YEAR(orderDate) AS year,
    SUM(quantityOrdered * priceEach) AS total
FROM
    orders -- ํ˜„์žฌ ํ…Œ์ด๋ธ”
INNER JOIN orderdetails -- inner join : ํƒ€ ํ…Œ์ด๋ธ”
    USING (orderNumber) -- using: ๊ณตํ†ต ๋ณ€์ˆ˜
WHERE
    status = 'Shipped'
GROUP BY 
    YEAR(orderDate);

Group by with Having clause

Having: select the total sales of the year after 200

SELECT 
    YEAR(orderDate) AS year,
    SUM(quantityOrdered * priceEach) AS total
FROM
    orders
INNER JOIN orderdetails 
    USING (orderNumber)
WHERE
    status = 'Shipped'
GROUP BY 
    year
HAVING 
    year > 2003;

Group By v.s. Distinct

If you use the GROUP BY clause in the SELECT statement without using aggregate functions, the GROUP BY clause behaves like the DISTINCT clause.

  1. Group by Clause:
SELECT 
    state
FROM
    customers
GROUP BY state;
 
  1. Distinct Clause:
SELECT DISTINCT
    state
FROM
    customers;
 

Only Difference is , GROUP BY: Sort, DISTINCT : x sort

2. Having

๐Ÿ“Œ
Use the MySQL HAVING clause with the GROUP BY clause to specify a filter condition for groups of rows or aggregates.

The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates.

The HAVING clause is often used with the GROUP BY clause to filter groups

based on a specified condition. If you omit the GROUP BY clause, the HAVING clause behaves like the WHERE clause.

SELECT 
    select_list
FROM 
    table_name
WHERE 
    search_condition
GROUP BY 
    group_by_expression
HAVING 
    group_condition;

์œ„์— group by ์—์„œ ์“ฐ์ธ ์˜ˆ์‹œ ์ฐธ๊ณ  (Having year>2003)

3. Roll up

Generate multiple grouping sets considering a hierarchy between columns specified in the GROUP BY clause.

SELECT 
    select_list
FROM 
    table_name
GROUP BY
    c1, c2, c3 WITH ROLLUP;

UNION ALL

If you want to generate two or more grouping sets together in one query, you may use the UNION ALL operator:

SELECT 
    productline, 
    SUM(orderValue) totalOrderValue
FROM
    sales
GROUP BY 
    productline 
UNION ALL
SELECT 
    NULL, 
    SUM(orderValue) totalOrderValue
FROM
    sales;

Because the UNION ALL requires all queries to have the same number of columns, NULL is is added in the select list of the second query to fulfill this requirement.

The NULL in the productLine column identifies the grand total super-aggregate line.

This query is able to generate the total order values by product lines and also the grand total row. However, it has two problems:

  1. The query is quite lengthy.
  1. The performance of the query may not be good since the database engine has to internally execute two separate queries and combine the result sets into one.

To fix these issues, you can use the ROLLUP clause.

The ROLLUP clause is an extension of the GROUP BY clause with the following syntax:

→ Fixed Code

SELECT 
    productLine, 
    SUM(orderValue) totalOrderValue
FROM
    sales
GROUP BY 
    productline WITH ROLLUP;
 
SELECT 
    productLine, 
    orderYear,
    SUM(orderValue) totalOrderValue
FROM
    sales
GROUP BY 
    productline, 
    orderYear 
WITH ROLLUP;

→ GROUP BY ์— ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด order year ๋ณ„๋กœ productline์˜ ํ•ฉ๊ณ„๋ฅผ ๋ณด์—ฌ์ฃผ๊ฒŒ ๋œ๋‹ค

 

Grouping() Function

To check whether NULL in the result set represents the subtotals or grand totals, you use the GROUPING() function → returns 1 when NULL occurs in a supper-aggregate row, otherwise, it returns 0.

SELECT 
    IF(GROUPING(orderYear),
        'All Years',
        orderYear) orderYear,
    IF(GROUPING(productLine),
        'All Product Lines',
        productLine) productLine,
    SUM(orderValue) totalOrderValue
FROM
    sales
GROUP BY 
    orderYear , 
    productline 
WITH ROLLUP;

<6> Sub Queries

1. Subquery

Subquery is a query nested within another query such as SELECT, INSERT, UPDATE or DELETE. Also, a subquery can be nested within another subquery.

→ day3 ์ˆ™์ œ ๋•Œ, where ์•ˆ์— ์ง‘์–ด๋„ฃ์€๊ฒŒ subquery์•ผ

Subquery in Where clause

You can use comparison operators e.g., =, >, < to compare a single value returned by the subquery with the expression in the WHERE clause.

 
 

Scott์˜ ์ง๋ฌด์™€ ๊ฐ™์€ ์‚ฌ๋žŒ์˜ ์ด๋ฆ„, ๋ถ€์„œ๋ช…, ๊ธ‰์—ฌ, ์ง๋ฌด๋ฅผ ๊ฒ€์ƒ‰ํ•˜์‹œ์˜ค

select 
		e.ename ์ด๋ฆ„,    -- ์š”๊ตฌํ•˜๋Š” columns
    d.dname ๋ถ€์„œ๋ช…,
    e.sal	๊ธ‰์—ฌ,
    e.job	์ง๋ฌด
from emp e 				   -- ๊ธฐ์ค€์ด ๋˜๋Š” ํ…Œ์ด๋ธ”
inner join dept d using(deptno) -- table 2 using(๊ณตํ†ตvar)
#subquery : e.job ์ด ์ด๋ฆ„์ด scott์ธ ์‚ฌ๋žŒ์˜ job๊ณผ ์ผ์น˜ํ•ด์•ผํ•œ๋‹ค
where e.job = (		   
		select job
    from emp
    where ename='scott' 
);

์ „์ฒด ์‚ฌ์›์˜ ํ‰๊ท ๊ธ‰์—ฌ๋ณด๋‹ค ๊ธ‰์—ฌ๊ฐ€ ๋งŽ์€ ์‚ฌ์›์˜ ์‚ฌ์›๋ฒˆํ˜ธ, ์ด๋ฆ„, ๋ถ€์„œ๋ช…, ์ž…์‚ฌ์ผ, ์ง€์—ญ, ๊ธ‰์—ฌ๋ฅผ ๊ฒ€์ƒ‰ํ•˜์‹œ์˜ค

select 
		e.empno ์‚ฌ์›๋ฒˆํ˜ธ,
		e.ename ์ด๋ฆ„,    -- ์š”๊ตฌํ•˜๋Š” columns
        d.dname ๋ถ€์„œ๋ช…,
        e.hiredate ์ž…์‚ฌ์ผ,
        d.loc	์ง€์—ญ,
        e.sal	๊ธ‰์—ฌ
from emp e 				-- ๊ธฐ์ค€์ด ๋˜๋Š” ํ…Œ์ด๋ธ”
inner join dept d using(deptno) -- table 2 using(๊ณตํ†ตvar)
#subquery
where e.sal > (			-- ์กฐ๊ฑด: e.sal > avg(Sal) 
		select avg(sal) -- ํ‰๊ท  ๊ธ‰์—ฌ
        from emp		-- from which table?
);

Subquery with IN and NOT IN operators

If a subquery returns more than one value, you can use other operators such as IN or NOT IN operator in the WHERE clause.

  1. in

'King'์ด๋‚˜ 'James'์˜ ๊ธ‰์—ฌ์™€ ๊ฐ™์€ ์‚ฌ๋žŒ์˜ ์‚ฌ์›๋ฒˆํ˜ธ, ์ด๋ฆ„,๊ธ‰์—ฌ๋ฅผ ๊ฒ€์ƒ‰ํ•˜์‹œ์˜ค

select 
		e.empno ์‚ฌ์›๋ฒˆํ˜ธ,
		e.ename ์ด๋ฆ„,    
        e.sal	๊ธ‰์—ฌ
from emp e 		
where e.sal in ( --  ์ด๊ฒƒ๋„ in์ด๋„ค..
		select sal
        from emp
        where ename in ('king','james')
);
  1. not in

10 ๋ฒˆ ๋ถ€์„œ ์ค‘์—์„œ 30๋ฒˆ ๋ถ€์„œ์—๋Š” ์—†๋Š” ์—†๋ฌด๋ฅผ ํ•˜๋Š” ์‚ฌ์›์˜ ์‚ฌ์›๋ฒˆํ˜ธ, ์ด๋ฆ„, ๋ถ€์„œ๋ช…, ์ž…์‚ฌ์ผ, ์ง€์—ญ์„ ๊ฒ€์ƒ‰ํ•˜์‹œ์˜ค

select 
		e.empno ์‚ฌ์›๋ฒˆํ˜ธ,
		e.ename ์ด๋ฆ„,    -- ์š”๊ตฌํ•˜๋Š” columns
    d.dname ๋ถ€์„œ๋ช…,
    e.hiredate ์ž…์‚ฌ์ผ,
    d.loc	์ง€์—ญ
from emp e 		
inner join dept d using(deptno)
where e.deptno = 10 -- dept no ๊ฐ€ 10์ด๊ณ  
and 
e.job not in  	-- e.job์ด 30๋ฒˆ ๋ถ€์„œ์—๋Š” ์—†๋‹ค
(
		select job
    from emp
		where  deptno=30
);

Subquery in the from clause

When you use a subquery in the FROM clause, the result set returned from a subquery is used as a temporary table. This table is referred to as a derived table or materialized subquery.

SELECT 
    MAX(items), 
    MIN(items), 
    FLOOR(AVG(items))
FROM
    (SELECT orderNumber, COUNT(orderNumber) AS items
    FROM orderdetails
    GROUP BY orderNumber) AS lineitems;-- lineitems๋Š” derived table ์ด๋‹ค(์•„๋ž˜์ฐธ๊ณ )

Subquery in Exists and Not Exists

When a subquery is used with the EXISTS or NOT EXISTS operator, a subquery returns a Boolean value of TRUE or FALSE.

SELECT *
FROM   table_name
WHERE  EXISTS( subquery );

2. Derived Table

The term derived table and subquery is often used interchangeably.

When a stand-alone subquery is used in the FROM clause of a SELECT statement, it is also called a derived table.

๐Ÿ“Œ
Every derived table must have its own alias
# Syntax
SELECT select_list
FROM (
			 SELECT  select_list
       FROM table_1
) derived_table_name
WHERE derived_table_name.c1 > 0;

3. Exists

The EXISTS operator is a Boolean operator that returns either true or false. The EXISTS operator is often used to test for the existence of rows returned by the subquery.

# Syntax
SELECT select_list
FROM   a_table
WHERE  [NOT] EXISTS(subquery);

Exists VS In Operator

The query that uses the

EXISTS operator is much faster

than the one that uses the IN operator.

 
 

<7> Common Table Expressions

What is Common Table Expression(CTE)

A common table expression is a named temporary result set that exists only within the execution scope of a single SQL statement e.g.,SELECT, INSERT, UPDATE, or DELETE.

โœ”๏ธ Derived Table๊ณผ ๊ณตํ†ต์ : not stored as an object and last only during the execution of a query

โœ”๏ธ Derived Table๊ณผ ์ฐจ์ด์ : CTE can be self-referencing (a recursive CTE) or can be referenced multiple times in the same query. In addition, a CTE provides better readability and performance in comparison with a derived table.

Syntax

WITH cte_name (column_list) AS (
    query
) 
SELECT * FROM cte_name;

Example

 
WITH customers_in_usa AS (-- cte:customers in usa
    SELECT                -- query
        customerName, state
    FROM
        customers
    WHERE
        country = 'USA'
) SELECT                  -- select something
    customerName          -- from cte table
 FROM
    customers_in_usa
 WHERE
    state = 'CA'
 ORDER BY customerName;

With clause

There are some contexts that you can use the WITH clause to make common table expressions:

  1. WITH clause can be used at the beginning of SELECT, UPDATE, and DELETE statements:
WITH ... SELECT ...
WITH ... UPDATE ...
WITH ... DELETE ...
  1. WITH clause can be used at the beginning of a subquery or a derived table subquery:
SELECT ... WHERE id IN (WITH ... SELECT ...);
SELECT * FROM (WITH ... SELECT ...) AS derived_table;
  1. Third, a WITH clause can be used immediately preceding SELECTof the statements that include a SELECTclause
CREATE TABLE ... WITH ... SELECT ...
CREATE VIEW ... WITH ... SELECT ...
INSERT ... WITH ... SELECT ...
REPLACE ... WITH ... SELECT ...
DECLARE CURSOR ... WITH ... SELECT ...
EXPLAIN ... WITH ... SELECT ...

<8>Set Operators

Set operators- Union, Union all, Intersect, and Minus operators

1. Union and Union All

UNION operator: combine two or more result sets from multiple SELECT statements into a single result set. ์ฆ‰, ๊ต์ง‘ํ•ฉ์„ ๊ตฌํ•ด์„œ ํ•ฉ์น˜๋Š” ๊ฒƒ

Union Operator

Combine two or more result sets of queries into a single result set

๐Ÿ“Œ ๊ทœ์น™

  • First, the number and the orders of columns that appear in all SELECT statements must be the same.→ ์ˆœ์„œ์™€ column #๊ฐ€ ๊ฐ™์•„์•ผ๋งŒ union์„ ์“ธ ์ˆ˜ ์žˆ์–ด์„œ, ๋‹ค๋ฅด๋ฉด null์ถ”๊ฐ€ํ•ด์ค˜์•ผํ•จ !
  • Second, the data types of columns must be the same or compatible.
# Syntax:
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
...

 

Union operator์€ DISTINCT ์—†์ด๋„ ์ค‘๋ณต๋˜๋Š” rows๋ฅผ ์ž๋™์œผ๋กœ ์ œ๊ฑฐํ•œ๋‹ค

DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;

CREATE TABLE t1 (
    id INT PRIMARY KEY
);

CREATE TABLE t2 (
    id INT PRIMARY KEY
);

INSERT INTO t1 VALUES (1),(2),(3); 
INSERT INTO t2 VALUES (2),(3),(4); --2 ๊ฐ€ ์ค‘๋ณต๋œ๋‹ค

#--------------------------------Union--------------------------------#
SELECT id
FROM t1
UNION
SELECT id
FROM t2;
#---------------------------------Result---------------------------------#
+----+
| id |
+----+
|  1 |
|  2 |  --> 2๋Š” ํ•œ๋ฒˆ๋งŒ ๋“ค์–ด๊ฐ„๋‹ค
|  3 |
|  4 |

Union VS Join

  1. Join Combines result sets horizontally
  1. Union Combines result sets vertically

Alias

Example:

→ Employees ์™€ Customer์˜ ์ด๋ฆ„ ๋ช…๋‹จ ํ•ฉ์น˜๊ธฐ(union)

SELECT 
			firstName,
			lastName
FROM  employees
Union
SELECT
			contactFirstName,
			contactLastName
FROM
			Customers
 

→Concat์„ ์ด์šฉํ•ด์„œ ํ…Œ์ด๋ธ” ํ•ฉ์น˜๊ธฐ

SELECT 
    CONCAT(firstName,' ',lastName) fullname
FROM
    employees 
UNION SELECT 
    CONCAT(contactFirstName,' ',contactLastName)
FROM
    customers;
 

Order By

Union์˜ result set์„ ์ •๋ ฌํ•˜๊ณ  ์‹ถ์œผ๋ฉด, SELECT์ ˆ์˜ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— ์ถ”๊ฐ€ํ•œ๋‹ค

→ ๋งŒ์ผ Order By๋ฅผ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์œผ๋ฉด ์ •๋ ฌ์ด ์ œ๋Œ€๋กœ ๋˜์ง€ ์•Š๋Š”๋‹ค !

SELECT 
    concat(firstName,' ',lastName) fullname
FROM
    employees 
UNION SELECT 
    concat(contactFirstName,' ',contactLastName)
FROM
    customers
ORDER BY fullname;

 

ํ‘œ์— column์„ ์ถ”๊ฐ€ํ•˜์—ฌ, employee์ธ์ง€ customer์ธ์ง€ ํ‘œ์‹œ

SELECT 
    CONCAT(firstName, ' ', lastName) fullname, 
    'Employee' as contactType
FROM
    employees 
UNION SELECT 
    CONCAT(contactFirstName, ' ', contactLastName),
    'Customer' as contactType
FROM
    customers
ORDER BY 
    fullname
 

2. Intersect

MySQL does not support the INTERSECT operator

MySQL์€ intersect operator๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š์ง€๋งŒ, join์ ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋น„์Šทํ•œ ํšจ๊ณผ๋ฅผ ๋‚ผ ์ˆ˜์žˆ๋‹ค

๊ทœ์น™

  1. The order and the number of columns in the select list of the queries must be the same.
  1. The data types of the corresponding columns must be compatible.
(SELECT column_list 
FROM table_1)
INTERSECT
(SELECT column_list
FROM table_2);

Emulating INTERSECT in MySQL

MySQL does not support intersect operator, but you can emulate it

Set up Tables

CREATE TABLE t1 (
    id INT PRIMARY KEY
);

CREATE TABLE t2 LIKE t1;

INSERT INTO t1(id) VALUES(1),(2),(3);
INSERT INTO t2(id) VALUES(2),(3),(4);

SELECT id FROM t1;-- get query from t1
SELECT id FROM t2;-- get query from t2
  1. Emulate Intersect using DISTINCT and INNER JOIN
SELECT DISTINCT -- ์ค‘๋ณต ์ œ๊ฑฐ
   id 
FROM t1
   INNER JOIN t2 USING(id); -- ํ…Œ์ด๋ธ” ํ•ฉ์ฒด
  1. Emulate Intersect using IN and Subquery
SELECT DISTINCT id -- ์ฆ๋ฒ… ์ œ๊ฑฐ
FROM t1
WHERE id IN (SELECT id FROM t2); -- range: t1 ~ t2์•ˆ์˜ ๋ชจ๋“  ๋‚ด์šฉ์—์„œ

3. Minus

MySQL does not support the MINUS operator

Minus operator

The MINUS compares the results of two queries and returns distinct rows from the result set of the first query that does not appear in the result set of the second query.

๊ทœ์น™

  • The number and order of columns in both select_list1 and select_list2 must be the same.
  • The data types of the corresponding columns in both queries must be compatible.
SELECT select_list1 
FROM table_name1
MINUS 
SELECT select_list2 
FROM table_name2;

์•ž์„œ ๋งŒ๋“  t1, t2 ํ…Œ์ด๋ธ” ์„ ์˜ˆ์‹œ๋กœ, t1- t2 = 1์ด ๋œ๋‹ค

Emulate Minus Operator

-- Syntax: 
SELECT 
    select_list
FROM 
    table1
LEFT JOIN table2 
    ON join_predicate
WHERE 
    table2.column_name IS NULL; -- table2์˜ ๊ฐ’์ด ์žˆ๊ฑฐ๋‚˜ ์—†์„ ๋•Œ๋Š” minus๊ฐ€ ์•„๋‹˜. nulll์ผ๋•Œ๋งŒ ๊ฐ€์ ธ์˜ด

์œ„ syntax๋ฅผ ์ ์šฉํ•ด๋ณด๋ฉด,

SELECT            -- ์ถ”์ถœํ•  ๋ฐ์ดํ„ฐ
    id
FROM              -- t1 - t2 ์ค‘ t1
    t1
LEFT JOIN         -- t2์˜ id๋ฅผ ํ•ฉ์น ๊ฒƒ์ด๋‹ค
    t2 USING (id)
WHERE             -- t2์˜ id๊ฐ€ null์ธ ๊ฐ’๋งŒ ์ถ”๊ฐ€ํ•œ๋‹ค. ์žˆ๊ฑฐ๋‚˜ ์—†์œผ๋ฉด minus๊ฐ€์•„๋‹˜
    t2.id IS NULL;

<9> Modifying data in MySQL

1. Insert

INSERT statement allows you to insert one or more rows into a table.

INSERT INTO table(c1,c2,...)
VALUES (v1,v2,...);

Example

Create a table

CREATE TABLE IF NOT EXISTS tast(
		task_id INT AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    start_date DATE,
    due_date DATE,
    priority TINYINT NOT NULL DEFAULT 3, --default 3
    description TEXT,
    PRIMARY KEY (task_id)
);

Insert

INSERT INTO tasks(title,priority) -- ํ…Œ์ด๋ธ” ์ถ”๊ฐ€ tablename(col,col)
VALUES('Learn MySQL INSERT Statement',1);-- Values(val1, val2);

Insert using default value

์œ„ ํ…Œ์ด๋ธ”์—์„œ priority์˜ ๋””ํดํŠธ ๊ฐ’์„ 3์œผ๋กœ ์ง€์ •ํ–ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์•„๋ž˜๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค

INSERT INTO tasks(title,priority)
VALUES('Understanding DEFAULT keyword in INSERT statement',DEFAULT);

Insert Date ('YYYY-MM-DD' format)

  1. ์ง์ ‘ ์ž…๋ ฅ : YYYY-MM-DDํ˜•ํƒœ
  1. CURRENT_DATE() ์‚ฌ์šฉ
# ๋ฐฉ๋ฒ• 1:
INSERT INTO tasks(title, start_date, due_date)
VALUES('Insert date into table','2018-01-09','2018-09-15');
# ๋ฐฉ๋ฒ• 2:
INSERT INTO tasks(title,start_date,due_date)
VALUES('Use current date for the task',CURRENT_DATE(),CURRENT_DATE())

2. Insert Multiple Rows

# Syntax: 
INSERT INTO table_name (column_list)
VALUES
	(value_list_1),
	(value_list_2),...
	(value_list_n);

Insert Multiple rows

value์— multiple ๊ฐ’๋“ค์„ ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค

INSERT INTO tasks(title, priority)
VALUES
	('My first task', 1),
	('It is the second task',2),
	('This is the third task of the week',3);

3. Insert into Select

# Syntax:
INSERT INTO table_name(column_list)
SELECT 
   select_list 
FROM 
   another_table
WHERE
   condition;

 

Example

Create a table:

CREATE TABLE suppliers (
    supplierNumber INT AUTO_INCREMENT,
    supplierName VARCHAR(50) NOT NULL,
    phone VARCHAR(50),
    addressLine1 VARCHAR(50),
    addressLine2 VARCHAR(50),
    city VARCHAR(50),
    state VARCHAR(50),
    postalCode VARCHAR(50),
    country VARCHAR(50),
    customerNumber INT,
    PRIMARY KEY (supplierNumber)
);

 

Check Table - customers living in CA

SELECT 
    customerNumber,
    customerName,
    phone,
    addressLine1,
    addressLine2,
    city,
    state,
    postalCode,
    country
FROM
    customers
WHERE
    country = 'USA' AND 
    state = 'CA';
  1. Use Insert into... Select
INSERT INTO suppliers ( -- select์ ˆ ์œ„์— ์ถ”๊ฐ€
    supplierName, 
    phone, 
    addressLine1,
    addressLine2,
    city,
    state,
    postalCode,
    country,
    customerNumber
)
SELECT 
    customerName,
    phone,
    addressLine1,
    addressLine2,
    city,
    state ,
    postalCode,
    country,
    customerNumber
FROM 
    customers
WHERE 
    country = 'USA' AND 
    state = 'CA';

Using SELECT statement in the values list

Example

Create table

CREATE TABLE stats (
    totalProduct INT,
    totalCustomer INT,
    totalOrder INT
);

Inswert Values

INSERT INTO stats(totalProduct, totalCustomer, totalOrder)
VALUES(
	(SELECT COUNT(*) FROM products),
	(SELECT COUNT(*) FROM customers),
	(SELECT COUNT(*) FROM orders)
);

4. Insert Ignore

Insert ์ ˆ์„ ํ†ตํ•ด rows๋ฅผ ๋”ํ• ๋•Œ์—๋Š”, ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ์•„๋ฌด row ๋„ ์ƒ์„ฑ๋˜์ง€ ์•Š๋Š”๋‹ค → insert ignore์„ ์‚ฌ์šฉํ•˜๋ฉด ์—๋Ÿฌ๋ฅผ ๋ฌด์‹œํ•˜๊ณ  ์ •์ƒ์ ์ธ ๊ฐ’์„ ๊ฐ€์ง„ row๋“ค์€ ์ถ”๊ฐ€๋œ๋‹ค

#Syntax
INSERT IGNORE INTO table(column_list)
VALUES( value_list),
      ( value_list),
      ...

 

Example

# Create Table
CREATE TABLE subscribers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(50) NOT NULL UNIQUE -- email ์ค‘๋ณต ๋ถˆ๊ฐ€
);
# Insert Value
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com');

# Insert Values
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com'),  -- email์ด ์ค‘๋ณต ๋ถˆ๊ฐ€์ธ๋ฐ, ๊ฐ™์€ ๊ฐ’์„ ์ถ”๊ฐ€ ์‹œ ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค
      ('jane.smith@ibm.com');

Insert Value ์‹œ ์˜ค๋ฅ˜ : Error Code: 1062. Duplicate entry 'john.doe@gmail.com' for key 'email'

์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๊ธฐ ๋•Œ๋ฌธ์—, Jane.smith@ibm.com๋„ ์ถ”๊ฐ€๋˜์ง€ ์•Š๋Š”๋‹ค

ํ•˜์ง€๋งŒ, insert ignore์„ ์‚ฌ์šฉํ•˜๋ฉด janem์˜ ์ด๋ฉ”์ผ์€ ์ถ”๊ฐ€๋œ๋‹ค:

INSERT IGNORE INTO subscribers(email)
VALUES('john.doe@gmail.com'), -- ์ค‘๋ณต ๊ฐ’ -> warning์ด ์ƒ๊ธด๋‹ค. SHOW WARNGINGS;
      ('jane.smith@ibm.com');

Strict and Insert Ingore

Strict Mode on → insert ingore ์‚ฌ์šฉ ์‹œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด, it tries to adjust the values to make them valid before adding the value to the table.

 

Example

CREATE TABLE tokens(s varchar(6)); -- create table
INSERT INTO tokens VALUES('abcdefg'); -- insert rows->error:7๊ธ€์ž์ž„..

 

# Insert Ignore Into
INSERT IGNORE INTO toekns VALUES('abcdefg'); -- g๋Š” ์•Œ์•„์„œ drop
 

 

 

 


ํŒจ์ŠคํŠธ์บ ํผ์Šค ํ™˜๊ธ‰ ์ฑŒ๋ฆฐ์ง€ ๋ฐ”๋กœ๊ฐ€๊ธฐ๐Ÿ‘‰ https://bit.ly/3FVdhDa

 

์ˆ˜๊ฐ•๋ฃŒ 100% ํ™˜๊ธ‰ ์ฑŒ๋ฆฐ์ง€ | ํŒจ์ŠคํŠธ์บ ํผ์Šค

๋”ฑ 5์ผ๊ฐ„ ์ง„ํ–‰๋˜๋Š” ํ™˜๊ธ‰์ฑŒ๋ฆฐ์ง€๋กœ ์ˆ˜๊ฐ•๋ฃŒ 100% ํ™˜๊ธ‰๋ฐ›์œผ์„ธ์š”! ๋” ๋Šฆ๊ธฐ์ „์— ์ž๊ธฐ๊ณ„๋ฐœ ๋ง‰์ฐจ ํƒ‘์Šน!

fastcampus.co.kr

๋ณธ ํฌ์ŠคํŒ…์€ ํŒจ์ŠคํŠธ์บ ํผ์Šค ํ™˜๊ธ‰ ์ฑŒ๋ฆฐ์ง€ ์ฐธ์—ฌ๋ฅผ ์œ„ํ•ด ์ž‘์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•

'๐Ÿ““ STUDY > FASTCAMPUS' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 9์ผ์ฐจ  (2) 2021.11.09
ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 8์ผ์ฐจ  (0) 2021.11.08
ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 6์ผ์ฐจ  (0) 2021.11.06
ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 5์ผ์ฐจ  (0) 2021.11.05
ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 4์ผ์ฐจ  (0) 2021.11.04
    '๐Ÿ““ STUDY/FASTCAMPUS' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€
    • ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 9์ผ์ฐจ
    • ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 8์ผ์ฐจ
    • ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 6์ผ์ฐจ
    • ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ฑŒ๋ฆฐ์ง€ 5์ผ์ฐจ
    JuneBee
    JuneBee
    โ‚Šหš.๐ŸŽง๐Ÿ““ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ ๐“‚ƒ๐Ÿ–Š

    ํ‹ฐ์Šคํ† ๋ฆฌํˆด๋ฐ”