Advanced SQL Concepts
Advanced SQL Concepts
SSQL
QL Concepts
table?
In SQL, you can find the last ID in a table using the MAX function along
with the column that represents the ID. Assuming you have an "id" column
SQL
This query selects the maximum (largest) value in the "id" column and
aliases it as "last_id." The result will be a single row with the highest ID
SQL
SELECT id
FROM your_table_name
ORDER BY id DESC
LIMIT 1;
This query selects the maximum (largest) value in the "id" column and
aliases it as "last_id." The result will be a single row with the highest ID
This will retrieve distinct rows from the table based on all columns. Keep in
mind that this doesn't actually remove duplicates from the table; it just
returns a result set with distinct values.
This query selects the maximum (largest) value in the "id" column and
aliases it as "last_id." The result will be a single row with the highest ID
value in the specified table.
FROM your_table
WITH CTE AS (
SELECT *,
FROM your_table
DELETE t1
FROM your_table t1
AND ...;
This query deletes duplicates based on specified columns, keeping the row
with the lowest ID.
03 Question
2
Bob
102
3
Charlie
101
4 David 103
Departments Table:
id department_id
101
HR
102
IT
103
Marketing
104 Sales
Inner Join:
SQL Query:
SQL
FROM employees
departments.id;
Output:
name department_name
Alice
HR
Bob
IT
Charlie
HR
David Marketing
Left Join (Left Outer Join):
# Returns all rows from the left table and the matched rows from the right
table.
SQL Query:
SQL
FROM employees
departments.id;
Output:
name department_name
Alice
HR
Bob
IT
Charlie
HR
David Marketing
Right Join (Right Outer Join):
% Returns all rows from the right table and the matched rows from the left
table.
SQL Query:
SQL
FROM employees
departments.id;
Output:
name department_name
Alice
HR
Bob
IT
Charlie
HR
David
Marketing
NULL Sales
Full Outer Join:
" Returns all rows when there is a match in either the left or right table.
" Includes rows with no match in either table with NULL values.
SQL Query:
SQL
FROM employees
Output:
name department_name
Alice
HR
Bob
IT
Charlie
HR
David
Marketing
NULL Sales
Self Join:
SQL Query:
SQL
FROM employees e1
Output:
name manager
Alice
NULL
Bob
NULL
Charlie
Alice
David NULL
04 Question
It helps to create a result set where rows are grouped based on the values
in specified columns.
Example:
SQL
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
In this example, the result set will have one row for each distinct
department, and the average salary for each department will be calculated.
HAVING Clause:
Example:
SQL
FROM employees
GROUP BY department
MySQL:
In MySQL, the auto-increment feature is achieved using the
AUTO_INCREMENT attribute.
SQL
CREATE TABLE example_table (
name VARCHAR(50)
);
increment column.
SQL
name VARCHAR(50)
);
Example:
columns.
SQL
name VARCHAR(50)
);
INSERT INTO example_table (name) VALUES ('John');
UNION:
The UNION operator is used to combine the result sets of two or more
SELECT statements. It removes duplicate rows from the result set.
SQL
SELECT column1, column2 FROM table1
UNION
Example:
SQL
-- Assuming two tables with similar structure
UNION
Similar to UNION, the UNION ALL operator combines the result sets of two
SQL
UNION
Example:
SQL
UNION
INTERSECT:
INTERSECT
Example:
SQL
INTERSECT
SQL
MINUS
SQL
MINUS
orders;
07 Question
OFFSET 5 ROWS -- N - 1 = 6 - 1 = 5, so we
skip the first 5 rows
Explanation:
ORDER BY: It specifies the column based on which the ordering of rows
is done.
OFFSET 5 ROWS: It skips the first 5 rows, so the starting point is the
6th row.
FETCH NEXT 1 ROWS ONLY: It retrieves the next 1 row after the offset,
giving you the 6th row.
Method 2: Using ROWNUM
SQL
SELECT *
FROM (
FROM Employees
) AS sub
WHERE RowNum = 8;
Explanation:
m ROW_NUMBER(): It assigns a unique number to each row based on the
specified ordering. In this case, it's ordered by Employee_ID.w
m *SELECT , ROW_NUMBER() OVER (ORDER BY Employee_ID) AS RowNum:
It selects all columns and also calculates the row number using
ROW_NUMBER() function, creating a subquery.w
m WHERE RowNum = 8: It filters out only the row with the desired row
number, in this case, the 8th row.
08 Question
SQL
CREATE TABLE employee (
employee_id INT,
employee_name VARCHAR(255)
);
SQL
FROM employee
UNION Operator:
SQL
UNION
The UNION operator combines the results of two SELECT statements, and
INTERSECT Operator:
SQL
INTERSECT
SQL
WITH cte AS (
FROM employee
FROM cte
The INTERSECT operator returns only the rows that are common to both
SELECT statements, effectively giving us distinct rows.
09 Question
Assuming you have a table named your_table with a primary key column
named id, you can use the following queries:
FROM your_table
WHERE id % 2 = 0;
This query selects all records where the value in the id column is even.
Select All Odd Records:
SQL
SELECT *
FROM your_table
WHERE id % 2 <> 0;
This query selects all records where the value in the id column is odd. The
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT
);
You can have only one clustered index in a table, but a composite index can
be created on multiple columns, allowing for a more complex indexing
structure.
11 Q u e s t i o n
In contrast to a clustered index where data and index are stored together, a
non-clustered index keeps the data and index in separate locations. This
distinction allows for the existence of multiple non-clustered indexes within
a single table.
Consider the following code, which creates a table named "Employee" with
columns such as "EmployeeID," "FirstName," "LastName," and
"DepartmentID." The primary key is set on the "EmployeeID" column. Three
records are inserted into the table, and a non-clustered index named
"NIX_LastName" is established on the "LastName" column in ascending
order.
SQL
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT
);
Employees Table:
101
John
Doe
1
102
Jane
Smith
2
SQL
CREATE TABLE Employee (
EmployeeID INT,
ManagerID INT,
EmployeeName VARCHAR(50)
);
Now, let's use a recursive CTE to retrieve the hierarchy for a specific
manager, starting from the CEO. Suppose we want to find all employees
under Manager2:
SQL
WITH RecursiveCTE AS (
FROM Employee
UNION ALL
FROM Employee e
The base case of the recursive CTE is the SELECT statement before the
UNION ALL. It selects the initial row where EmployeeID is 3 (Manager2).
The recursive part comes after the UNION ALL, where we reference the
CTE (RecursiveCTE) in the SELECT statement and join it with the Employee
table based on the ManagerID and EmployeeID relationship.
The recursive CTE continues to expand until no more rows are selected,
meaning that there are no more employees managed by the current set of
results.
The final SELECT statement outside the CTE retrieves all rows from the
recursive CTE.
In this example, the query will return the hierarchy under Manager2,
RANK():
The RANK() function assigns a unique rank to each distinct row within the
result set.
If two or more rows have the same values, they receive the same rank, and
the next rank is skipped.
After assigning ranks, there may be gaps in the ranking sequence if there
are tied values.
Example:
SQL
SELECT
column1,
column2,
RANK() OVER (ORDER BY column1) AS ranking
FROM
your_table;
DENSE_RANK():
E The DENSE_RANK() function also assigns a unique rank to each distinct
row within the result set.I
E If two or more rows have the same values, they receive the same rank,
but the next rank is not skipped. There are no gaps in the ranking
sequence.I
E This function is useful when you want to avoid gaps in the ranking and
want a continuous sequence.
Example:
SQL
SELECT
column1,
column2,
FROM
your_table;
In both examples, column1 is the column based on which the ranking is
ranking should be determined. You can adjust the ORDER BY clause to rank
column1 column2
10
A
20
B
10
C
30 D
10
A
1
10
C
1
20
B
3
30 D 4
10
A
1
10
C
1
20
B
2
30 D 3
In the RANK() example, there is a gap in the ranking sequence between 3
and 4 because two rows share the same rank. In the DENSE_RANK()
example, there are no gaps in the ranking sequence, and the ranks are
assigned continuously.
14 Question
SQL
CREATE TABLE employees (
employee_name VARCHAR(50)
);
employee_id INT,
salary INT,
);
INSERT INTO employees VALUES (1, 'John');
Now, suppose you want to find employees whose salary is greater than the
average salary for their department. You can use a correlated subquery for
this:
SQL
SELECT
e.employee_id,
e.employee_name,
s.salary
FROM
employees e
JOIN
WHERE
s.salary > (
SELECT AVG(salary)
FROM salaries
);
In this example: The outer query selects employee information from the
The inner query calculates the average salary for a specific employee's
department. Note that it references the employee_id from the outer query
(correlated).
The WHERE clause of the outer query compares each employee's salary
with the average salary for their department, and only returns rows where
Purpose of
To control and run To help with planning,
data fundamental business tasks problem solving, and
decision support
Reveals a snapshot of Multi-dimensional views of
What the data ongoing business processes various kinds of business
activities
Insets and
Short and fast inserts and Periodic long-running batch
Updates updates initiated by end obs refresh the data
Users j
involving aggregations
relatively few records
Depends on the amount of
data involved; batch data
Processing
refreshes and complex
Speed Typically very fast queries may take many
hours; query speed can be
improved by creating
indexes
Larger due to the existence
Space Can be relatively small if of aggregation structures
Requirements historical data is archived and history data; requires
more indexes than OLTP
Backup religiously;
operational data is critical to Instead
some
of regular backups,
environments may
Backup and run the business, data loss is consider simply reloading
Recovery likely to entail significant the OLTP data as a recovery
monetary loss and legal method
liability
16 Question
^[ INSERTED Table:
j The INSERTED table is used in the context of an AFTER INSERT or
INSTEAD OF INSERT trigger.q
j It contains the rows that were inserted or affected by the INSERT
statement that triggered the trigger.q
j The columns in the INSERTED table correspond to the columns in the
table on which the trigger is defined.
[ DELETED Table:
j The DELETED table is used in the context of AFTER UPDATE, AFTER
DELETE, or INSTEAD OF DELETE triggers.q
j It contains the rows that were either updated or deleted by the UPDATE
or DELETE statement that triggered the trigger.q
j The columns in the DELETED table also correspond to the columns in
the table on which the trigger is defined.
These tables allow you to access the old and new values of rows affected
by the triggering operation within the body of the trigger. You can use them
to perform actions based on the changes made to the data, compare values
before and after the operation, or log changes for auditing purposes.
17 Question
SQL
SELECT SUBSTRING(column_name, 1, 5) AS
first_five_chars
FROM your_table;
You can use the SUBSTRING() function to extract a portion of the string.
For example:
LEFT() Function:
The LEFT() function can also be used to retrieve the leftmost characters
from a string:
SQL
FROM your_table;
FROM Customers
In this query:
Customers is the table containing customer information.
Orders is the table containing order information.
Customers.CustomerID and Orders.CustomerID are assumed to
be the columns linking the two tables.
The LEFT JOIN is used to retrieve all records from the Customers table
and the matching records from the Orders table. The WHERE clause filters
out the rows where there is no matching order, meaning customers who
have never placed an order.
19 Question
FROM
sales;
In this example:
+ The SUM function is used with a CASE statement to calculate the total
quantity sold after the specified date. The CASE statement checks if the
average quantity sold after the specified date. Again, the CASE
SELECT e2.employee_name
FROM employees e1
Bosscoder?
750+ Alumni placed at Top
Product-based companies.
Explore More