Comprehensive Guide To SQL (Structured Query Language)

Comprehensive Guide To SQL (Structured Query Language)

What is SQL

  • SQL (Structured Query Language) is a standardized programming language used to manage and manipulate relational databases.
  • It helps in performing tasks such as querying data, updating records, inserting data, and deleting records.
  • Key SQL Commands:SELECT: Retrieves data from a database.INSERT: Adds data to a table.UPDATE: Modifies existing data.DELETE: Removes data from a table.CREATE: Creates new tables or databases.DROP: Deletes tables or databases.


2. MySQL Installation

MySQL is a popular relational database management system that uses SQL for managing databases. Here's a general guide for installation:

  • Windows:
  • macOS/Linux:

Once installed, you're ready to interact with the MySQL database using SQL commands.


3. Types of SQL Commands

SQL commands are categorized into different types, based on their functionality:

  • DML (Data Manipulation Language): Deals with data manipulation within tables.SELECT, INSERT, UPDATE, DELETE
  • DDL (Data Definition Language): Deals with schema definitions (structure of databases).CREATE, ALTER, DROP, TRUNCATE
  • DCL (Data Control Language): Manages access control.GRANT, REVOKE
  • TCL (Transaction Control Language): Deals with transaction operations.COMMIT, ROLLBACK, SAVEPOINT

These commands provide full control over the database, allowing you to create, modify, and secure data.


4. Databases and Related SQL Commands

  • A database is a collection of data organized in a structured way.
  • Commands to work with databases:CREATE DATABASE database_name; – Creates a new database.USE database_name; – Selects the database to be used.DROP DATABASE database_name; – Deletes a database.


5. Tables and Related SQL Commands

Tables are where the actual data is stored in a relational database.

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    department VARCHAR(50),
    salary DECIMAL(10, 2)
);

DROP TABLE employees;
        

6. Building a Database – From Tables to Data Insertion

  • After creating a database and tables, the next step is to insert data.

INSERT INTO employees (id, name, department, salary) 
VALUES (1, 'Alice', 'HR', 60000.00);

SELECT * FROM employees;        

7. Datatypes in SQL

SQL provides different types of data that can be stored in a table:

  • INT: Integer values (e.g., 1, 2, 100).
  • VARCHAR(size): Variable-length character string (e.g., VARCHAR(50) can store up to 50 characters).
  • DECIMAL(p, s): Decimal numbers where p is the total number of digits, and s is the number of digits after the decimal point (e.g., DECIMAL(10, 2) can store 12345678.90).
  • DATE: Stores date values (e.g., 2023-09-15).
  • BOOLEAN: True or false values.

These datatypes ensure that the data entered into the tables are valid and consistent.


8. Keys in SQL

Keys are essential in SQL for identifying rows in tables and creating relationships between tables.

Example:

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);        

  • Primary Key: Uniquely identifies each record in a table.Example:
  • Unique Key: Ensures that all values in a column are distinct.
  • Foreign Key: Links a column in one table to a primary key in another table (covered in more detail in the next section).


9. Constraints in SQL

Constraints enforce rules on data in the table.

  • NOT NULL: Ensures a column cannot have a NULL value.
  • UNIQUE: Ensures all values in a column are unique.
  • PRIMARY KEY: A combination of NOT NULL and UNIQUE. Identifies each row uniquely.
  • FOREIGN KEY: Ensures referential integrity between tables.
  • CHECK: Ensures that values meet a specific condition.

CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, salary DECIMAL(10, 2) CHECK(salary > 0) );        

10. Foreign Key in SQL

A Foreign Key is used to create a relationship between two tables by linking a column from one table to the primary key of another table.

Example:

CREATE TABLE departments ( dept_id INT PRIMARY KEY, dept_name VARCHAR(50) ); CREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name VARCHAR(50), dept_id INT, FOREIGN KEY (dept_id) REFERENCES departments(dept_id) );        

  • Here, dept_id in the employees table references the dept_id in the departments table, linking the two tables.



Lets study more About DML

DML (Data Manipulation Language):

These commands are used for managing data within tables. They are used to retrieve, insert, update, and delete data.

  • SELECT: Retrieves data from a table.

SELECT * FROM employees;        

Copy code

SELECT * FROM employees;

  • INSERT: Adds new rows of data into a table.

INSERT INTO employees (id, name, department, salary) 
VALUES (1, 'Alice', 'HR', 50000);        

  • UPDATE: Modifies existing data within a table.

UPDATE employees 
SET salary = 55000 
WHERE id = 1;        

  • DELETE: Removes data from a table.

DELETE FROM employees 
WHERE id = 1;        

2. DDL (Data Definition Language):

These commands are used to define and manage the structure of database objects like tables, indexes, and views.

  • CREATE: Creates new objects such as databases or tables.

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    department VARCHAR(50),
    salary DECIMAL(10, 2)
);        

  • ALTER: Modifies the structure of an existing table.

ALTER TABLE employees 
ADD email VARCHAR(100);        

  • DROP: Deletes objects such as tables or databases.

DROP TABLE employees;        

  • TRUNCATE: Removes all records from a table but keeps its structure.

TRUNCATE TABLE employees;        

3. DCL (Data Control Language):

These commands are used to control access to data within the database, ensuring only authorized users can perform specific actions.

  • GRANT: Gives permissions to users.

GRANT SELECT, INSERT ON employees TO 'user1'@'localhost';        

  • REVOKE: Removes permissions from users.

REVOKE SELECT ON employees FROM 'user1'@'localhost';
        

4. TCL (Transaction Control Language):

TCL commands handle transactions within a database. A transaction is a sequence of operations performed as a single logical unit of work.

  • COMMIT: Saves the current transaction's changes permanently.

INSERT INTO employees (id, name, department, salary) 
VALUES (2, 'Bob', 'Finance', 60000);

COMMIT;
        

  • ROLLBACK: Reverts the changes made during the current transaction if something goes wrong.

INSERT INTO employees (id, name, department, salary) 
VALUES (3, 'Eve', 'IT', 70000);

ROLLBACK;
        

  • SAVEPOINT: Sets a point within a transaction to which you can later roll back.

SAVEPOINT beforeUpdate;

UPDATE employees 
SET salary = 65000 
WHERE id = 2;

ROLLBACK TO beforeUpdate;
        

Summary:

  • DML (Data Manipulation Language): Manipulates data (SELECT, INSERT, UPDATE, DELETE).
  • DDL (Data Definition Language): Defines structure (CREATE, ALTER, DROP, TRUNCATE).
  • DCL (Data Control Language): Manages access (GRANT, REVOKE).
  • TCL (Transaction Control Language): Manages transactions (COMMIT, ROLLBACK, SAVEPOINT).

These SQL commands provide comprehensive control over data and the structure of a relational database.


        

we'll cover SQL queries and clauses, focusing on commands that allow you to manipulate and retrieve data from tables.

1. UPDATE Command in SQL

The UPDATE command modifies existing records in a table.

UPDATE employees SET salary = 55000 WHERE id = 2;        

This command updates the salary of the employee with id = 2 to 55000. If you omit the WHERE clause, all rows in the table will be updated.


2. DELETE Command in SQL

The DELETE command removes rows from a table based on a specified condition.

Example:

DELETE FROM employees WHERE id = 3;        

This deletes the employee with id = 3. Again, without the WHERE clause, all rows will be deleted, though the table structure will remain.


3. SELECT Command in SQL

The SELECT command is used to retrieve data from one or more tables.

You can also retrieve all columns using:

SELECT * FROM employees;

SELECT name, department 
FROM employees 
WHERE salary > 50000;
        

This retrieves the names and departments of employees whose salary is greater than 50000.


4. WHERE Clause in SQL

The WHERE clause filters records, allowing you to specify conditions for selecting, updating, or deleting records.

SELECT * FROM employees WHERE department = 'IT';        

This retrieves all employees from the IT department.

You can also combine conditions using logical operators:

  • AND: Both conditions must be true.
  • OR: Either condition must be true.
  • NOT: Reverses the condition.

Example using AND and OR:

SELECT * FROM employees 
WHERE department = 'IT' AND salary > 50000;        

This retrieves employees who are in the IT department and have a salary greater than 50,000.



5. ALTER Command in SQL

The ALTER command is used to modify the structure of an existing table.

  • Add a column:

ALTER TABLE employees 
ADD phone_number VARCHAR(15);        

  • Modify a column:

ALTER TABLE employees 
MODIFY salary DECIMAL(12, 2);        

  • Drop a column:

ALTER TABLE employees 
DROP COLUMN phone_number;        

6. RENAME Command in SQL

The RENAME command is used to rename a table or a column.

  • Rename a table:

ALTER TABLE employees 
DROP COLUMN phone_number;        

  • Rename a column (Using ALTER):

ALTER TABLE employees 
DROP COLUMN phone_number;        

7. TRUNCATE Command in SQL

The TRUNCATE command removes all rows from a table, but unlike DELETE, it doesn't log each deleted row, making it faster. The table structure is preserved.

ALTER TABLE employees 
DROP COLUMN phone_number;        

8. Difference Between TRUNCATE, DELETE, & DROP in SQL

  • TRUNCATE:
  • Removes all rows from a table, but keeps the table structure intact.
  • Cannot be rolled back in most databases.

TRUNCATE TABLE employees;        

  • DELETE:
  • Removes specific rows or all rows if no condition is given.
  • Can be rolled back if part of a transaction.

DELETE FROM employees WHERE id = 2;        

  • DROP:
  • Deletes the entire table structure and all its data.
  • Cannot be rolled back.

 DROP TABLE employees;        

9. DISTINCT Keyword in SQL

The DISTINCT keyword is used to return only unique values, filtering out duplicates.

SELECT DISTINCT department 
FROM employees;        

10. Operators in SQL

SQL uses various operators to filter and compare data. Here are the most common types:

  • Arithmetic Operators::

SELECT salary + 1000 
FROM employees 
WHERE id = 2;        

  • Comparison Operators::

SELECT * FROM employees 
WHERE salary >= 50000;        

  • Logical Operators:

SELECT * FROM employees 
WHERE department = 'HR' AND salary > 50000;        

11. Clauses in SQL

SQL clauses are used to specify conditions and organize query results.

  • WHERE: Filters rows based on a condition (as covered earlier).
  • ORDER BY: Sorts the results based on one or more columns.

SELECT * FROM employees 
ORDER BY salary DESC;
        

  • LIMIT: Restricts the number of rows returned.

SELECT * FROM employees 
LIMIT 5;
        

Summary

  • UPDATE: Modify existing data.
  • DELETE: Remove data from a table.
  • SELECT: Retrieve data from a table.
  • WHERE: Filter data based on a condition.
  • ALTER: Modify the structure of a table.
  • RENAME: Change the name of a table or column.
  • TRUNCATE: Remove all rows from a table.
  • DISTINCT: Get unique values.
  • Operators: Perform arithmetic and logical operations.
  • Clauses: Add additional functionality to your queries (e.g., ORDER BY, LIMIT).

These are the building blocks of SQL that will help you effectively manipulate and retrieve data from your database. Experiment with these commands to get comfortable using them in different scenarios.




we’ll cover more advanced SQL concepts, including aggregate functions, joins, and sub queries.

These are essential for performing more complex queries on databases.


1. Aggregate Functions in SQL

Here are the most commonly used aggregate functions:

  • COUNT(): Returns the number of rows that match a condition.

SELECT COUNT(*) 
FROM employees;        

  • SUM(): Adds up the values in a column.

SELECT SUM(salary) 
FROM employees 
WHERE department = 'IT';        

  • AVG(): Returns the average value of a numeric column

SELECT AVG(salary) 
FROM employees;        

  • MIN(): Returns the smallest value in a column.

SELECT MIN(salary) 
FROM employees;        


  • MAX(): Returns the largest value in a column.

SELECT MAX(salary) 
FROM employees;
        

2. GROUP BY and HAVING Clauses in SQL

The GROUP BY clause groups rows that have the same values in specified columns into summary rows, like “total salary by department.” The HAVING clause is used to filter records after the GROUP BY.

  • GROUP BY Syntax:

SELECT department, SUM(salary) 
FROM employees 
GROUP BY department;        

  • HAVING Syntax:

SELECT department, SUM(salary) 
FROM employees 
GROUP BY department
HAVING SUM(salary) > 100000;        

3. Difference Between HAVING and WHERE Clause in SQL

  • The WHERE clause filters rows before grouping.
  • The HAVING clause filters rows after grouping.
  • WHERE Example:

SELECT * FROM employees WHERE salary > 50000;        

  • HAVING Example:

SELECT department, SUM(salary) FROM employees GROUP BY department HAVING SUM(salary) > 100000;        

4. Practice Questions on Clauses and Aggregate Functions

Here are some practice questions to solidify your understanding:

  1. Find the total salary of employees in each department

SELECT department, SUM(salary) 
FROM employees 
GROUP BY department;        


  1. Find the average salary of employees in the IT department:

SELECT AVG(salary) 
FROM employees 
WHERE department = 'IT';        


  1. Find the department with a total salary greater than 200,000:

SELECT department, SUM(salary) 
FROM employees 
GROUP BY department
HAVING SUM(salary) > 200000;        

  1. Count the number of employees in each department:

SELECT department, COUNT(*) 
FROM employees 
GROUP BY department;        



5. General Order of SQL Commands

When writing SQL queries, commands follow a specific order of execution:

  1. FROM: The table from which the data is retrieved.
  2. WHERE: Filters the data.
  3. GROUP BY: Groups data.
  4. HAVING: Filters groups.
  5. SELECT: Specifies columns to display.
  6. ORDER BY: Sorts the result.

  • Example Query:
  • Query:

SELECT department, AVG(salary) FROM employees WHERE salary > 30000 GROUP BY department HAVING AVG(salary) > 50000 ORDER BY AVG(salary) DESC;        

6. Joins in SQL

SQL JOIN clauses are used to combine rows from two or more tables based on a related column.


Types of Joins:

a. INNER JOIN:

Returns only the rows where there is a match in both tables.

SELECT employees.name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.id;        

This returns employees and their corresponding department names, but only for employees who have a matching department.



b. LEFT (OUTER) JOIN:

Returns all rows from the left table, and matched rows from the right table. If there's no match, NULL values are returned for columns from the right table.

  • This returns all employees and their corresponding department names. If an employee has no matching department, the department_name will be NULL.

SELECT employees.name, departments.department_name FROM employees LEFT JOIN departments ON employees.department_id = departments.id;        

c. RIGHT (OUTER) JOIN:

Returns all rows from the right table, and matched rows from the left table. If there's no match, NULL values are returned for columns from the left table.

This returns all departments, including those with no employees.

SELECT employees.name, departments.department_name FROM employees RIGHT JOIN departments ON employees.department_id = departments.id;        

d. FULL (OUTER) JOIN:

Returns rows when there is a match in either left or right table. Non-matching rows will have NULL values for columns where there is no match.

Example:

This returns all employees and all departments, with NULL values where there is no match.

SELECT employees.name, departments.department_name FROM employees FULL OUTER JOIN departments ON employees.department_id = departments.id;
        

7. Subqueries in SQL

A subquery is a query within another query. It can be used in SELECT, INSERT, UPDATE, or DELETE statements.

  • Example (Subquery in SELECT):

SELECT name 
FROM employees 
WHERE salary > (SELECT AVG(salary) FROM employees);

This retrieves the names of employees whose salary is greater than the average salary of all employees.        

8. Nth Highest Salary in SQL

Finding the Nth highest salary in SQL can be done using LIMIT or OFFSET in a subquery.

  • Example (Find the 2nd highest salary):

SELECT salary 
FROM employees 
ORDER BY salary DESC 
LIMIT 1 OFFSET 1;
        

  • ORDER BY salary DESC: Orders salaries in descending order.
  • LIMIT 1 OFFSET 1: Skips the highest salary and returns the next one.


Summary

  • Aggregate Functions: Perform calculations on data (e.g., COUNT(), SUM(), AVG()).
  • GROUP BY and HAVING: Group data and filter after grouping.
  • Joins: Combine data from multiple tables (e.g., INNER JOIN, LEFT JOIN).
  • Subqueries: Nested queries to enhance your results.
  • Nth Highest Salary: Using LIMIT and OFFSET to find ranked results.

These concepts help you perform complex queries and join data across multiple tables efficiently. Practice writing queries using these commands to strengthen your understanding.



要查看或添加评论,请登录

Ijaz Khan的更多文章

社区洞察

其他会员也浏览了