SQL Commands: Querying |
What |
How |
Example(s) |
All columns |
SELECT * FROM table; |
SELECT * FROM Students; |
Some columns |
SELECT column1,column2,...
FROM table; |
SELECT LastName, FirstName FROM Students;
|
Some rows/ columns |
SELECT column1,column2,...
FROM table
[WHERE condition(s)]; |
SELECT LastName,FirstName
FROM Students
WHERE StudentID LIKE '%123%'; |
No Repeats |
SELECT [DISTINCT] column(s)
FROM table;
|
SELECT DISTINCT LastName
FROM Students;
|
Ordering |
SELECT column1,column2,...
FROM table
[ORDER BY column(s) [DESC]];
|
SELECT LastName,FirstName
FROM Students
ORDER BY LastName, FirstName DESC;
|
Column Aliases |
SELECT column1 [AS alias1],
column2 [AS alias2], ...
FROM table1;
|
SELECT LastName,FirstName AS First
FROM Students;
|
Grouping |
SELECT column1,column2,...
FROM table
[GROUP BY column(s)];
|
SELECT LastName,COUNT(*)
FROM Students
GROUP BY LastName;
|
Group Filtering |
SELECT column1,column2,...
FROM table
[GROUP BY column(s)]
[HAVING condition(s)];
|
SELECT LastName,COUNT(*)
FROM Students
GROUP BY LastName
HAVING LastName like '%son';
|
Joins |
SELECT column1,column2,...
FROM table1,table2,...
[WHERE condition(s)]; |
SELECT LastName,Points
FROM Students,Assignments
WHERE AssignmentID=12 AND
Students.StudentID=Assignments.StudentID;
|
Table Aliases |
SELECT column1,column2,...
FROM table1 [alias1],
table2 [alias2],...
[WHERE condition(s)]; |
SELECT LastName,Points
FROM Students S,Assignments A
WHERE S.StudentID=A.StudentID AND
A.AssignmentID=12; |
Everything |
SELECT [DISTINCT]
column1 [AS alias1],
column2 [AS alias2], ...
FROM table1 [alias1],
table2 [alias2],...
[WHERE condition(s)]
[GROUP BY column(s)]
[HAVING condition(s)]
[ORDER BY column(s) [DESC]];
|
SELECT Points, COUNT(*) AS Cnt
FROM Students S,Assignments A
WHERE S.StudentID=A.StudentID AND
A.AssignmentID=12
GROUP BY Points
HAVING Points > 10
ORDER BY Cnt, Points DESC;
|