SQL Notes Summary & Practice Questions
Basic SQL Commands
SELECT - retrieve data
INSERT - add new data
UPDATE - modify existing data
DELETE - remove data
Example: SELECT * FROM customers;
SELECT name FROM customers WHERE age > 30;
ORDER BY and WHERE
SELECT * FROM customers WHERE country = 'India' AND age > 18 ORDER BY name;
SELECT DISTINCT
SELECT DISTINCT column_name FROM table;
WHERE Clause with Operators
SELECT * FROM table WHERE age > 30 AND country = 'India';
SELECT * FROM table WHERE NOT country = 'USA';
ORDER BY
SELECT * FROM customers ORDER BY name ASC;
Aggregate Functions
COUNT() - Total number of entries
SUM() - Total sum
AVG() - Average value
MIN() - Minimum value
MAX() - Maximum value
Example: SELECT COUNT(*) FROM users WHERE gender = 'Male';
JOINs
INNER JOIN: SELECT * FROM A INNER JOIN B ON A.id = B.id;
LEFT JOIN: SELECT * FROM A LEFT JOIN B ON A.id = B.id;
RIGHT JOIN: SELECT * FROM A RIGHT JOIN B ON A.id = B.id;
INSERT, UPDATE, DELETE
INSERT: INSERT INTO table (col1, col2) VALUES (val1, val2);
UPDATE: UPDATE table SET column = value WHERE condition;
DELETE: DELETE FROM table WHERE condition;
CREATE, DROP, RENAME TABLE
CREATE TABLE tablename (id INT PRIMARY KEY, name VARCHAR(50));
DROP TABLE tablename;
RENAME TABLE old_name TO new_name;
GROUP BY and HAVING
SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000;
Practice Questions
1. What SQL command is used to retrieve data from a table?
2. Write a query to select unique countries from a 'customers' table.
3. Which function returns the number of rows in a result set?
4. How do you sort the result set in descending order by a column named 'salary'?
5. Write a query to find all employees with salary > 50000 using HAVING.
6. What is the difference between INNER JOIN and LEFT JOIN?
7. Provide the syntax to add a new record to a 'students' table.
8. Write a query to update the age of a customer whose name is 'John'.
9. How do you delete all records from the 'orders' table where quantity = 0?
10. What does the following query do?
SELECT AVG(salary) FROM employees WHERE department = 'HR';