SQL Tutorial for Beginners
SQL Tutorial for Beginners
Introduction to SQL
SELECT
INSERT
UPDATE
DELETE
Constraints
PRIMARY KEY
FOREIGN KEY
UNIQUE
NOT NULL
CHECK
DEFAULT
Filtering Data
WHERE Clause
Sorting Data
ORDER BY Clause
Aggregate Functions
Grouping Data
GROUP BY Clause
HAVING Clause
Joins
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
CROSS JOIN
Subqueries
Set Operations
UNION
INTERSECT
EXCEPT
Views
Indexes
Transactions
Triggers
Window Functions
Pivot Tables
1. Introduction to SQL
To practice SQL, you need a database management system (DBMS). Here are a few
options:
MySQL: Open-source RDBMS.
Installing MySQL:
Example:
sql
Copy
INSERT
Example:
sql
Copy
UPDATE
Example:
sql
Copy
DELETE
The DELETE statement is used to delete existing records.
sql
Copy
Example:
sql
Copy
INT: Integer.
Example:
sql
Copy
5. Constraints
FOREIGN KEY
UNIQUE
NOT NULL
CHECK
DEFAULT
6. Filtering Data
WHERE Clause
SELECT * FROM employees WHERE age > 30 AND salary > 50000;
sql
Copy
7. Sorting Data
ORDER BY Clause
8. Aggregate Functions
COUNT, SUM, AVG, MIN, MAX
9. Grouping Data
GROUP BY Clause
HAVING Clause
10. Joins
INNER JOIN
LEFT JOIN
Returns all records from the left table and matched records from the right table.
sql
Copy
RIGHT JOIN
Returns all records from the right table and matched records from the left table.
sql
Copy
FULL JOIN
Returns all records when there is a match in either left or right table.
sql
Copy
CROSS JOIN
11. Subqueries
INTERSECT
EXCEPT
Returns records from the first SELECT statement that are not in the second.
sql
Copy
13. Views
14. Indexes
15. Transactions
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Function
17. Triggers
Perform calculations across a set of table rows related to the current row.
sql
Copy
SELECT first_name, salary, RANK() OVER (ORDER BY salary DESC) AS rank FROM
employees;
A temporary result set that you can reference within a SELECT, INSERT, UPDATE, or
DELETE statement.
sql
Copy
WITH HighSalaryEmployees AS (
SELECT * FROM employees WHERE salary > 70000
)
SELECT * FROM HighSalaryEmployees;
Pivot Tables
SELECT department,
SUM(CASE WHEN year = 2020 THEN salary END) AS "2020",
SUM(CASE WHEN year = 2021 THEN salary END) AS "2021"
FROM employees
GROUP BY department;
This tutorial covers the fundamental and advanced topics in SQL. Practice these
concepts by writing queries and experimenting with different datasets. Happy
querying!