ฮะฮ่า- จำ Sql command กันไม่ได้ละสิ ไม่เป็นไร เรารวบรวมมาไว้แน้วววววววว

#Query

SELECT * FROM <table> WHERE <column>

SELECT * FROM <table> 
	WHERE <column> LIKE(OR NOT LIKE) '%...%'
SELECT * FROM <table> 
	WHERE <column> LIKE(OR NOT LIKE) '_...'
% คำไหนเท่าไหร่ก็ได้
_ ตัวนี้ตัวเดียวแต่เป็นอะไรก็ได้

#if

SELECT 
  country,
  CASE
    WHEN country IN ('Canada', 'USA') THEN 'America'
    WHEN country IN ('Belgium', 'France', 'Italy') THEN 'Europe'
    ELSE 'Other'
  END AS region
FROM customers

# if null

SELECT COALESCE(<column check null>, <column relace null>) AS <name>
	FROM <table>

#Join

SELECT * 
	FROM <tableA> AS A
	LEFT JOIN(OR JOIN) <tableB> AS B
	ON A.<primary key> = B.<foreign key>
	
SELECT * 
	FROM <tableA>,<tableB> 
	WHERE <tableA>.<primary key> = <tableB>.<foriegn key>


#Random

SELECT <column>,RANDOM() FROM <table>
	ORDER BY RAMDOM()

#Aggregate

SELECT 
	AVG(<column>),
	SUM(<column>),
	MIN(<column>),
	MAX(<column>),
	COUNT(<column>)
	FROM <table>;

#Count Distinct

SELECT DISTINCT <column> FROM <table>;

#Group

SELECT <column> FROM <table> GROUP BY <column>;

#Having

SELECT <column>,
			COUNT(*)
	FROM <table>
	WHERE <table>
	HAVING COUNT(*) >= 100;

#Order By

SELECT <column> FROM <table> ORDER BY <column> DESC;

#View(virtual table)

CREATE VIEW <view_name> AS 
SELECT ... FROM ... WHERE ...
DROP VIEW <view_name>

#UNION(append)

SELECT .... FROM ... WHERE...
UNION ALL(or UNION)
SELECT .... FROM ... WHERE...
  #UNION ALL => allow duplicate
  #UNION => no duplicate

#With clause ใช้ในการประกาศตัวแปรใน SQL

WITH <name> AS (SELECT ... FROM ... WHERE ...)

Trending