5. Count the Filtered Rows
SELECT COUNT(*) FROM users WHERE age>18;
6. Sort Rows Based on Criteria
SELECT * FROM Users ORDER BY userId ASC/DESC;
Note: You can use ASC for Ascending Order or DESC for descending order. If nothing is specified, sorting is done in Ascending order(ASC).
7. Retrieve Limited Rows
SELECT * FROM Users WHERE country=’india’ LIMIT 20;
8. Retrieve and Skip/Offset Rows
SELECT * FROM Users ORDER BY userId OFFSET 10 ROWS;
9. Get Average, Sum, Max, Min, etc. of Results
SELECT AVG(age) FROM USERS;
10. Get all Values from two Tables
SELECT * FROM Users INNER JOIN Wallets ON Users.walletId = Wallets.walletId;
Note:- We can use any type of join that we want. The condition via which we want to join the tables needs to be specified after the ON keyword.
11. Get selected values from two tables
SELECT us.userId,us.name,wall.walletId,wall.balance
FROM Users AS us
INNER JOIN Wallets AS wall
Note: - We use the AS keyword to give an alias to a table to make our SELECT statement shorter. We can even eliminate the AS keyword in this case and simply write the Alias after the
table name.
SQL Cheatsheet for INSERT Queries
1. Insert All Values in Order a Table
INSERT INTO Users VALUES(‘Kanak Infosystems’,’
[email protected]’,9876543210);
2. Insert Selected Values in a Table
INSERT INTO Users(userName,email) VALUES(‘Kanak Infosystems’,’
[email protected]’);
3. Insert Multiple Rows
INSERT INTO User(userName) VALUES
(‘user1’),
(‘user2’);
Note: - We separate each row with a pair of brackets followed by a comma.
SQL Cheatsheet for TABLE Queries
1. Create a New Table
CREATE TABLE Users(
id INT PRIMARY KEY,
userName VARCHAR(50),
age INT DEFAULT 10
);
2. Delete a Table
DROP TABLE Users;
3. Remove all Values from a Table
TRUNCATE TABLE Users;
4. Add a Column to the Table
ALTER TABLE Users ADD COLUMN country VARCHAR(20);
5. Remove a Column from a Table
ALTER TABLE Users DROP COLUMN country;
6. Rename a Table
ALTER TABLE Users RENAME TO Customers;
7. Rename a Column
ALTER TABLE Users RENAME userName to name;
SQL Cheat Sheet for UPDATE/DELETE Queries
1. Update Column Value for all Rows
UPDATE Users SET country=’india’;
2. Update Column Value for Selected Rows
UPDATE Users SET isEligible=’true’ WHERE age>=18;