2 minutes
SQL Cheat Sheet
Insert
INSERT INTO Student (SId, Sname, Sage, Ssex)
VALUES ('01', 'John', 1990-01-01, 'M')
Update
UPDATE Student Ssex = 'F', Sname = 'Alison'
WHERE SId = '01'
Delete
DELETE FROM Student
WHERE SId = '01'
Select
SELECT * FROM Student;
SELECT SId, Sname FROM Student;
SELECT SC.SId, Student.Sname FROM SC, Student WHERE SC.SId = Student.SId;
Where
SELECT * FROM Student WHERE SId = '01' AND Sname = 'Alex';
SELECT * FROM Student WHERE SId <> '01';
Order By (Sort)
SELECT * FROM Student ORDER BY SId ASC;
SELECT * FROM Student ORDER BY SId DESC;
Concatenate Columns
SELECT CONCAT(First_Name, ' ', Last_Name) AS 'Name' FROM Student;
Select Distinct Rows
SELECT DISTINCT SId FROM Student;
Between (Select Range)
SELECT * FROM SC WHERE score BETWEEN 60 AND 90;
Like (Searching)
SELECT * FROM Student WHERE Sname LIKE 'A%';
SELECT * FROM Student WHERE Sname LIKE 'Alex%';
SELECT * FROM Student WHERE Sname LIKE '%x';
SELECT * FROM Student WHERE Sname LIKE '%e%';
Not Like
SELECT * FROM Student WHERE Sname NOT LIKE 'A%';
IN
SELECT * FROM Student WHERE Sname IN ('Alex', 'Bert');
Left Join
SELECT Student.Sname, SC.Cname, SC.score
FROM Student
LEFT JOIN SC
ON SC.SId = Student.SId
Aggregate Functions
SELECT COUNT(SId) FROM Student;
SELECT MAX(score) FROM SC;
SELECT MIN(score) FROM SC;
SELECT SUM(score) FROM SC;
SELECT AVG(score) FROM SC;
Partition By
SELECT age, count(age) OVER (PARTITION BY age) AS number FROM users
Group By
SELECT Ssex, count(SId) FROM Student GROUP BY Ssex;
SELECT Ssex, count(SId) FROM Student WHERE Sname NOT LIKE 'A%' GROUP BY Ssex;
SELECT Ssex, count(SId) FROM Student GROUP BY Ssex HAVING count(SId) >=2;
Cast
SELECT CAST(25.65 AS int);
SELECT CAST(25 AS char(4));
SELECT CAST('2017-08-25' AS datetime);
Convert
SELECT CONVERT(int, 25.65);
SELECT CONVERT(char(4), 25);
SELECT CONVERT(datetime, '2017-08-25');