SQL tutorial and QnA with examples

Sure! Here's an SQL tutorial with examples to help you understand the basics and gradually progress to more advanced topics. We'll cover key SQL concepts using simple queries.

1. SQL Basics - Querying Data

1.1 SELECT Statement

The SELECT statement is used to query (retrieve) data from a table.

Syntax:

SELECT column1, column2, ... FROM table_name;

Example:

SELECT first_name, last_name FROM employees;

This retrieves the first name and last name of all employees from the employees table.

1.2 SELECT * (All Columns)

You can retrieve all columns from a table using *.

Example:

SELECT * FROM employees;

This retrieves all the columns for each employee in the employees table.

2. Filtering Data

2.1 WHERE Clause

The WHERE clause is used to filter records based on a specified condition.

Syntax:

SELECT column1, column2 FROM table_name WHERE condition;

Example:

SELECT first_name, last_name FROM employees WHERE department = 'Sales';

This query returns the first name and last name of employees in the 'Sales' department.

2.2 Comparison Operators

You can use comparison operators such as =, >, <, >=, <=, and <> in the WHERE clause.

Example:

SELECT first_name, salary FROM employees WHERE salary > 50000;

This query returns the first name and salary of employees whose salary is greater than 50,000.

2.3 Logical Operators

Use AND, OR, and NOT to combine multiple conditions.

Example:

SELECT first_name, department, salary FROM employees WHERE department = 'Sales' AND salary > 50000;

This retrieves the first name, department, and salary of employees in the 'Sales' department with a salary greater than 50,000.

3. Sorting Data

3.1 ORDER BY Clause

The ORDER BY clause sorts the result set in ascending or descending order.

Syntax:

SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];

Example:

SELECT first_name, salary FROM employees ORDER BY salary DESC;

This retrieves the first name and salary of employees, sorted by salary in descending order.

3.2 Sorting by Multiple Columns

You can sort by multiple columns by separating them with commas.

Example:

SELECT first_name, last_name, department, salary FROM employees ORDER BY department ASC, salary DESC;

This sorts the employees first by department (in ascending order), and then by salary (in descending order).

4. Aggregating Data

4.1 COUNT() Function

The COUNT() function is used to count the number of rows that match a specified condition.

Example:

SELECT COUNT(*) FROM employees WHERE department = 'Sales';

This counts the number of employees in the 'Sales' department.

4.2 SUM() Function

The SUM() function returns the total sum of a numeric column.

Example:

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

This calculates the total salary of employees in the 'Marketing' department.

4.3 AVG() Function

The AVG() function calculates the average value of a numeric column.

Example:

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

This returns the average salary of employees in the 'IT' department.

4.4 GROUP BY Clause

The GROUP BY clause is used to group rows that have the same values into summary rows, often with aggregate functions.

Example:

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

This calculates the average salary for each department.

4.5 HAVING Clause

The HAVING clause is used to filter groups after applying aggregate functions, like SUM(), AVG(), etc.

Example:

SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 60000;

This retrieves departments where the average salary is greater than 60,000.

5. Joining Tables

5.1 INNER JOIN

An INNER JOIN returns records that have matching values in both tables.

Syntax:

SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Example:

SELECT employees.first_name, employees.last_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id;

This retrieves the first name, last name, and department name of employees by joining the employees and departments tables on the department_id field.

5.2 LEFT JOIN

A LEFT JOIN returns all records from the left table, along with the matched records from the right table. If there's no match, NULL is returned.

Example:

SELECT employees.first_name, employees.last_name, departments.department_name FROM employees LEFT JOIN departments ON employees.department_id = departments.department_id;

This retrieves the first name, last name, and department name of employees, including employees who do not belong to any department (in this case, NULL will be returned for the department name).

6. Modifying Data

6.1 INSERT INTO

The INSERT INTO statement is used to add new records into a table.

Syntax:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Example:

INSERT INTO employees (first_name, last_name, department, salary) VALUES ('John', 'Doe', 'Sales', 55000);

This adds a new employee to the employees table with the specified values.

6.2 UPDATE

The UPDATE statement is used to modify existing records in a table.

Syntax:

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

Example:

UPDATE employees SET salary = 60000 WHERE department = 'Sales';

This updates the salary of all employees in the 'Sales' department to 60,000.

6.3 DELETE

The DELETE statement is used to delete records from a table.

Syntax:

DELETE FROM table_name WHERE condition;

Example:

DELETE FROM employees WHERE employee_id = 101;

This deletes the employee with employee_id 101 from the employees table.

7. Subqueries

A subquery is a query within another query.

7.1 Subquery in SELECT

A subquery can be used in the SELECT clause to calculate values dynamically.

Example:

SELECT first_name, last_name, (SELECT MAX(salary) FROM employees) AS max_salary FROM employees;

This returns the first name, last name, and the maximum salary of employees.

7.2 Subquery in WHERE

A subquery can be used in the WHERE clause to filter results.

Example:

SELECT first_name, last_name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);

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

****************************************

1. SQL Basics - Querying Data

1.1 SELECT Statement

The SELECT statement is the primary SQL statement used to retrieve data from a database table.

Syntax:

SELECT column1, column2, ... FROM table_name;
  • column1, column2, ... are the columns you want to retrieve.
  • table_name is the name of the table from which you're retrieving the data.

Example:

SELECT first_name, last_name FROM employees;

This returns the first_name and last_name columns for all employees in the employees table.

Notes:

  • You can select specific columns or all columns (*).
  • The order of the columns in the query determines the order of the data returned.

1.2 SELECT * (All Columns)

You can use the wildcard * to select all columns of a table.

Example:

SELECT * FROM employees;

This will return every column from the employees table for all rows.

Warning: Using * is convenient, but it's best to specify only the columns you need in order to reduce unnecessary data retrieval, especially for large tables.

2. Filtering Data

2.1 WHERE Clause

The WHERE clause allows you to filter the data that is returned based on a condition.

Syntax:

SELECT column1, column2 FROM table_name WHERE condition;

Example:

SELECT first_name, last_name FROM employees WHERE department = 'Sales';

This will return the first_name and last_name of employees who work in the 'Sales' department.

Conditions:

  • Comparisons like =, >, <, <=, >=, <> (not equal).
  • Logical operators like AND, OR, NOT.

2.2 Comparison Operators

SQL provides several comparison operators to filter data.

  • = (Equal)
  • > (Greater Than)
  • < (Less Than)
  • >= (Greater Than or Equal To)
  • <= (Less Than or Equal To)
  • <> (Not Equal To)

Example:

SELECT first_name, salary FROM employees WHERE salary > 50000;

This retrieves the first name and salary of employees with a salary greater than 50,000.

2.3 Logical Operators

You can combine multiple conditions with logical operators like AND, OR, and NOT.

Example:

sql
SELECT first_name, last_name, salary FROM employees WHERE department = 'Sales' AND salary > 50000;

This retrieves the first name, last name, and salary of employees in the 'Sales' department whose salary is greater than 50,000.

Example using OR:

sql
SELECT first_name, last_name FROM employees WHERE department = 'Sales' OR department = 'Marketing';

This retrieves the names of employees in either 'Sales' or 'Marketing' departments.

3. Sorting Data

3.1 ORDER BY Clause

You can use the ORDER BY clause to sort the results in ascending (default) or descending order.

Syntax:

SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];
  • ASC (ascending) is the default, and DESC (descending) is used to sort data in reverse order.

Example:

SELECT first_name, salary FROM employees ORDER BY salary DESC;

This retrieves the first name and salary of employees, sorted by salary in descending order.

3.2 Sorting by Multiple Columns

You can sort by multiple columns by separating them with commas.

Example:

SELECT first_name, last_name, department, salary FROM employees ORDER BY department ASC, salary DESC;

This sorts employees first by department in ascending order, and then by salary in descending order within each department.

4. Aggregating Data

4.1 COUNT() Function

The COUNT() function is used to count the number of rows or records in a table that match a specific condition.

Example:

SELECT COUNT(*) FROM employees WHERE department = 'Sales';

This counts how many employees belong to the 'Sales' department.

4.2 SUM() Function

The SUM() function is used to calculate the total sum of a numeric column.

Example:

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

This calculates the total salary of all employees in the 'Marketing' department.

4.3 AVG() Function

The AVG() function calculates the average value of a numeric column.

Example:

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

This returns the average salary of employees in the 'IT' department.

4.4 GROUP BY Clause

The GROUP BY clause groups rows that have the same values into summary rows. It is often used with aggregate functions (COUNT(), SUM(), AVG(), etc.).

Example:

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

This calculates the average salary for each department.

4.5 HAVING Clause

The HAVING clause is used to filter groups after applying aggregate functions, unlike WHERE, which filters individual rows before grouping.

Example:

SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 60000;

This filters out departments where the average salary is less than or equal to 60,000.

5. Joining Tables

5.1 INNER JOIN

An INNER JOIN returns only the records where there is a match in both tables.

Syntax:

SELECT column1, column2 FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Example:

SELECT employees.first_name, employees.last_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id;

This retrieves the first name, last name, and department name for employees by matching the department_id from the employees and departments tables.

5.2 LEFT JOIN

A LEFT JOIN returns all records from the left table, and the matching records from the right table. If there's no match, it returns NULL for columns from the right table.

Example:

SELECT employees.first_name, employees.last_name, departments.department_name FROM employees LEFT JOIN departments ON employees.department_id = departments.department_id;

This retrieves all employees' names along with their department names. If an employee does not belong to any department, the department name will be NULL.

6. Modifying Data

6.1 INSERT INTO

The INSERT INTO statement is used to add new records to a table.

Syntax:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Example:

INSERT INTO employees (first_name, last_name, department, salary) VALUES ('John', 'Doe', 'Sales', 55000);

This inserts a new employee into the employees table with a first_name of 'John', last_name of 'Doe', department as 'Sales', and salary of 55,000.

6.2 UPDATE

The UPDATE statement is used to modify existing data in a table.

Syntax:

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

Example:

UPDATE employees SET salary = 60000 WHERE department = 'Sales';

This updates the salary to 60,000 for all employees in the 'Sales' department.

6.3 DELETE

The DELETE statement is used to remove records from a table.

Syntax:

DELETE FROM table_name WHERE condition;

Example:

DELETE FROM employees WHERE employee_id = 101;

This deletes the employee with employee_id 101 from the employees table.

7. Subqueries

A subquery is a query nested inside another query.

7.1 Subquery in SELECT

You can use a subquery in the SELECT clause to calculate a value dynamically for each row.

Example:

SELECT first_name, last_name, (SELECT MAX(salary) FROM employees) AS max_salary FROM employees;

This retrieves the first name, last name, and the maximum salary from the employees table.

7.2 Subquery in WHERE

You can use a subquery in the WHERE clause to filter the result based on dynamic conditions.

Example:

SELECT first_name, last_name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);

This retrieves the first name and last name of employees whose salary is greater than the average salary of all employees.


These are the foundational concepts of SQL. Each section can be further expanded, especially with advanced topics such as joins (e.g., RIGHT JOIN, FULL JOIN), subqueries, views, stored procedures, and more. As you continue to practice and write queries, you'll become proficient in SQL.

=================>

Here’s a list of commonly asked SQL questions and their answers, which can help you prepare for a SQL interview:

1. What is SQL?

Answer:
SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. It is used to query, insert, update, and delete data in databases.

2. What are the different types of SQL commands?

Answer:
SQL commands are categorized into the following:

  • DML (Data Manipulation Language): Used for data manipulation.
    • SELECT, INSERT, UPDATE, DELETE
  • DDL (Data Definition Language): Used for defining data structures.
    • CREATE, ALTER, DROP, TRUNCATE
  • DCL (Data Control Language): Used for permissions and access control.
    • GRANT, REVOKE
  • TCL (Transaction Control Language): Used for managing transactions.
    • COMMIT, ROLLBACK, SAVEPOINT

3. What is the difference between INNER JOIN and LEFT JOIN?

Answer:

  • INNER JOIN: Returns records that have matching values in both tables.
  • LEFT JOIN: Returns all records from the left table, and the matched records from the right table. If there is no match, NULL values will be returned for columns from the right table.

4. What is normalization?

Answer:
Normalization is the process of organizing the attributes and tables of a relational database to minimize redundancy and dependency. It involves dividing a database into two or more tables and defining relationships between them. There are several normal forms (1NF, 2NF, 3NF, BCNF, etc.).

5. What is the difference between WHERE and HAVING?

Answer:

  • WHERE: Filters rows before grouping.
  • HAVING: Filters groups after grouping (i.e., used with aggregate functions).

6. What is the difference between UNION and UNION ALL?

Answer:

  • UNION: Combines results from two queries and removes duplicate rows.
  • UNION ALL: Combines results from two queries without removing duplicates.

7. What are aggregate functions in SQL?

Answer:
Aggregate functions perform a calculation on a set of values and return a single value. Common aggregate functions are:

  • COUNT()
  • SUM()
  • AVG()
  • MIN()
  • MAX()

8. What is a PRIMARY KEY?

Answer:
A PRIMARY KEY is a field (or combination of fields) in a table that uniquely identifies each record in that table. It must contain unique values and cannot contain NULLs.

9. What is a FOREIGN KEY?

Answer:
A FOREIGN KEY is a field (or group of fields) in a table that uniquely identifies a row of another table or the same table. It establishes a relationship between the two tables.

10. What is the GROUP BY clause?

Answer:
The GROUP BY clause is used in conjunction with aggregate functions to group the result set by one or more columns. It is used to organize identical data into groups.

11. What is the difference between DELETE, TRUNCATE, and DROP?

Answer:

  • DELETE: Removes rows from a table based on a condition. It is a DML command and can be rolled back.
  • TRUNCATE: Removes all rows from a table but does not log individual row deletions. It is a DDL command and cannot be rolled back.
  • DROP: Removes a table from the database entirely, including its structure and data.

12. What is the DISTINCT keyword in SQL?

Answer:
The DISTINCT keyword is used to return only distinct (unique) values in a query result.

13. What is an index in SQL?

Answer:
An index is a database object that improves the speed of data retrieval operations on a table at the cost of additional space and maintenance time during data modification operations (INSERT, UPDATE, DELETE).

14. What is a SELF JOIN?

Answer:
A SELF JOIN is a type of join where a table is joined with itself. This is useful when a table has hierarchical relationships.

15. What are subqueries?

Answer:
A subquery is a query nested inside another query, typically in the WHERE, FROM, or SELECT clauses. It allows you to perform more complex filtering or calculations.

16. What is the IN operator in SQL?

Answer:
The IN operator is used to compare a column's value with a set of values. It is equivalent to multiple OR conditions.

SELECT * FROM Employees WHERE Department IN ('Sales', 'HR', 'IT');

17. What is the difference between CHAR and VARCHAR?

Answer:

  • CHAR: A fixed-length character string. It always occupies the specified length, even if the data is shorter.
  • VARCHAR: A variable-length character string. It occupies only the amount of space needed for the data.

18. What is the CASE statement in SQL?

Answer:
The CASE statement is a conditional expression in SQL that returns a value based on conditions. It’s like an IF-ELSE statement.

SELECT Name, CASE WHEN Age >= 18 THEN 'Adult' ELSE 'Minor' END AS AgeGroup FROM Persons;

19. What is a view in SQL?

Answer:
A view is a virtual table based on the result set of a SQL query. It can be used to simplify complex queries, and it doesn’t store data itself but fetches it from underlying tables.

20. What is a transaction in SQL?

Answer:
A transaction is a unit of work in SQL that is executed as a single operation. It ensures that either all operations are completed successfully (commit) or none (rollback) in case of an error.

21. What is ACID in database management?

Answer:
ACID stands for:

  • Atomicity: The transaction is all or nothing.
  • Consistency: The transaction brings the database from one valid state to another.
  • Isolation: Transactions are executed independently of each other.
  • Durability: Changes made by a transaction are permanent, even in the event of a system failure.

22. What is the difference between NULL and IS NULL?

Answer:

  • NULL is a keyword that represents an unknown or missing value.
  • IS NULL is used to check if a value is NULL in SQL.
sql
SELECT * FROM Employees WHERE Age IS NULL;

23. What is a stored procedure in SQL?

Answer:
A stored procedure is a precompiled collection of one or more SQL statements that can be executed on the database. It allows for modular programming and reusability.

24. What is a trigger in SQL?

Answer:
A trigger is a set of SQL statements that are automatically executed in response to certain events (like INSERT, UPDATE, or DELETE) on a table or view.

25. What is a schema in SQL?

Answer:
A schema is a collection of database objects, such as tables, views, indexes, etc., that are associated with a database. It provides a way to logically group these objects.

26. What is a composite key in SQL?

Answer:
A composite key is a primary key made up of two or more columns to uniquely identify a record in a table. It is used when a single column is not enough to uniquely identify a record.

CREATE TABLE Orders ( OrderID INT, ProductID INT, PRIMARY KEY (OrderID, ProductID) );

27. What is a unique constraint in SQL?

Answer:
A unique constraint ensures that all values in a column are different. Unlike the primary key, a column with a unique constraint can contain NULL values, but all non-null values must be unique.

28. What is a stored function in SQL?

Answer:
A stored function is similar to a stored procedure but always returns a value. It can be used in SQL statements (e.g., SELECT, WHERE) and is generally used to perform operations like calculations.

29. What is the difference between RDBMS and NoSQL?

Answer:

  • RDBMS (Relational Database Management System): Uses structured data stored in tables with fixed schemas and enforces relationships between tables. Examples include MySQL, PostgreSQL, SQL Server.
  • NoSQL: Typically used for unstructured or semi-structured data and does not enforce a fixed schema. It supports flexible data models like key-value pairs, documents, graphs, etc. Examples include MongoDB, Cassandra, Redis.

30. What is Referential Integrity in SQL?

Answer:
Referential integrity ensures that relationships between tables remain consistent. It is enforced by FOREIGN KEY constraints, ensuring that a foreign key value in one table corresponds to a valid primary key value in another table.

31. What are indexes and how do they work?

Answer:
An index is used to speed up the retrieval of data from a table. It is a data structure that allows faster searches. When a query is executed, the database uses the index to locate rows more quickly. However, indexes also add overhead during INSERT, UPDATE, and DELETE operations.

32. What is a subquery and what types of subqueries exist?

Answer:
A subquery is a query nested within another query. There are several types of subqueries:

  • Scalar subquery: Returns a single value.
  • Row subquery: Returns a single row of values.
  • Column subquery: Returns a single column of values.
  • Table subquery: Returns a table of results (used in FROM clause).

33. What is the EXISTS operator in SQL?

Answer:
The EXISTS operator is used to check if the result of a subquery returns any rows. If the subquery returns one or more rows, the EXISTS condition evaluates to true.

SELECT * FROM Employees e WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.EmployeeID = e.EmployeeID);

34. What are wildcards in SQL?

Answer:
Wildcards are special characters used in SQL LIKE queries to match patterns. Common wildcards include:

  • %: Represents any sequence of characters.
  • _: Represents a single character.
SELECT * FROM Customers WHERE Name LIKE 'A%'; -- Finds all names starting with 'A'

35. What is the COALESCE function in SQL?

Answer:
The COALESCE function returns the first non-null value in a list of expressions. It is often used to handle NULL values.

SELECT COALESCE(Phone, 'No Phone') FROM Customers;

36. What is the CONCAT function in SQL?

Answer:
The CONCAT function is used to concatenate two or more strings together.

SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM Employees;

37. What is the LIKE operator in SQL?

Answer:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. It is often used with wildcard characters.

SELECT * FROM Employees WHERE Name LIKE 'A%'; -- Finds all employees whose names start with 'A'

38. What is a foreign key constraint in SQL?

Answer:
A foreign key constraint ensures that the value in one table corresponds to a valid value in another table. It enforces the integrity of the relationship between the two tables.

CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );

39. What is the ROWNUM function in SQL?

Answer:
ROWNUM is a pseudocolumn in Oracle that assigns a unique row number to each row returned by a query. It can be used to limit the number of rows returned.

SELECT * FROM Employees WHERE ROWNUM <= 10;

40. What is the LIMIT clause in SQL?

Answer:
The LIMIT clause is used in SQL to restrict the number of rows returned by a query. It is commonly used in MySQL, PostgreSQL, and SQLite.

SELECT * FROM Employees LIMIT 5;

41. What is a cross join in SQL?

Answer:
A CROSS JOIN returns the Cartesian product of two tables, i.e., it returns all possible combinations of rows from both tables. If one table has m rows and the other has n rows, the result will have m * n rows.

SELECT * FROM Products CROSS JOIN Categories;

42. What is a union in SQL?

Answer:
A UNION operator is used to combine the results of two or more SELECT queries. It eliminates duplicate rows by default.

SELECT Name FROM Employees UNION SELECT Name FROM Managers;

43. What is the LIMIT clause used in SQL queries?

Answer:
The LIMIT clause is used in SQL to limit the number of rows returned in a query result. It is often used to retrieve a subset of rows for paging or testing purposes.

SELECT * FROM Employees LIMIT 10; -- Fetches the first 10 rows

44. What is SQL injection?

Answer:
SQL injection is a type of attack where an attacker can execute arbitrary SQL code on a database by manipulating input fields or URLs. It is prevented by using parameterized queries or prepared statements.

45. What is the ALTER command in SQL?

Answer:
The ALTER command is used to modify the structure of an existing table, such as adding, deleting, or modifying columns or constraints.

ALTER TABLE Employees ADD Age INT;

46. What is a timestamp in SQL?

Answer:
A timestamp is a data type used to store date and time information, typically representing the number of seconds since a particular date (like Unix epoch time). It is used for tracking changes or for auditing purposes.

47. What is data redundancy?

Answer:
Data redundancy refers to the unnecessary repetition of data in a database. It is avoided through normalization, where tables are organized to minimize duplicate information.

48. What is SQL Profiler?

Answer:
SQL Profiler is a tool in SQL Server that captures and logs database events. It is used for monitoring and troubleshooting SQL queries and performance issues.

49. How can you check if a column exists in a table in SQL?

Answer:
You can check if a column exists in a table using a query against the INFORMATION_SCHEMA.COLUMNS view.

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employees' AND COLUMN_NAME = 'Salary';

50. What is the difference between AND and OR in SQL?

Answer:

  • AND: Returns rows where all conditions are true.
  • OR: Returns rows where at least one condition is true.
SELECT * FROM Employees WHERE Age > 30 AND Department = 'HR';

These additional questions should provide more comprehensive coverage of common SQL interview topics. Make sure you practice writing queries, and understand concepts such as joins, aggregation, and normalization to perform well in interviews.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics