• SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database

SQL Exercises

  • SQL Concepts and Queries
  • SQL Inner Join
  • SQL - SELECT LAST
  • SQL for Data Science
  • Comparison Operators in SQL
  • SQL Query Interview Questions
  • 7 Best Books for SQL
  • SAP Labs Interview Experience
  • Oracle Interview Experience
  • Shell India Interview Experience
  • DE Shaw Interview Experience
  • TCS NQT Interview Experience
  • Sapient Interview Experience | Set 4
  • Spring Works Interview Experience
  • TCS Ninja Interview Experience
  • Infosys InfyTQ Interview Experience
  • SAP Labs Interview Experience | Set 7

SQL ( Structured Query Language ) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is essential for our skills and language mastery.

In this article, we’ll cover a series of SQL practice exercises covering a wide range of topics suitable for beginners , intermediate , and advanced learners. These exercises are designed to provide hands-on experience with common SQL tasks, from basic retrieval and filtering to more advanced concepts like joins window functions , and stored procedures.

List of SQL Exercises

  • SQL Questions for Practice

SQL Practice Exercises for Beginners

Sql practice exercises for intermediate, sql practice exercises for advanced, more questions for practice, sql exercises for practice.

Practice SQL questions to enhance our skills in database querying and manipulation. Each question covers a different aspect of SQL , providing a comprehensive learning experience.

SQL-Practice-Questions-with-Sollutions

We have covered a wide range of topics in the sections beginner , intermediate and advanced .

  • Basic Retrieval
  • Arithmetic Operations and Comparisons:
  • Aggregation Functions
  • Group By and Having
  • Window Functions
  • Conditional Statements
  • DateTime Operations
  • Creating and Aliasing
  • Constraints
  • Stored Procedures:
  • Transactions

let’s create the table schemas and insert some sample data into them.

Create Sales table

sales_table

Create Products table

Product_Table

This hands-on approach provides a practical environment for beginners to experiment with various SQL commands, gaining confidence through real-world scenarios. By working through these exercises, newcomers can solidify their understanding of fundamental concepts like data retrieval, filtering, and manipulation, laying a strong foundation for their SQL journey.

1. Retrieve all columns from the Sales table.

Explanation: This SQL query selects all columns from the Sales table, denoted by the asterisk (*) wildcard. It retrieves every row and all associated columns from the Sales table.

2. Retrieve the product_name and unit_price from the Products table.

Explanation:

This SQL query selects the product_name and unit_price columns from the Products table. It retrieves every row but only the specified columns, which are product_name and unit_price.

3. Retrieve the sale_id and sale_date from the Sales table.

This SQL query selects the sale_id and sale_date columns from the Sales table. It retrieves every row but only the specified columns, which are sale_id and sale_date.

4. Filter the Sales table to show only sales with a total_price greater than $100.

This SQL query selects all columns from the Sales table but only returns rows where the total_price column is greater than 100. It filters out sales with a total_price less than or equal to $100.

5. Filter the Products table to show only products in the ‘Electronics’ category.

This SQL query selects all columns from the Products table but only returns rows where the category column equals ‘Electronics’. It filters out products that do not belong to the ‘Electronics’ category.

6. Retrieve the sale_id and total_price from the Sales table for sales made on January 3, 2024.

This SQL query selects the sale_id and total_price columns from the Sales table but only returns rows where the sale_date is equal to ‘2024-01-03’. It filters out sales made on any other date.

7. Retrieve the product_id and product_name from the Products table for products with a unit_price greater than $100.

This SQL query selects the product_id and product_name columns from the Products table but only returns rows where the unit_price is greater than $100. It filters out products with a unit_price less than or equal to $100.

8. Calculate the total revenue generated from all sales in the Sales table.

This SQL query calculates the total revenue generated from all sales by summing up the total_price column in the Sales table using the SUM() function.

9. Calculate the average unit_price of products in the Products table.

This SQL query calculates the average unit_price of products by averaging the values in the unit_price column in the Products table using the AVG() function.

10. Calculate the total quantity_sold from the Sales table.

This SQL query calculates the total quantity_sold by summing up the quantity_sold column in the Sales table using the SUM() function.

11. Retrieve the sale_id, product_id, and total_price from the Sales table for sales with a quantity_sold greater than 4.

This SQL query selects the sale_id, product_id, and total_price columns from the Sales table but only returns rows where the quantity_sold is greater than 4.

12. Retrieve the product_name and unit_price from the Products table, ordering the results by unit_price in descending order.

This SQL query selects the product_name and unit_price columns from the Products table and orders the results by unit_price in descending order using the ORDER BY clause with the DESC keyword.

13. Retrieve the total_price of all sales, rounding the values to two decimal places.

This SQL query calculates the total sales revenu by summing up the total_price column in the Sales table and rounds the result to two decimal places using the ROUND() function.

14. Calculate the average total_price of sales in the Sales table.

This SQL query calculates the average total_price of sales by averaging the values in the total_price column in the Sales table using the AVG() function.

15. Retrieve the sale_id and sale_date from the Sales table, formatting the sale_date as ‘YYYY-MM-DD’.

This SQL query selects the sale_id and sale_date columns from the Sales table and formats the sale_date using the DATE_FORMAT() function to display it in ‘YYYY-MM-DD’ format.

16. Calculate the total revenue generated from sales of products in the ‘Electronics’ category.

This SQL query calculates the total revenue generated from sales of products in the ‘Electronics’ category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the ‘Electronics’ category.

17. Retrieve the product_name and unit_price from the Products table, filtering the unit_price to show only values between $20 and $600.

This SQL query selects the product_name and unit_price columns from the Products table but only returns rows where the unit_price falls within the range of $50 and $200 using the BETWEEN operator.

18. Retrieve the product_name and category from the Products table, ordering the results by category in ascending order.

This SQL query selects the product_name and category columns from the Products table and orders the results by category in ascending order using the ORDER BY clause with the ASC keyword.

19. Calculate the total quantity_sold of products in the ‘Electronics’ category.

This SQL query calculates the total quantity_sold of products in the ‘Electronics’ category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the ‘Electronics’ category.

20. Retrieve the product_name and total_price from the Sales table, calculating the total_price as quantity_sold multiplied by unit_price.

This SQL query retrieves the product_name from the Sales table and calculates the total_price by multiplying quantity_sold by unit_price, joining the Sales table with the Products table on the product_id column.

These exercises are designed to challenge you beyond basic queries, delving into more complex data manipulation and analysis. By tackling these problems, you’ll solidify your understanding of advanced SQL concepts like joins, subqueries, functions, and window functions, ultimately boosting your ability to work with real-world data scenarios effectively.

1. Calculate the total revenue generated from sales for each product category.

This query joins the Sales and Products tables on the product_id column, groups the results by product category, and calculates the total revenue for each category by summing up the total_price.

2. Find the product category with the highest average unit price.

This query groups products by category, calculates the average unit price for each category, orders the results by the average unit price in descending order, and selects the top category with the highest average unit price using the LIMIT clause.

3. Identify products with total sales exceeding $500.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and selects products with total sales exceeding 30 using the HAVING clause.

4. Count the number of sales made in each month.

This query formats the sale_date column to extract the month and year, groups the results by month, and counts the number of sales made in each month.

5. Determine the average quantity sold for products with a unit price greater than $100.

This query joins the Sales and Products tables on the product_id column, filters products with a unit price greater than $100, and calculates the average quantity sold for those products.

6. Retrieve the product name and total sales revenue for each product.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, and calculates the total sales revenue for each product.

7. List all sales along with the corresponding product names.

This query joins the Sales and Products tables on the product_id column and retrieves the sale_id and product_name for each sale.

8. Retrieve the product name and total sales revenue for each product.

This query will give you the top three product categories contributing to the highest percentage of total revenue generated from sales. However, if you only have one category (Electronics) as in the provided sample data, it will be the only result.

9. Rank products based on total sales revenue.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and ranks products based on total sales revenue using the RANK () window function.

10. Calculate the running total revenue for each product category.

This query joins the Sales and Products tables on the product_id column, partitions the results by product category, orders the results by sale date, and calculates the running total revenue for each product category using the SUM() window function.

11. Categorize sales as “High”, “Medium”, or “Low” based on total price (e.g., > $200 is High, $100-$200 is Medium, < $100 is Low).

This query categorizes sales based on total price using a CASE statement. Sales with a total price greater than $200 are categorized as “High”, sales with a total price between $100 and $200 are categorized as “Medium”, and sales with a total price less than $100 are categorized as “Low”.

12. Identify sales where the quantity sold is greater than the average quantity sold.

This query selects all sales where the quantity sold is greater than the average quantity sold across all sales in the Sales table.

13. Extract the month and year from the sale date and count the number of sales for each month.

14. calculate the number of days between the current date and the sale date for each sale..

This query calculates the number of days between the current date and the sale date for each sale using the DATEDIFF function.

15. Identify sales made during weekdays versus weekends.

This query categorizes sales based on the day of the week using the DAYOFWEEK function. Sales made on Sunday (1) or Saturday (7) are categorized as “Weekend”, while sales made on other days are categorized as “Weekday”.

This section likely dives deeper into complex queries, delving into advanced features like window functions, self-joins, and intricate data manipulation techniques. By tackling these challenging exercises, users can refine their SQL skills and tackle real-world data analysis scenarios with greater confidence and efficiency.

1. Write a query to create a view named Total_Sales that displays the total sales amount for each product along with their names and categories.

This query creates a view named Total_Sales that displays the total sales amount for each product along with their names and categories.

2. Retrieve the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.

This query retrieves the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.

3. Explain the significance of indexing in SQL databases and provide an example scenario where indexing could significantly improve query performance in the given schema.

With an index on the sale_date column, the database can quickly locate the rows that match the specified date without scanning the entire table. The index allows for efficient lookup of rows based on the sale_date value, resulting in improved query performance.

4. Add a foreign key constraint to the Sales table that references the product_id column in the Products table.

This query adds a foreign key constraint to the Sales table that references the product_id column in the Products table, ensuring referential integrity between the two tables.

5. Create a view named Top_Products that lists the top 3 products based on the total quantity sold.

This query creates a view named Top_Products that lists the top 3 products based on the total quantity sold.

6. Implement a transaction that deducts the quantity sold from the Products table when a sale is made in the Sales table, ensuring that both operations are either committed or rolled back together.

The quantity in stock for product with product_id 101 should be updated to 5.The transaction should be committed successfully.

7. Create a query that lists the product names along with their corresponding sales count.

This query selects the product names from the Products table and counts the number of sales (using the COUNT() function) for each product by joining the Sales table on the product_id. The results are grouped by product name using the GROUP BY clause.

8. Write a query to find all sales where the total price is greater than the average total price of all sales.

The subquery (SELECT AVG(total_price) FROM Sales) calculates the average total price of all sales. The main query selects all columns from the Sales table where the total price is greater than the average total price obtained from the subquery.

9. Analyze the performance implications of indexing the sale_date column in the Sales table, considering the types of queries commonly executed against this column.

By comparing the execution plans and analysis results of these queries, we can evaluate the performance implications of indexing the sale_date column. We’ll be able to observe differences in factors such as the query execution time, the type of scan used (sequential scan vs. index scan), and any additional costs associated with using the index.

10. Add a check constraint to the quantity_sold column in the Sales table to ensure that the quantity sold is always greater than zero.

All rows in the Sales table meet the condition of the check constraint, as each quantity_sold value is greater than zero.

11. Create a view named Product_Sales_Info that displays product details along with the total number of sales made for each product.

This view provides a concise and organized way to view product details alongside their respective sales information, facilitating analysis and reporting tasks.

12. Develop a stored procedure named Update_Unit_Price that updates the unit price of a product in the Products table based on the provided product_id.

The above SQL code creates a stored procedure named Update_Unit_Price. This stored procedure takes two parameters: p_product_id (the product ID for which the unit price needs to be updated) and p_new_price (the new unit price to set).

13. Implement a transaction that inserts a new product into the Products table and then adds a corresponding sale record into the Sales table, ensuring that both operations are either fully completed or fully rolled back.

This will update the unit price of the product with product_id 101 to 550.00 in the Products table.

14. Write a query that calculates the total revenue generated from each category of products for the year 2024.

When you execute this query, you will get the total revenue generated from each category of products for the year 2024.

If you’re looking to sharpen your SQL skills and gain more confidence in querying database s, consider delving into these articles. They’re packed with query-based SQL questions designed to enhance your understanding and proficiency in SQL .

By practicing with these exercises, you’ll not only improve your SQL abilities but also boost your confidence in tackling various database-related tasks. The Questions are as follows:

  • How to Insert a Value that Contains an Apostrophe in SQL?
  • How to Select Row With Max Value in SQL?
  • How to Efficiently Convert Rows to Columns in SQL?
  • How To Use Nested Select Queries in SQL
  • How to Select Row With Max Value on a Column in SQL?
  • How to Specify Condition in Count() in SQL?
  • How to Find the Maximum of Multiple Columns in SQL?
  • How to Update Top 100 Records in SQL?
  • How to Select the Last Records in a One-To-Many Relationship Using SQL Join
  • How to Join First Row in SQL?
  • How to Insert Row If Not Exists in SQL?
  • How to Use GROUP BY to Concatenate Strings in SQL?
  • How Inner Join works in LINQ to SQL
  • How to Get the Identity of an Inserted Row in SQL
  • How to Declare a Variable in SQL?

Mastering SQL requires consistent practice and hands-on experience. By working through these SQL practice exercises , you’ll strengthen your skills and gain confidence in querying relational databases.

Whether you’re just starting or looking to refine your expertise, these exercises provide valuable opportunities to hone your SQL abilities. Keep practicing , and you’ll be well-equipped to tackle real-world data challenges with SQL.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

SQL Tutorial

Sql database, sql references, sql examples, sql exercises.

You can test your SQL skills with W3Schools' Exercises.

We have gathered a variety of SQL exercises (with answers) for each SQL Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start SQL Exercises

Start SQL Exercises ❯

If you don't know SQL, we suggest that you read our SQL Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • SQL Server training
  • Write for us!

Daniel Calbimonte

SQL Practice – common questions and answers for SQL skills

This article will show some important questions and answers to practice SQL.

Introduction

SQL is the base to handle different databases. Even some of the NoSQL databases use an extension of SQL to query data. Data Scientists, BI Analysts, BI Developers, DBAs, Database Developers, Data Engineers, Reporting Analysts, and several other jobs require SQL knowledge as part of the knowledge required. For data management, SQL knowledge is the base to handle databases and the numbers of jobs related to databases are growing each day. The software industry, including databases, is the world’s most in-demand profession. That is why in this article, we will show some questions and answers to practice SQL.

Requirements

In order to start, you need the SQL Server installed and the Adventureworks sample database installed. The following links can help you if you do not have them installed:

  • How to install SQL Server developer edition
  • Install and configure the AdventureWorks2016 sample database

Q1. Please select all the information of persons table that the name starts with A

A1. You will show all the columns with the select * and the where [FirstName] like ‘a%’ will filter the data to all the persons that the name starts with a. The query used is the following:

The LIKE operator is very common in SQL queries. The like ‘a%’ will show all the first names that start with the letter a. There are several other operators that you need to practice like the EXISTS, IN, =, <>, ANY. The following link provides more information about the operators:

  • Operators (Transact-SQL)

Note that the use of * is a bad practice for big tables, but in this case, it is a small table, so it will not impact performance. In general, try to select only the columns required and not all.

Q2. Create a store procedure that receives the first name of the person table as input and the last name as output.

In SQL practice, it is necessary to mention the stored procedures because they are frequently used in SQL Server. The stored procedures are T-SQL sentences that cannot be applied to other databases like Oracle, MySQL, PostgreSQL. The following sample of code shows how to create a stored procedure named GetLastName. It receives the parameter @firstname and returns the last name of the provided firstname. It queries the Person table:

To call the stored procedure using T-SQL, you will need to declare a variable to store the output variable. We use the execute command to call a stored procedure. John is the parameter value for the first name and the last name is the output of the stored procedure:

The result displayed by this store procedure invocation will be something like this:

stored procedure results

For more information about creating stored procedures, please refer to this link:

  • Learn SQL: User-Defined Stored Procedures
  • SQL Server stored procedures for beginners
  • CREATE PROCEDURE (Transact-SQL)

Q3. Which query would you execute to delete all the rows from the person table with minimal bulk-logged activity?

A3. The truncate table sentence removes data without logging individual row deletions. It is the most efficient way to remove all the data. The delete command, on the other hand, logs a lot of data if we have multiple rows and can consume a lot of space in the transaction log files. So, the code will be the following:

Truncate table person.person

To practice SQL, try the truncate and delete statements. For more detailed information about the differences between the truncate and the delete sentences, refer to this link:

  • The internals of SQL Truncate and SQL Delete statements

Q4. Create a query to show the account number and customerid from the customer table for the customer without sales orders.

A4. The query would be something like this:

The result displayed will be something like this:

the use of the left join

We are using the left join to look for all the customers without sales, so the salesorderid will be null. In SQL practice, you need to know the use of the different JOINS like the LEFT JOIN, RIGHT JOIN, CROSS JOIN. We created some articles about the different types of JOINs here. It is very important for you to check, practice, and study all the options:

  • Learn SQL: Join multiple tables
  • Learn SQL: INNER JOIN vs LEFT JOIN
  • SQL CROSS JOIN with examples

We could also use the EXISTS or the IN operators instead of using the JOINS. The performance is different according to the scenario. The performance in queries is out of the scope of this SQL practice. However, we have an entire article about this topic here:

  • How to design SQL queries with better performance: SELECT * and EXISTS vs IN vs JOINs

Q5. You have a table with some of the temperatures in Celsius of some patients. Create a function or a stored procedure to get the convert Fahrenheit to Celsius. Would you use a function or a stored procedure?

A5. Basically, the question here is to create a stored procedure or a function to convert from Celsius to Fahrenheit. If you already have a table with some rows in Celsius, the easiest option is to use a function. The function could be something like this:

Invoking a function is easier than a stored procedure. For more information about the use of functions vs stored procedures, refer to this link:

  • Functions vs stored procedures in SQL Server

Q6. Create a query to show the top 10 customerIDs of users with more Orders.

A6. For this practice test, we will use the TOP 10 to get the customer IDs with more orders. We will use the SUM to SUM the Order Quantity column. Note that for aggregated functions like the SUM, the alias is needed to define the column name in the query. Also, the Sum is grouped by the customer ID. Usually aggregated functions come with the GROUP BY clause. Finally, we are using the order by to order the result in descendant order:

query with the sum, group by and order by including the TOP sentence

For more information about aggregated functions like the SUM, MAX, MIN, AVG, refer to this link:

  • Aggregate Functions (Transact-SQL)

In this article, we show different questions for SQL practice. We show some questions and answers to practice SQL and improve the knowledge. If you have more questions about this topic, do not hesitate to contact us.

  • Recent Posts

Daniel Calbimonte

  • PostgreSQL tutorial to create a user - November 12, 2023
  • PostgreSQL Tutorial for beginners - April 6, 2023
  • PSQL stored procedures overview and examples - February 14, 2023

Related posts:

  • A complete guide to T-SQL Metadata Functions in SQL Server
  • Top SQL Server Books
  • An overview of the SQL Server Update Join
  • FOR XML PATH clause in SQL Server
  • Creating and using CRUD stored procedures

Revising the Select Query I Easy SQL (Basic) Max Score: 10 Success Rate: 95.95%

Revising the select query ii easy sql (basic) max score: 10 success rate: 98.68%, select all easy sql (basic) max score: 10 success rate: 99.53%, select by id easy sql (basic) max score: 10 success rate: 99.66%, japanese cities' attributes easy sql (basic) max score: 10 success rate: 99.59%, japanese cities' names easy sql (basic) max score: 10 success rate: 99.52%, weather observation station 1 easy sql (basic) max score: 15 success rate: 99.41%, weather observation station 3 easy sql (basic) max score: 10 success rate: 97.99%, weather observation station 4 easy sql (basic) max score: 10 success rate: 98.71%, weather observation station 5 easy sql (intermediate) max score: 30 success rate: 94.36%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

41 Essential SQL Interview Questions  *

Toptal sourced essential questions that the best sql developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..

sql tasks and answers

Interview Questions

What does UNION do? What is the difference between UNION and UNION ALL ?

UNION merges the contents of two structurally-compatible tables into a single combined table. The difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records.

It is important to note that the performance of UNION ALL will typically be better than UNION , since UNION requires the server to do the additional work of removing any duplicates. So, in cases where is is certain that there will not be any duplicates, or where having duplicates is not a problem, use of UNION ALL would be recommended for performance reasons.

List and explain the different types of JOIN clauses supported in ANSI-standard SQL.

ANSI-standard SQL specifies five types of JOIN clauses as follows:

INNER JOIN (a.k.a. “simple join”): Returns all rows for which there is at least one match in BOTH tables. This is the default type of join if no specific JOIN type is specified.

LEFT JOIN (or LEFT OUTER JOIN ): Returns all rows from the left table, and the matched rows from the right table; i.e., the results will contain all records from the left table, even if the JOIN condition doesn’t find any matching records in the right table. This means that if the ON clause doesn’t match any records in the right table, the JOIN will still return a row in the result for that record in the left table, but with NULL in each column from the right table.

RIGHT JOIN (or RIGHT OUTER JOIN ): Returns all rows from the right table, and the matched rows from the left table. This is the exact opposite of a LEFT JOIN ; i.e., the results will contain all records from the right table, even if the JOIN condition doesn’t find any matching records in the left table. This means that if the ON clause doesn’t match any records in the left table, the JOIN will still return a row in the result for that record in the right table, but with NULL in each column from the left table.

FULL JOIN (or FULL OUTER JOIN ): Returns all rows for which there is a match in EITHER of the tables. Conceptually, a FULL JOIN combines the effect of applying both a LEFT JOIN and a RIGHT JOIN ; i.e., its result set is equivalent to performing a UNION of the results of left and right outer queries.

CROSS JOIN : Returns all records where each row from the first table is combined with each row from the second table (i.e., returns the Cartesian product of the sets of rows from the joined tables). Note that a CROSS JOIN can either be specified using the CROSS JOIN syntax (“explicit join notation”) or (b) listing the tables in the FROM clause separated by commas without using a WHERE clause to supply join criteria (“implicit join notation”).

Given the following tables:

What will be the result of the query below?

Explain your answer and also provide an alternative version of this query that will avoid the issue that it exposes.

Surprisingly, given the sample data provided, the result of this query will be an empty set. The reason for this is as follows: If the set being evaluated by the SQL NOT IN condition contains any values that are null, then the outer query here will return an empty set, even if there are many runner ids that match winner_ids in the races table.

Knowing this, a query that avoids this issue would be as follows:

Note, this is assuming the standard SQL behavior that you get without modifying the default ANSI_NULLS setting.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance SQL Developer Jobs

Given two tables created and populated as follows:

What will the result be from the following query:

Explain your answer.

The result of the query will be as follows:

The EXISTS clause in the above query is a red herring. It will always be true since ID is not a member of dbo.docs . As such, it will refer to the envelope table comparing itself to itself!

The idnum value of NULL will not be set since the join of NULL will not return a result when attempting a match with any value of envelope .

Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name) .

If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query:

The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever the ‘where’ clause is omitted.

Given two tables created as follows

Write a query to fetch values in table test_a that are and not in test_b without using the NOT keyword.

Note, Oracle does not support the above INSERT syntax, so you would need this instead:

In SQL Server, PostgreSQL, and SQLite, this can be done using the except keyword as follows:

In Oracle, the minus keyword is used instead. Note that if there are multiple columns, say ID and Name, the column should be explicitly stated in Oracle queries: Select ID from test_a minus select ID from test_b

MySQL does not support the except function. However, there is a standard SQL solution that works in all of the above engines, including MySQL:

Write a SQL query to find the 10th highest employee salary from an Employee table. Explain your answer.

(Note: You may assume that there are at least 10 records in the Employee table.)

This can be done as follows:

This works as follows:

First, the SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC query will select the top 10 salaried employees in the table. However, those salaries will be listed in descending order. That was necessary for the first query to work, but now picking the top 1 from that list will give you the highest salary not the the 10th highest salary.

Therefore, the second query reorders the 10 records in ascending order (which the default sort order) and then selects the top record (which will now be the lowest of those 10 salaries).

Not all databases support the TOP keyword. For example, MySQL and PostreSQL use the LIMIT keyword, as follows:

Or even more concisely, in MySQL this can be:

And in PostgreSQL this can be:

Write a SQL query using UNION ALL ( not UNION ) that uses the WHERE clause to eliminate duplicates. Why might you want to do this?

You can avoid duplicates using UNION ALL and still run much faster than UNION DISTINCT (which is actually same as UNION) by running a query like this:

The key is the AND a!=X part. This gives you the benefits of the UNION (a.k.a., UNION DISTINCT ) command, while avoiding much of its performance hit.

Write a query to to get the list of users who took the a training lesson more than once in the same day, grouped by user and training lesson, each ordered from the most recent lesson date to oldest date.

What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL server’s query optimizer for a stored procedure or ad hoc query. Execution plans are very useful for helping a developer understand and analyze the performance characteristics of a query or stored procedure, since the plan is used to execute the query or stored procedure.

In many SQL systems, a textual execution plan can be obtained using a keyword such as EXPLAIN , and visual representations can often be obtained as well. In Microsoft SQL Server, the Query Analyzer has an option called “Show Execution Plan” (located on the Query drop down menu). If this option is turned on, it will display query execution plans in a separate window when a query is run.

List and explain each of the ACID properties that collectively guarantee that database transactions are processed reliably.

ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably. They are defined as follows:

  • Atomicity. Atomicity requires that each transaction be “all or nothing”: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes.
  • Consistency. The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof.
  • Isolation. The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially, i.e., one after the other. Providing isolation is the main goal of concurrency control. Depending on concurrency control method (i.e. if it uses strict - as opposed to relaxed - serializability), the effects of an incomplete transaction might not even be visible to another transaction.
  • Durability. Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter). To defend against power loss, transactions (or their effects) must be recorded in a non-volatile memory.

Given a table dbo.users where the column user_id is a unique numeric identifier, how can you efficiently select the first 100 odd user_id values from the table?

(Assume the table contains well over 100 records with odd user_id values.)

SELECT TOP 100 user_id FROM dbo.users WHERE user_id % 2 = 1 ORDER BY user_id

What are the NVL and the NVL2 functions in SQL? How do they differ?

Both the NVL(exp1, exp2) and NVL2(exp1, exp2, exp3) functions check the value exp1 to see if it is null.

With the NVL(exp1, exp2) function, if exp1 is not null, then the value of exp1 is returned; otherwise, the value of exp2 is returned, but case to the same data type as that of exp1 .

With the NVL2(exp1, exp2, exp3) function, if exp1 is not null, then exp2 is returned; otherwise, the value of exp3 is returned.

How can you select all the even number records from a table? All the odd number records?

To select all the even number records from a table:

To select all the odd number records from a table:

What is the difference between the RANK() and DENSE_RANK() functions? Provide an example.

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100} . For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4} .

What is the difference between the WHERE and HAVING clauses?

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

  • The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
  • The HAVING clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).

Given a table Employee having columns empName and empId , what will be the result of the SQL query below?

“Order by 2” is only valid when there are at least two columns being used in select statement. However, in this query, even though the Employee table has 2 columns, the query is only selecting 1 column name, so “Order by 2” will cause the statement to throw an error while executing the above sql query.

What will be the output of the below query, given an Employee table having 10 records?

This query will return 10 records as TRUNCATE was executed in the transaction. TRUNCATE does not itself keep a log but BEGIN TRANSACTION keeps track of the TRUNCATE command.

  • What is the difference between single-row functions and multiple-row functions?
  • What is the group by clause used for?
  • Single-row functions work with single row at a time. Multiple-row functions work with data of multiple rows at a time.
  • The group by clause combines all those records that have identical values in a particular field or any group of fields.

Imagine a single column in a table that is populated with either a single digit (0-9) or a single character (a-z, A-Z). Write a SQL query to print ‘Fizz’ for a numeric value or ‘Buzz’ for alphabetical value for all values in that column.

['d', 'x', 'T', 8, 'a', 9, 6, 2, 'V']

…should output:

['Buzz', 'Buzz', 'Buzz', 'Fizz', 'Buzz','Fizz', 'Fizz', 'Fizz', 'Buzz']

What is the difference between char and varchar2 ?

When stored in a database, varchar2 uses only the allocated space. E.g. if you have a varchar2(1999) and put 50 bytes in the table, it will use 52 bytes.

But when stored in a database, char always uses the maximum length and is blank-padded. E.g. if you have char(1999) and put 50 bytes in the table, it will consume 2000 bytes.

Write an SQL query to display the text CAPONE as:

Or in other words, an SQL query to transpose text.

In Oracle SQL, this can be done as follows:

Can we insert a row for identity column implicitly?

Yes, like so:

Given this table:

What will be the output of below snippet?

Table is as follows:

Print the rows which have ‘Yellow’ in one of the columns C1, C2, or C3, but without using OR .

Write a query to insert/update Col2 ’s values to look exactly opposite to Col1 ’s values.

Or if the type is numeric:

How do you get the last id without the max function?

In SQL Server:

What is the difference between IN and EXISTS ?

  • Works on List result set
  • Doesn’t work on subqueries resulting in Virtual tables with multiple columns
  • Compares every value in the result list
  • Performance is comparatively SLOW for larger resultset of subquery
  • Works on Virtual tables
  • Is used with co-related queries
  • Exits comparison when match is found
  • Performance is comparatively FAST for larger resultset of subquery

Suppose in a table, seven records are there.

The column is an identity column.

Now the client wants to insert a record after the identity value 7 with its identity value starting from 10 .

Is it possible? If so, how? If not, why not?

Yes, it is possible, using a DBCC command:

How can you use a CTE to return the fifth highest (or Nth highest) salary from a table?

Given the following table named A :

Write a single query to calculate the sum of all positive values of x and he sum of all negative values of x .

Given the table mass_table :

Write a query that produces the output:

Consider the Employee table below.

Write a query to generate below output:

How do you copy data from one table to another table ?

Find the SQL statement below that is equal to the following: SELECT name FROM customer WHERE state = 'VA';

  • SELECT name IN customer WHERE state IN ('VA');
  • SELECT name IN customer WHERE state = 'VA';
  • SELECT name IN customer WHERE state = 'V';
  • SELECT name FROM customer WHERE state IN ('VA');

Given these contents of the Customers table:

Here is a query written to return the list of customers not referred by Jane Smith:

What will be the result of the query? Why? What would be a better way to write it?

Although there are 4 customers not referred by Jane Smith (including Jane Smith herself), the query will only return one: Pat Richards. All the customers who were referred by nobody at all (and therefore have NULL in their ReferredBy column) don’t show up. But certainly those customers weren’t referred by Jane Smith, and certainly NULL is not equal to 2, so why didn’t they show up?

SQL Server uses three-valued logic, which can be troublesome for programmers accustomed to the more satisfying two-valued logic (TRUE or FALSE) most programming languages use. In most languages, if you were presented with two predicates: ReferredBy = 2 and ReferredBy <> 2, you would expect one of them to be true and one of them to be false, given the same value of ReferredBy. In SQL Server, however, if ReferredBy is NULL, neither of them are true and neither of them are false. Anything compared to NULL evaluates to the third value in three-valued logic: UNKNOWN.

The query should be written in one of two ways:

Watch out for the following, though!

This will return the same faulty set as the original. Why? We already covered that: Anything compared to NULL evaluates to the third value in the three-valued logic: UNKNOWN. That “anything” includes NULL itself! That’s why SQL Server provides the IS NULL and IS NOT NULL operators to specifically check for NULL. Those particular operators will always evaluate to true or false.

Even if a candidate doesn’t have a great amount of experience with SQL Server, diving into the intricacies of three-valued logic in general can give a good indication of whether they have the ability learn it quickly or whether they will struggle with it.

Given a table TBL with a field Nmbr that has rows with the following values:

1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1

Write a query to add 2 where Nmbr is 0 and add 3 where Nmbr is 1.

Suppose we have a Customer table containing the following data:

Write a single SQL statement to concatenate all the customer names into the following single semicolon-separated string:

This is close, but will have an undesired trailing ; . One way of fixing that could be:

In PostgreSQL one can also use this syntax to achieve the fully correct result:

How do you get the Nth-highest salary from the Employee table without a subquery or CTE?

This will give the third-highest salary from the Employee table. Accordingly we can find out Nth salary using LIMIT (N-1),1 .

But MS SQL Server doesn’t support that syntax, so in that case:

OFFSET ’s parameter corresponds to the (N-1) above.

How to find a duplicate record?

duplicate records with one field

duplicate records with more than one field

Considering the database schema displayed in the SQLServer-style diagram below, write a SQL query to return a list of all the invoices. For each invoice, show the Invoice ID, the billing date, the customer’s name, and the name of the customer who referred that customer (if any). The list should be ordered by billing date.

sql tasks and answers

This question simply tests the candidate’s ability take a plain-English requirement and write a corresponding SQL query. There is nothing tricky in this one, it just covers the basics:

Did the candidate remember to use a LEFT JOIN instead of an inner JOIN when joining the customer table for the referring customer name? If not, any invoices by customers not referred by somebody will be left out altogether.

Did the candidate alias the tables in the JOIN? Most experienced T-SQL programmers always do this, because repeating the full table name each time it needs to be referenced gets tedious quickly. In this case, the query would actually break if at least the Customer table wasn’t aliased, because it is referenced twice in different contexts (once as the table which contains the name of the invoiced customer, and once as the table which contains the name of the referring customer).

Did the candidate disambiguate the Id and Name columns in the SELECT? Again, this is something most experienced programmers do automatically, whether or not there would be a conflict. And again, in this case there would be a conflict, so the query would break if the candidate neglected to do so.

Note that this query will not return Invoices that do not have an associated Customer. This may be the correct behavior for most cases (e.g., it is guaranteed that every Invoice is associated with a Customer, or unmatched Invoices are not of interest). However, in order to guarantee that all Invoices are returned no matter what, the Invoices table should be joined with Customers using LEFT JOIN:

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of SQL Developers

Looking to land a job as a SQL Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for SQL Developers?

Looking for SQL Developers ? Check out Toptal’s SQL developers.

Jeremy Barrio, SQL Engineer.

Jeremy Barrio

Jeremy is a Microsoft SQL Server database administrator and T-SQL developer offering nearly 15 years of experience working with SQL Server 2008-2019, developing T-SQL queries and stored procedures, managing database-related projects, monitoring and optimizing databases, and developing and maintaining recurring automated processes using SQL jobs, SSIS, and PowerShell. Jeremy enjoys learning new technologies and excels with replication, HA/DR, and clustering.

Rajib Baruah, Accomplished SQL Freelancer.

Rajib Baruah

Rajib is a senior data engineer with 23 years of experience in T-SQL coding and building SQL Server databases, ETL data pipelines in the Azure cloud using ADF, or on-premises software using SQL Server Integration Services (SSIS) to ingest data and processes. An expert in coding using Python and PySpark, he creates notebooks in Databricks for data transformation and load. With his extensive experience, Rajib will be an excellent addition to any team.

Pedro Correia, Toptal SQL Developer.

Pedro Correia

Pedro has been working with Microsoft technologies since the early days of MS-DOS and GW-BASIC when he became fascinated with DBMS and used SQL Server 6.5 for the first time. During the last 20 years, he's implemented numerous web and Windows solutions in .NET, using SQL Server on the back end. Also, he taught several official Microsoft courses where he shared his expertise in the field. In one sentence, Pedro is eager to learn, inspired by challenges, and motivated to share.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

Python and Excel Projects for practice

SQL EXERCISES

  • 30 Exercises: agregate functions, order, group by, having , boolean, joins.
  • 14 Exercises: select, filtering, scalar functions, group by, joins, subquery, tables, DDL.
  • Beginner – Intermediate
  • 400 Exercises: sql queries, filtering, sorting, multiple tables, joins, subqueries.
  • 140 Exercises
  • 40 Exercises: select, variables, subqueries, joins, aggregation, data modification.
  • 100 Exercises
  • 20 Exercises: select, sum, count, joins, nulls.
  • 20 Exercises/projects/challenges
  • Intermediate
  • 60 Exercises: multiple tables queries.
  • 50 Exercises
  • 1 Challenge: Football World Cup 2014
  • 27 Practice exams: databases
  • 16 Skills evaluation tests
  • 7 Evaluation questions
  • 45 Interview questions
  • 20 Interview questions. 10 Exercises
  • 4 Exercises & Mock  interview questions: joins and sub queries.
  • 50 Theory questions
  • 15 Theory questions: MySQL certification
  • Challenge & Quiz
  • Intermediate – Advanced
  • 50 Exercises: multiple table queries
  • 10 Exercises: subqueries, joins.
  • Beginner – Intermediate – Advanced
  • 190 Exercises
  • 30 Exercises/Labs
  • 20 Challenges
  • 12 SQL Server Developer questions.

facebook_logo

Terms of Use

Python and Excel Projects for practice

Shopping cart

Codility Logo

Access block

In line with applicable trade sanctions and embargo requirements, Codility (like other similar organizations) does not support access to our products to users located in countries and regions on the United States Treasury’s list of Embargoed and Sanctioned Countries . Codility is committed to compliance with these sanctions and has blocked usage of our products in these countries and regions.

What happens while you’re in a country or region with restricted access? If you are trying to access our products from a restricted country or region, you will be unable to and your access will be blocked for as long as you are in a sanctioned country or region.

What can you do to gain access? These restrictions only apply if you attempt to access Codility from one of these countries or regions. To regain access to Codility, you’ll need to access our products from outside of the restricted location.

What if you’re trying to access Codility as part of a recruitment process? If you have been invited to take a screening assessment or participate in a technical interview as part of a recruitment process with a Codility customer, please contact your Recruiter to inform them that you are unable to access Codility.

What if your access is blocked, but you’re not in a restricted country or region? If you feel there is a mistake please contact [email protected]

logo

Practice Interview Questions

Get 1:1 Coaching

20 Advanced SQL Interview Questions (With Answers!)

By Nick Singh

(Ex-Facebook & Best-Selling Data Science Author)

Currently, he’s the best-selling author of Ace the Data Science Interview, and Founder & CEO of DataLemur.

Nick Singh with book

March 25, 2024

Looking to ace your next SQL interview with confidence? Test yourself with these 20 advanced SQL interview questions, each accompanied by detailed answers to help you impress recruiters and land that dream job. These questions cover everything from complex queries to data manipulation and optimization techniques, and equip you with the knowledge you need to excel in any SQL interview scenario.

How many questions can you solve?

Advanced SQL Interview Questions

Advanced SQL Interview Questions

Interview questions that test practical and conceptual SQL skills are to test the candidate's ability to translate knowledge into effective solutions. The following questions are 20 SQL interview questions pulled from REAL interviews, that helped managers assess candidates' SQL skills.

While we have included sample answers for each question, remember that these are not the only correct answers. There are often multiple ways to achieve the same goal. Focus on writing clean and functional code.

1. Repeated Payments [Stripe SQL Interview Question]

Stripe asked this tricky SQL interview question, about identifying any payments made at the same merchant with the same credit card for the same amount within 10 minutes of each other and reporting the count of such repeated payments.

Input/Output Data

Example Input:

Example Output:

Stripe SQL Interview Questions

You can solve this Stripe SQL problem interactively and get a full solution explanation:

Stripe SQL Interview Question

2. Describe how recursive queries work in SQL. Provide an example scenario where a recursive query would be beneficial.

Recursive queries in SQL enable iteration over hierarchical data structures like organizational charts, bill-of-materials, or nested comments. For example, you could use a recursive query to traverse a hierarchical data structure and retrieve all descendants of a specific node.

3. Median Google Search Frequency [Google SQL Interview Question]

Google’s Marketing Team needed to add a simple statistic to their upcoming Superbowl Ad: the median number of searches made per year. You were given a summary table that tells you the number of searches made last year, write a query to report the median searches made per user.

Input/Output Data:

You can solve this Google SQL problem interactively, and get the full solution explanation .

Enjoyed this one? p.s. here's more Google SQL Interview Questions to practice!

4. What are ACID properties in SQL?

ACID properties are:

  • Atomicity: Changes in the data must be like a single operation.
  • Consistency: The data must be consistent before and after the transaction.
  • Isolation: Multiple transactions can be done without any hindrance.
  • Durability: Transaction gets successful in case of system failures.

ACID Properties

5. Monthly Merchant Balance [Visa SQL Interview Question]

Say you have access to all the transactions for a given merchant account. Write a query to print the cumulative balance of the merchant account at the end of each day, with the total balance reset back to zero at the end of the month. Output the transaction date and cumulative balance.

You can solve this Visa SQL problem interactively, and get the full solution explanation .

6. Explain the concept of correlated subqueries in SQL. Can you provide an example of how you can use them?

Correlated subqueries are executed once for each row of the outer query and depend on the outer query for results. For example, you could use a correlated subquery to retrieve data from one table according to conditions in a separate table.

7. Server Utilization Time [Amazon SQL Interview Question]

Fleets of servers power Amazon Web Services (AWS). Senior management has requested data-driven solutions to optimize server usage.

Write a query that calculates the total time that the fleet of servers was running. The output should be in units of full days .

Assumptions:

  • Each server might start and stop several times.
  • The total time in which the server fleet is running can be calculated as the sum of each server's uptime.

You can solve this Amazon SQL problem interactively, and get the full solution explanation .

Looking for more Amazon SQL Interview Questions? Check out our Amazon SQL Interview Guide for access to even more questions and solutions!

8. Explain how indexing works in a relational database. What are the benefits and potential drawbacks of indexing?

Indexing in a relational database involves creating data structures (indexes) that allow for faster data retrieval by providing direct access to rows based on the indexed columns. The benefits of indexing include improved query performance and faster data retrieval, especially for large datasets. However, indexing can also introduce overhead during data modification operations (such as INSERT, UPDATE, and DELETE) and increased storage requirements.

9. Uniquely Staffed Consultants [Accenture SQL Interview Questions]

As a Data Analyst on the People Operations team at Accenture, you are tasked with understanding how many consultants are staffed to each client, and how many consultants are exclusively staffed to a single client.

Write a query that displays the outputs of client name and the number of uniquely and exclusively staffed consultants ordered by client name.

You can solve this Accenture SQL problem interactively, and get the full solution explanation .

10. Compare and contrast stored procedures and user-defined functions in SQL. When would you choose to use one over the other?

Stored procedures and user-defined functions (UDFs) are both reusable pieces of code in SQL, but they have some key differences. Stored procedures can perform DML operations and transaction management, while UDFs are limited to returning values and cannot perform DML operations. Stored procedures are typically used for procedural tasks and complex business logic, while UDFs are often used for calculations and data transformations.

11. Event Friends Recommendation [Facebook SQL Interview Questions]

Facebook wants to recommend new friends to people who show interest in attending 2 or more of the same private events.

Sort your results in order of user_a_id and user_b_id (refer to the Example Output below). Table:

Each row of this table indicates the status of the friendship between user_a_id and user_b_id.

Users 222 and 333 who are not friends have shown interest in attending 2 or more of the same private events.

Facebook SQL Interview Questions

You can solve this Facebook SQL problem interactively, and get the full solution explanation .

Looking for more Facebook SQL Interview Questions? Check out our Facebook SQL Interview Guide for access to even more questions and solutions!

12. Explain the purpose of the MERGE statement in SQL. Provide an example.

The MERGE statement performs INSERT, UPDATE, or DELETE operations on a target table based on the results of a join with a source table.

13. 3-Topping Pizzas [McKinsey SQL Interview Question]

You’re a consultant for a major pizza chain that will be running a promotion where all 3-topping pizzas will be sold for a fixed price, and are trying to understand the costs involved.

Given a list of pizza toppings, consider all the possible 3-topping pizzas, and print out the total cost of those 3 toppings. Sort the results with the highest total cost on the top followed by pizza toppings in ascending order.

Break ties by listing the ingredients in alphabetical order, starting from the first ingredient, followed by the second and third.

** Table:**

McKinsey SQL Interview Questions

You can solve this McKinsey SQL problem interactively AND see alternate solutions, and get the full solution explanation .

14. Describe the differences between clustered and non-clustered indexes in SQL.

A clustered index determines the physical order of data in a table, while a non-clustered index does not. A table can have only one clustered index but multiple non-clustered indexes.

15. Follow-Up Airpod Percentage [Apple SQL Interview Questions]

The Apple retention team needs your help to investigate buying patterns. Write a query to determine the percentage of buyers who bought AirPods directly after they bought iPhones. Round your answer to a percentage (i.e. 20 for 20%, 50 for 50) with no decimals.

You can solve this Apple SQL problem interactively, and get the full solution explanation .

Looking for more Apple SQL Interview Questions? Check out our Apple SQL Interview Guide for access to even more questions and solutions!

16. What is the purpose of the LAG and LEAD functions in SQL? Provide an example.

The LAG and LEAD functions allow accessing data from previous or subsequent rows in a result set.

17. Marketing Touch Streak [Snowflake SQL Interview Question]

As a Data Analyst on Snowflake's Marketing Analytics team, your objective is to analyze customer relationship management (CRM) data and identify contacts that satisfy two conditions:

  • Contacts who had a marketing touch for three or more consecutive weeks.
  • Contacts who had at least one marketing touch of the type 'trial_request'.

Marketing touches, also known as touch points, represent the interactions or points of contact between a brand and its customers.

Your goal is to generate a list of email addresses for these contacts.

You can solve this Snowflake SQL problem interactively, and get the full solution explanation .

Looking for more Snowflake SQL Interview Questions? Check out these 10 Snowflake SQL Interview Questions for access to even more questions and solutions!

18. Explain the purpose of the TRUNCATE statement in SQL. How is it different from DELETE?

The TRUNCATE statement removes all rows from a table but does not log individual row deletions, making it faster than DELETE, which removes rows one by one and logs each deletion. However, TRUNCATE cannot be rolled back, and it resets identity columns.

19. Bad Delivery Rate [DoorDash SQL Interview Question]

The Growth Team at DoorDash wants to ensure that new users, who make orders within their first 14 days on the platform, have a positive experience. However, they have noticed several issues with deliveries that result in a bad experience.

These issues include:

  • Orders being completed incorrectly, with missing items or wrong orders.
  • Orders not being received due to incorrect addresses or drop-off spots.
  • Orders being delivered late, with the actual delivery time being 30 minutes later than the order placement time. Note that the is automatically set to 30 minutes after the .

Write a query that calculates the bad experience rate for new users who signed up in June 2022 during their first 14 days on the platform. The output should include the percentage of bad experiences, rounded to 2 decimal places. Table:

You can solve this DoorDash SQL problem interactively, and get the full solution explanation .

Looking for more DoorDash SQL Interview Questions? Check out these 8 DoorDash SQL Interview Questions for access to even more questions and solutions!

20. Describe the difference between a view and a materialized view in SQL.

A view is a virtual table based on the result of a SELECT query, while a materialized view is a physical copy of the result set of a query that is stored and updated periodically.

SQL Interview Tips

The best way to prepare for the SQL interview is to practice, practice, practice. Besides solving the earlier SQL interview questions, you should also solve the 200+ SQL coding questions which come from companies like FAANG tech companies and tech startups.

DataLemur Questions

Each exercise has hints to guide you, step-by-step solutions and best of all, there is an interactive coding environment so you can right online code up your SQL query and have it checked. However, if your SQL skills are weak, forget about going right into solving questions – refresh your SQL knowledge with this DataLemur SQL Tutorial .

SQL tutorial for Data Scientists & Analysts

Data Science Interview Tips

To prepare for the Data Science interviews read the book Ace the Data Science Interview because it's got:

  • 201 Interview Questions from Facebook, Google & startups
  • A Crash Course covering Product Analytics, SQL & ML
  • Amazing Reviews (900+ 5-star reviews on Amazon)

Ace the Data Science Interview Book on Amazon

Interview Questions

Career resources.

Download Interview guide PDF

Sql interview questions, download pdf.

sql tasks and answers

Are you preparing for your SQL developer interview?

Then you have come to the right place.

This guide will help you to brush up on your SQL skills, regain your confidence and be job-ready!

Here, you will find a collection of real-world Interview questions asked in companies like Google, Oracle, Amazon, and Microsoft, etc. Each question comes with a perfectly written answer inline, saving your interview preparation time.

It also covers practice problems to help you understand the basic concepts of SQL .

We've divided this article into the following sections:

PostgreSQL Interview Questions

In the end, multiple-choice questions are provided to test your understanding.

1. What is Database?

A database is an organized collection of data, stored and retrieved digitally from a remote or local computer system. Databases can be vast and complex, and such databases are developed using fixed design and modeling approaches.

2. What is DBMS?

DBMS stands for Database Management System. DBMS is a system software responsible for the creation, retrieval, updation, and management of the database. It ensures that our data is consistent, organized, and is easily accessible by serving as an interface between the database and its end-users or application software.

3. What is RDBMS? How is it different from DBMS?

RDBMS stands for Relational Database Management System. The key difference here , compared to DBMS, is that RDBMS stores data in the form of a collection of tables, and relations can be defined between the common fields of these tables. Most modern database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and Amazon Redshift are based on RDBMS.

sql tasks and answers

4. What is SQL?

SQL stands for Structured Query Language. It is the standard language for relational database management systems. It is especially useful in handling organized data comprised of entities (variables) and relations between different entities of the data.

5. What is the difference between SQL and MySQL?

SQL is a standard language for retrieving and manipulating structured databases. On the contrary, MySQL is a relational database management system, like SQL Server, Oracle or IBM DB2, that is used to manage SQL databases.

sql tasks and answers

Learn via our Video Courses

6. what are tables and fields.

A table is an organized collection of data stored in the form of rows and columns. Columns can be categorized as vertical and rows as horizontal. The columns in a table are called fields while the rows can be referred to as records.

7. What are Constraints in SQL?

Constraints are used to specify the rules concerning data in the table. It can be applied for single or multiple fields in an SQL table during the creation of the table or after creating using the ALTER TABLE command. The constraints are:

  • NOT NULL - Restricts NULL value from being inserted into a column.
  • CHECK - Verifies that all values in a field satisfy a condition.
  • DEFAULT - Automatically assigns a default value if no value has been specified for the field.
  • UNIQUE - Ensures unique values to be inserted into the field.
  • INDEX - Indexes a field providing faster retrieval of records.
  • PRIMARY KEY - Uniquely identifies each record in a table.
  • FOREIGN KEY - Ensures referential integrity for a record in another table.

8. What is a Primary Key?

The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint. A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).

write a sql statement to add primary key 't_id' to the table 'teachers'.

Write a sql statement to add primary key constraint 'pk_a' for table 'table_a' and fields 'col_b, col_c'., 9. what is a unique constraint.

A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined per table. The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.

10. What is a Foreign Key?

A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to the PRIMARY KEY in another table. Foreign key constraint ensures referential integrity in the relation between two tables. The table with the foreign key constraint is labeled as the child table, and the table containing the candidate key is labeled as the referenced or parent table.

What type of integrity constraint does the foreign key ensure?

Write a sql statement to add a foreign key 'col_fk' in 'table_y' that references 'col_pk' in 'table_x'., 11. what is a join list its different types..

The SQL Join clause is used to combine records (rows) from two or more tables in a SQL database based on a related column between the two.

sql tasks and answers

There are four different types of JOINs in SQL:

  • (INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is the widely used join for queries.
  • LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from the right table.
  • RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows from the left table.
  • FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table.

12. What is a Self-Join?

A self JOIN is a case of regular join where a table is joined to itself based on some relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign different names to the table within the query.

13. What is a Cross-Join?

Cross join can be defined as a cartesian product of the two tables included in the join. The table after join contains the same number of rows as in the cross-product of the number of rows in the two tables. If a WHERE clause is used in cross join then the query will work like an INNER JOIN.

sql tasks and answers

Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from table_1 & 'col_2' from table_2 respectively. Do not use alias.

Write a sql statement to perform self join for 'table_x' with alias 'table_1' and 'table_2', on columns 'col_1' and 'col_2' respectively., 14. what is an index explain its different types..

A database index is a data structure that provides a quick lookup of data in a column or columns of a table. It enhances the speed of operations accessing data from a database table at the cost of additional writes and memory to maintain the index data structure.

There are different types of indexes that can be created for different purposes:

  • Unique and Non-Unique Index:

Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a table have identical key values. Once a unique index has been defined for a table, uniqueness is enforced whenever keys are added or changed within the index.

Non-unique indexes, on the other hand, are not used to enforce constraints on the tables with which they are associated. Instead, non-unique indexes are used solely to improve query performance by maintaining a sorted order of data values that are used frequently.

  • Clustered and Non-Clustered Index:

Clustered indexes are indexes whose order of the rows in the database corresponds to the order of the rows in the index. This is why only one clustered index can exist in a given table, whereas, multiple non-clustered indexes can exist in the table.

The only difference between clustered and non-clustered indexes is that the database manager attempts to keep the data in the database in the same order as the corresponding keys appear in the clustered index.

Clustering indexes can improve the performance of most query operations because they provide a linear-access path to data stored in the database.

Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields "column_1" & "column_2".

15. what is the difference between clustered and non-clustered index.

As explained above, the differences can be broken down into three small factors -

  • Clustered index modifies the way records are stored in a database based on the indexed column. A non-clustered index creates a separate entity within the table which references the original table.
  • Clustered index is used for easy and speedy retrieval of data from the database, whereas, fetching records from the non-clustered index is relatively slower.
  • In SQL, a table can have a single clustered index whereas it can have multiple non-clustered indexes.

16. What is Data Integrity?

Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle and is a critical aspect of the design, implementation, and usage of any system which stores, processes, or retrieves data. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.

17. What is a Query?

A query is a request for data or information from a database table or combination of tables. A database query can be either a select query or an action query.

18. What is a Subquery? What are its types?

A subquery is a query within another query, also known as a nested query or inner query . It is used to restrict or enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query respectively. For example, here we fetch the contact information for students who have enrolled for the maths subject:

There are two types of subquery - Correlated and Non-Correlated .

  • A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table listed in the FROM of the main query.
  • A non-correlated subquery can be considered as an independent query and the output of the subquery is substituted in the main query.

Write a SQL query to update the field "status" in table "applications" from 0 to 1.

Write a sql query to select the field "app_id" in table "applications" where "app_id" less than 1000., write a sql query to fetch the field "app_name" from "apps" where "apps.id" is equal to the above collection of "app_id"., 19. what is the select statement.

SELECT operator in SQL is used to select data from a database. The data returned is stored in a result table, called the result-set.

20. What are some common clauses used with SELECT query in SQL?

Some common SQL clauses used in conjuction with a SELECT query are as follows:

  • WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.
  • ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending ( ASC ) or descending order ( DESC) .
  • GROUP BY clause in SQL is used to group records with identical data and can be used in conjunction with some aggregation functions to produce summarized results from the database.
  • HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is different from WHERE, since the WHERE clause cannot filter aggregated records.

21. What are UNION, MINUS and INTERSECT commands?

The UNION operator combines and returns the result-set retrieved by two or more SELECT statements. The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second SELECT query from the result-set obtained by the first SELECT query and then return the filtered results from the first. The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where records from one match the other and then returns this intersection of result-sets.

Certain conditions need to be met before executing either of the above statements in SQL -

  • Each SELECT statement within the clause must have the same number of columns
  • The columns must also have similar data types
  • The columns in each SELECT statement should necessarily have the same order

Write a SQL query to fetch "names" that are present in either table "accounts" or in table "registry".

Write a sql query to fetch "names" that are present in "accounts" but not in table "registry"., write a sql query to fetch "names" from table "contacts" that are neither present in "accounts.name" nor in "registry.name"., 22. what is cursor how to use a cursor.

A database cursor is a control structure that allows for the traversal of records in a database. Cursors, in addition, facilitates processing after traversal, such as retrieval, addition, and deletion of database records. They can be viewed as a pointer to one row in a set of rows.

Working with SQL Cursor:

  • DECLARE a cursor after any variable declaration. The cursor declaration must always be associated with a SELECT Statement.
  • Open cursor to initialize the result set. The OPEN statement must be called before fetching rows from the result set.
  • FETCH statement to retrieve and move to the next row in the result set.
  • Call the CLOSE statement to deactivate the cursor.
  • Finally use the DEALLOCATE statement to delete the cursor definition and release the associated resources.

23. What are Entities and Relationships?

Entity : An entity can be a real-world object, either tangible or intangible, that can be easily identifiable. For example, in a college database, students, professors, workers, departments, and projects can be referred to as entities. Each entity has some associated properties that provide it an identity.

Relationships : Relations or links between entities that have something to do with each other. For example - The employee's table in a company's database can be associated with the salary table in the same database.

sql tasks and answers

24. List the different types of relationships in SQL.

  • One-to-One - This can be defined as the relationship between two tables where each record in one table is associated with the maximum of one record in the other table.
  • One-to-Many & Many-to-One - This is the most commonly used relationship where a record in a table is associated with multiple records in the other table.
  • Many-to-Many - This is used in cases when multiple instances on both sides are needed for defining a relationship.
  • Self-Referencing Relationships - This is used when a table needs to define a relationship with itself.

25. What is an Alias in SQL?

An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a temporary name assigned to the table or table column for the purpose of a particular SQL query. In addition, aliasing can be employed as an obfuscation technique to secure the real names of database fields. A table alias is also called a correlation name.

An alias is represented explicitly by the AS keyword but in some cases, the same can be performed without it as well. Nevertheless, using the AS keyword is always a good practice.

Write an SQL statement to select all from table "Limited" with alias "Ltd".

26. what is a view.

A view in SQL is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

sql tasks and answers

27. What is Normalization?

Normalization represents the way of organizing structured data in the database efficiently. It includes the creation of tables, establishing relationships between them, and defining rules for those relationships. Inconsistency and redundancy can be kept in check based on these rules, hence, adding flexibility to the database.

28. What is Denormalization?

Denormalization is the inverse process of normalization, where the normalized schema is converted into a schema that has redundant information. The performance is improved by using redundancy and keeping the redundant data consistent. The reason for performing denormalization is the overheads produced in the query processor by an over-normalized structure.

29. What are the various forms of Normalization?

Normal Forms are used to eliminate or reduce redundancy in database tables. The different forms are as follows:

  • First Normal Form: A relation is in first normal form if every attribute in that relation is a single-valued attribute . If a relation contains a composite or multi-valued attribute, it violates the first normal form. Let's consider the following students table. Each student in the table, has a name, his/her address, and the books they issued from the public library -

Students Table

As we can observe, the Books Issued field has more than one value per record, and to convert it into 1NF, this has to be resolved into separate individual records for each book issued. Check the following table in 1NF form -

Students Table (1st Normal Form)

  • Second Normal Form:

A relation is in second normal form if it satisfies the conditions for the first normal form and does not contain any partial dependency. A relation in 2NF has no partial dependency , i.e., it has no non-prime attribute that depends on any proper subset of any candidate key of the table. Often, specifying a single column Primary Key is the solution to the problem. Examples -

Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF form has a candidate key in the form of [Student, Address] that can uniquely identify all records in the table. The field Books Issued (non-prime attribute) depends partially on the Student field. Hence, the table is not in 2NF. To convert it into the 2nd Normal Form, we will partition the tables into two while specifying a new Primary Key attribute to identify the individual records in the Students table. The Foreign Key constraint will be set on the other table to ensure referential integrity.

Students Table (2nd Normal Form)

Books Table (2nd Normal Form)

Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)

Here, WX is the only candidate key and there is no partial dependency, i.e., any proper subset of WX doesn’t determine any non-prime attribute in the relation.

  • Third Normal Form

A relation is said to be in the third normal form, if it satisfies the conditions for the second normal form and there is no transitive dependency between the non-prime attributes, i.e., all non-prime attributes are determined only by the candidate keys of the relation and not by any other non-prime attribute.

Example 1 - Consider the Students Table in the above example. As we can observe, the Students Table in the 2NF form has a single candidate key Student_ID (primary key) that can uniquely identify all records in the table. The field Salutation (non-prime attribute), however, depends on the Student Field rather than the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once again partition the tables into two while specifying a new Foreign Key constraint to identify the salutations for individual records in the Students table. The Primary Key constraint for the same will be set on the Salutations table to identify each record uniquely.

Students Table (3rd Normal Form)

Books Table (3rd Normal Form)

Salutations Table (3rd Normal Form)

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)

For the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS, QR, T}.

  • Boyce-Codd Normal Form

A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and for every functional dependency, Left-Hand-Side is super key. In other words, a relation in BCNF has non-trivial functional dependencies in form X –> Y, such that X is always a super key. For example - In the above example, Student_ID serves as the sole unique identifier for the Students Table and Salutation_ID for the Salutations Table, thus these tables exist in BCNF. The same cannot be said for the Books Table and there can be several books with common Book Names and the same Student_ID.

30. What are the TRUNCATE, DELETE and DROP statements?

DELETE statement is used to delete rows from a table.

TRUNCATE command is used to delete all the rows from the table and free the space containing the table.

DROP command is used to remove an object from the database. If you drop a table, all the rows in the table are deleted and the table structure is removed from the database.

Write a SQL statement to wipe a table 'Temporary' from memory.

Write a sql query to remove first 1000 records from table 'temporary' based on 'id'., write a sql statement to delete the table 'temporary' while keeping its relations intact., 31. what is the difference between drop and truncate statements.

If a table is dropped, all things associated with the tables are dropped as well. This includes - the relationships defined on the table with other tables, the integrity checks and constraints, access privileges and other grants that the table has. To create and use the table again in its original form, all these relations, checks, constraints, privileges and relationships need to be redefined. However, if a table is truncated, none of the above problems exist and the table retains its original structure.

32. What is the difference between DELETE and TRUNCATE statements?

The TRUNCATE command is used to delete all the rows from the table and free the space containing the table. The DELETE command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

33. What are Aggregate and Scalar functions?

An aggregate function performs operations on a collection of values to return a single scalar value. Aggregate functions are often used with the GROUP BY and HAVING clauses of the SELECT statement. Following are the widely used SQL aggregate functions:

  • AVG() - Calculates the mean of a collection of values.
  • COUNT() - Counts the total number of records in a specific table or view.
  • MIN() - Calculates the minimum of a collection of values.
  • MAX() - Calculates the maximum of a collection of values.
  • SUM() - Calculates the sum of a collection of values.
  • FIRST() - Fetches the first element in a collection of values.
  • LAST() - Fetches the last element in a collection of values.

Note: All aggregate functions described above ignore NULL values except for the COUNT function.

A scalar function returns a single value based on the input value. Following are the widely used SQL scalar functions:

  • LEN() - Calculates the total length of the given field (column).
  • UCASE() - Converts a collection of string values to uppercase characters.
  • LCASE() - Converts a collection of string values to lowercase characters.
  • MID() - Extracts substrings from a collection of string values in a table.
  • CONCAT() - Concatenates two or more strings.
  • RAND() - Generates a random collection of numbers of a given length.
  • ROUND() - Calculates the round-off integer value for a numeric field (or decimal point values).
  • NOW() - Returns the current date & time.
  • FORMAT() - Sets the format to display a collection of values.

34. What is User-defined function? What are its various types?

The user-defined functions in SQL are like functions in any other programming language that accept parameters, perform complex calculations, and return a value. They are written to use the logic repetitively whenever required. There are two types of SQL user-defined functions:

  • Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
  • Inline: returns a table data type based on a single SELECT statement.
  • Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be used inside the function body.

35. What is OLTP?

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs. An essential attribute of an OLTP system is its ability to maintain concurrency. To avoid single points of failure, OLTP systems are often decentralized. These systems are usually designed for a large number of users who conduct short transactions. Database queries are usually simple, require sub-second response times, and return relatively few records. Here is an insight into the working of an OLTP system [ Note - The figure is not important for interviews ] -

sql tasks and answers

36. What are the differences between OLTP and OLAP?

OLTP stands for Online Transaction Processing , is a class of software applications capable of supporting transaction-oriented programs. An important attribute of an OLTP system is its ability to maintain concurrency. OLTP systems often follow a decentralized architecture to avoid single points of failure. These systems are generally designed for a large audience of end-users who conduct short transactions. Queries involved in such databases are generally simple, need fast response times, and return relatively few records. A number of transactions per second acts as an effective measure for such systems.

OLAP stands for Online Analytical Processing , a class of software programs that are characterized by the relatively low frequency of online transactions. Queries are often too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness measure relies highly on response time. Such systems are widely used for data mining or maintaining aggregated, historical data, usually in multi-dimensional schemas.

sql tasks and answers

37. What is Collation? What are the different types of Collation Sensitivity?

Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the correct character sequence are used to sort the character data. It incorporates options for specifying case sensitivity, accent marks, kana character types, and character width. Below are the different types of collation sensitivity:

  • Case sensitivity: A and a are treated differently.
  • Accent sensitivity: a and á are treated differently.
  • Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.
  • Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-width) are treated differently.

38. What is a Stored Procedure?

A stored procedure is a subroutine available to applications that access a relational database management system (RDBMS). Such procedures are stored in the database data dictionary. The sole disadvantage of stored procedure is that it can be executed nowhere except in the database and occupies more memory in the database server. It also provides a sense of security and functionality as users who can't access the data directly can be granted access via stored procedures.

sql tasks and answers

39. What is a Recursive Stored Procedure?

A stored procedure that calls itself until a boundary condition is reached, is called a recursive stored procedure. This recursive function helps the programmers to deploy the same set of code several times as and when required. Some SQL programming languages limit the recursion depth to prevent an infinite loop of procedure calls from causing a stack overflow, which slows down the system and may lead to system crashes.

40. How to create empty tables with the same structure as another table?

Creating empty tables with the same structure can be done smartly by fetching the records of one table into a new table using the INTO operator while fixing a WHERE clause to be false for all records. Hence, SQL prepares the new table with a duplicate structure to accept the fetched records but since no records get fetched due to the WHERE clause in action, nothing is inserted into the new table.

41. What is Pattern Matching in SQL?

SQL pattern matching provides for pattern search in data if you have no clue as to what that word should be. This kind of SQL query uses wildcards to match a string pattern, rather than writing the exact word. The LIKE operator is used in conjunction with SQL Wildcards to fetch the required information.

  • Using the % wildcard to perform a simple search

The % wildcard matches zero or more characters of any type and can be used to define wildcards both before and after the pattern. Search a student in your database with first name beginning with the letter K:

  • Omitting the patterns using the NOT keyword

Use the NOT keyword to select records that don't match the pattern. This query returns all students whose first name does not begin with K.

  • Matching a pattern anywhere using the % wildcard twice

Search for a student in the database where he/she has a K in his/her first name.

  • Using the _ wildcard to match pattern at a specific position

The _ wildcard matches exactly one character of any type. It can be used in conjunction with % wildcard. This query fetches all students with letter K at the third position in their first name.

  • Matching patterns for a specific length

The _ wildcard plays an important role as a limitation when it matches exactly one character. It limits the length and position of the matched results. For example - 

1. What is PostgreSQL?

PostgreSQL was first called Postgres and was developed by a team led by Computer Science Professor Michael Stonebraker in 1986. It was developed to help developers build enterprise-level applications by upholding data integrity by making systems fault-tolerant. PostgreSQL is therefore an enterprise-level, flexible, robust, open-source, and object-relational DBMS that supports flexible workloads along with handling concurrent users. It has been consistently supported by the global developer community. Due to its fault-tolerant nature, PostgreSQL has gained widespread popularity among developers.

2. How do you define Indexes in PostgreSQL?

Indexes are the inbuilt functions in PostgreSQL which are used by the queries to perform search more efficiently on a table in the database. Consider that you have a table with thousands of records and you have the below query that only a few records can satisfy the condition, then it will take a lot of time to search and return those rows that abide by this condition as the engine has to perform the search operation on every single to check this condition. This is undoubtedly inefficient for a system dealing with huge data. Now if this system had an index on the column where we are applying search, it can use an efficient method for identifying matching rows by walking through only a few levels. This is called indexing.

3. How will you change the datatype of a column?

This can be done by using the ALTER TABLE statement as shown below:

4. What is the command used for creating a database in PostgreSQL?

The first step of using PostgreSQL is to create a database. This is done by using the createdb command as shown below: createdb db_name After running the above command, if the database creation was successful, then the below message is shown:

5. How can we start, restart and stop the PostgreSQL server?

  • To start the PostgreSQL server, we run:
  • Once the server is successfully started, we get the below message:
  • To restart the PostgreSQL server, we run:

Once the server is successfully restarted, we get the message:

  • To stop the server, we run the command:

Once stopped successfully, we get the message:

6. What are partitioned tables called in PostgreSQL?

Partitioned tables are logical structures that are used for dividing large tables into smaller structures that are called partitions. This approach is used for effectively increasing the query performance while dealing with large database tables. To create a partition, a key called partition key which is usually a table column or an expression, and a partitioning method needs to be defined. There are three types of inbuilt partitioning methods provided by Postgres:

  • Range Partitioning : This method is done by partitioning based on a range of values. This method is most commonly used upon date fields to get monthly, weekly or yearly data. In the case of corner cases like value belonging to the end of the range, for example: if the range of partition 1 is 10-20 and the range of partition 2 is 20-30, and the given value is 10, then 10 belongs to the second partition and not the first.
  • List Partitioning: This method is used to partition based on a list of known values. Most commonly used when we have a key with a categorical value. For example, getting sales data based on regions divided as countries, cities, or states.
  • Hash Partitioning: This method utilizes a hash function upon the partition key. This is done when there are no specific requirements for data division and is used to access data individually. For example, you want to access data based on a specific product, then using hash partition would result in the dataset that we require.

The type of partition key and the type of method used for partitioning determines how positive the performance and the level of manageability of the partitioned table are.

7. Define tokens in PostgreSQL?

A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier, or any symbol that has a distinctive personality. They may or may not be separated using a space, newline or a tab. If the tokens are keywords, they are usually commands with useful meanings. Tokens are known as building blocks of any PostgreSQL code.

8. What is the importance of the TRUNCATE statement?

TRUNCATE TABLE name_of_table statement removes the data efficiently and quickly from the table. The truncate statement can also be used to reset values of the identity columns along with data cleanup as shown below:

We can also use the statement for removing data from multiple tables all at once by mentioning the table names separated by comma as shown below:

9. What is the capacity of a table in PostgreSQL?

The maximum size of PostgreSQL is 32TB.

10. Define sequence.

A sequence is a schema-bound, user-defined object which aids to generate a sequence of integers. This is most commonly used to generate values to identity columns in a table. We can create a sequence by using the CREATE SEQUENCE statement as shown below:

To get the next number 101 from the sequence, we use the nextval() method as shown below:

We can also use this sequence while inserting new records using the INSERT command:

11. What are string constants in PostgreSQL?

They are character sequences bound within single quotes. These are using during data insertion or updation to characters in the database. There are special string constants that are quoted in dollars. Syntax: $tag$<string_constant>$tag$ The tag in the constant is optional and when we are not specifying the tag, the constant is called a double-dollar string literal.

12. How can you get a list of all databases in PostgreSQL?

This can be done by using the command \l -> backslash followed by the lower-case letter L.

13. How can you delete a database in PostgreSQL?

This can be done by using the DROP DATABASE command as shown in the syntax below:

If the database has been deleted successfully, then the following message would be shown:

14. What are ACID properties? Is PostgreSQL compliant with ACID?

ACID stands for Atomicity, Consistency, Isolation, Durability. They are database transaction properties which are used for guaranteeing data validity in case of errors and failures.

  • Atomicity : This property ensures that the transaction is completed in all-or-nothing way.
  • Consistency : This ensures that updates made to the database is valid and follows rules and restrictions.
  • Isolation : This property ensures integrity of transaction that are visible to all other transactions.
  • Durability : This property ensures that the committed transactions are stored permanently in the database.

PostgreSQL is compliant with ACID properties.

15. Can you explain the architecture of PostgreSQL?

  • The architecture of PostgreSQL follows the client-server model.
  • The server side comprises of background process manager, query processer, utilities and shared memory space which work together to build PostgreSQL’s instance that has access to the data. The client application does the task of connecting to this instance and requests data processing to the services. The client can either be GUI (Graphical User Interface) or a web application. The most commonly used client for PostgreSQL is pgAdmin.

sql tasks and answers

16. What do you understand by multi-version concurrency control?

MVCC or Multi-version concurrency control is used for avoiding unnecessary database locks when 2 or more requests tries to access or modify the data at the same time. This ensures that the time lag for a user to log in to the database is avoided. The transactions are recorded when anyone tries to access the content.

For more information regarding this, you can refer here .

17. What do you understand by command enable-debug?

The command enable-debug is used for enabling the compilation of all libraries and applications. When this is enabled, the system processes get hindered and generally also increases the size of the binary file. Hence, it is not recommended to switch this on in the production environment. This is most commonly used by developers to debug the bugs in their scripts and help them spot the issues. For more information regarding how to debug, you can refer here .

18. How do you check the rows affected as part of previous transactions?

SQL standards state that the following three phenomena should be prevented whilst concurrent transactions. SQL standards define 4 levels of transaction isolations to deal with these phenomena.

  • Dirty reads : If a transaction reads data that is written due to concurrent uncommitted transaction, these reads are called dirty reads.
  • Phantom reads : This occurs when two same queries when executed separately return different rows. For example, if transaction A retrieves some set of rows matching search criteria. Assume another transaction B retrieves new rows in addition to the rows obtained earlier for the same search criteria. The results are different.
  • Non-repeatable reads : This occurs when a transaction tries to read the same row multiple times and gets different values each time due to concurrency. This happens when another transaction updates that data and our current transaction fetches that updated data, resulting in different values.

To tackle these, there are 4 standard isolation levels defined by SQL standards. They are as follows:

  • Read Uncommitted – The lowest level of the isolations. Here, the transactions are not isolated and can read data that are not committed by other transactions resulting in dirty reads.
  • Read Committed – This level ensures that the data read is committed at any instant of read time. Hence, dirty reads are avoided here. This level makes use of read/write lock on the current rows which prevents read/write/update/delete of that row when the current transaction is being operated on.
  • Repeatable Read – The most restrictive level of isolation. This holds read and write locks for all rows it operates on. Due to this, non-repeatable reads are avoided as other transactions cannot read, write, update or delete the rows.
  • Serializable – The highest of all isolation levels. This guarantees that the execution is serializable where execution of any concurrent operations are guaranteed to be appeared as executing serially.

The following table clearly explains which type of unwanted reads the levels avoid:

19. What can you tell about WAL (Write Ahead Logging)?

Write Ahead Logging is a feature that increases the database reliability by logging changes before any changes are done to the database. This ensures that we have enough information when a database crash occurs by helping to pinpoint to what point the work has been complete and gives a starting point from the point where it was discontinued.

For more information, you can refer here .

20. What is the main disadvantage of deleting data from an existing table using the DROP TABLE command?

DROP TABLE command deletes complete data from the table along with removing the complete table structure too. In case our requirement entails just remove the data, then we would need to recreate the table to store data in it. In such cases, it is advised to use the TRUNCATE command.

21. How do you perform case-insensitive searches using regular expressions in PostgreSQL?

To perform case insensitive matches using a regular expression, we can use POSIX (~*) expression from pattern matching operators. For example:

22. How will you take backup of the database in PostgreSQL?

We can achieve this by using the pg_dump tool for dumping all object contents in the database into a single file. The steps are as follows:

Step 1 : Navigate to the bin folder of the PostgreSQL installation path.

Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:

The database dump will be stored in the sample_data.tar file on the location specified.

23. Does PostgreSQL support full text search?

Full-Text Search is the method of searching single or collection of documents stored on a computer in a full-text based database. This is mostly supported in advanced database systems like SOLR or ElasticSearch. However, the feature is present but is pretty basic in PostgreSQL.

24. What are parallel queries in PostgreSQL?

Parallel Queries support is a feature provided in PostgreSQL for devising query plans capable of exploiting multiple CPU processors to execute the queries faster.

sql tasks and answers

25. Differentiate between commit and checkpoint.

The commit action ensures that the data consistency of the transaction is maintained and it ends the current transaction in the section. Commit adds a new record in the log that describes the COMMIT to the memory. Whereas, a checkpoint is used for writing all changes that were committed to disk up to SCN which would be kept in datafile headers and control files.

Conclusion:

SQL is a language for the database. It has a vast scope and robust capability of creating and manipulating a variety of database objects using commands like CREATE, ALTER, DROP, etc, and also in loading the database objects using commands like INSERT. It also provides options for Data Manipulation using commands like DELETE, TRUNCATE and also does effective retrieval of data using cursor commands like FETCH, SELECT, etc. There are many such commands which provide a large amount of control to the programmer to interact with the database in an efficient way without wasting many resources. The popularity of SQL has grown so much that almost every programmer relies on this to implement their application's storage functionalities thereby making it an exciting language to learn. Learning this provides the developer a benefit of understanding the data structures used for storing the organization's data and giving an additional level of control and in-depth understanding of the application.

PostgreSQL being an open-source database system having extremely robust and sophisticated ACID, Indexing, and Transaction supports has found widespread popularity among the developer community. 

References and Resources:

  • PostgreSQL Download
  • PostgreSQL Tutorial
  • SQL Server Interview Questions
  • SQL Query Interview Questions and Answers
  • SQL Interview Questions for Data Science
  • MySQL Interview Questions
  • DBMS Interview Questions
  • PL SQL Interview Questions
  • MongoDB Interview Questions
  • Database Testing Interview Questions
  • SQL Vs MySQL
  • PostgreSQL vs MySQL
  • Difference Between SQL and PLSQL
  • Difference between RDBMS and DBMS
  • SQL Vs NoSQL
  • SQL Projects
  • MySQL Commands
  • OLTP vs OLAP

Coding Problems

Which statement is true for a PRIMARY KEY constraint?

Which statement is false for a FOREIGN KEY constraint?

What is a Query?

What does SQL stand for?

Which statement is used to update data in the database?

Query to select all records with "bar" in their name?

Which statement is false for the ORDER BY statement?

SQL query used to fetch unique values from a field?

What is the main advantage of a clustered index over a non-clustered index?

Normalization which has neither composite values nor partial dependencies?

An SQL query to delete a table from the database and memory while keeping the structure of the table intact?

Which of the following is known as a virtual table in SQL?

What is the name of the component that requests data to the PostgreSQL server?

What statement is used for adding data to PostgreSQL?

What is the order of results shown by default if the ASC or DESC parameter is not specified with the ORDER BY command?

Which command is used to tell PostgreSQL to make all changes made to the database permanent?

What is a pre-requisite for creating a database in PostgreSQL?To create a database in PostgreSQL, you must have the special CREATEDB privilege or

What command is used for restoring the backup of PostgreSQL which was created using pg_dump?

What allows us to define how various tables are related to each other formally in a database?

What languages are supported by PostgreSQL?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

Cloud Training Program

Learn Cloud With Us

Top 50+ ETL Interview Questions and Answers for Data Professionals

' src=

June 1, 2024 by Aniket Gawandar Leave a Comment

Preparing for an ETL or data engineering job interview can be challenging, especially when facing complex ETL interview questions . Whether you’re an aspiring data analyst , data scientist , or data engineer , it’s important to be well-prepared.

To help you out, we’ve selected the top 20 most important ETL interview questions and answers from a comprehensive list of 50 questions. This guide will arm you with the expertise and assurance required to excel in your interview and land your dream job in data management.

Introduction to ETL and Leading ETL Tools

Etl developer interview questions and answers, etl testing interview questions and answers , etl scenario-based interview questions and answers, etl sql interview questions and answers, python etl interview questions and answers, etl interview questions for data analyst.

ETL , standing for Extract, Transform, and Load , plays a pivotal role in data management , particularly in designing data warehousing architecture . With the market for ETL tools projected to grow significantly, the demand for skilled data analysts , scientists , and engineers is on the rise. Now, let’s delve into the top 50 ETL interview questions and answers to better equip you for your next interview.

sql tasks and answers

  • Apache Nifi : Known for its easy-to-use, web-based interface and ability to automate data flow between systems. Ideal for real-time data ingestion .
  • Talend : An open-source ETL tool that offers extensive data integration capabilities , including big data and cloud integration .
  • AWS Glue : A fully managed ETL service provided by Amazon Web Services , designed for large-scale data processing and integration in the cloud .

ETL Interview Questions and Answers

This guide covers essential ETL interview questions from various key areas within the ETL and data engineering domain. The questions mentioned below include ETL Developer Interview Questions and Answers , ETL Testing Interview Questions and Answers , ETL Scenario-Based Interview Questions and Answers , ETL SQL Interview Questions and Answers , Python ETL Interview Questions and Answers , and ETL Interview Questions for Data Analysts .

Below are some of the most frequently asked ETL developer interview questions and answers . Review these to boost your chances of acing your next ETL developer job interview .

Q1) Explain the three-layer architecture of an ETL cycle.

The ETL cycle consists of three distinct layers:

  • Staging Layer: This layer is where data extracted from various sources is initially stored. It acts as a temporary storage area where data is loaded and prepared for transformation processes. Developers use this layer to perform initial transformations and cleansing operations before data is moved to the next layer.
  • Data Integration Layer: In this layer, the data is further transformed and integrated. This layer involves complex transformations, such as joining different data sources, aggregating data, and applying business rules. The primary goal is to prepare the data for loading into the database layer.
  • Access Layer: Also known as the dimension layer, this is the final layer where transformed data is stored and made available for end-users. Users can retrieve data for analytical reporting and information retrieval, allowing them to generate insights and make data-driven decisions.

Q2) What is the difference between OLAP tools and ETL tools?

ETL tools are designed to extract, transform, and load data from various sources into a data warehouse. They focus on the process of moving data from its source to a centralized data repository, where it can be stored and managed for further analysis. ETL is essential for data warehousing because it ensures that data is cleansed, transformed, and integrated before being stored.

On the other hand, OLAP (Online Analytical Processing) tools are used primarily for querying and reporting purposes. They allow users to conduct multidimensional data analysis, facilitating complex calculations, trend analysis, and data modeling. OLAP tools transform data into cubes, making it easier to generate interactive and analytical reports that help in decision-making processes.

Q3) What are Cubes and OLAP Cubes?

Cubes in data processing are units that consist of data warehouse fact tables and their related dimensions. These cubes enable efficient data storage and retrieval for analytical purposes. They are organized into multidimensional structures that allow users to analyze data from various perspectives.

OLAP cubes , specifically, are designed for high-performance data analysis. They store vast amounts of data in a way that supports fast querying and reporting. OLAP cubes contain measures (quantitative data) and dimensions (descriptive data), which together enable complex analytical operations such as slicing, dicing, drilling down, and rolling up, providing deep insights into business data.

Q4) What do you mean by an ETL Pipeline?

An ETL pipeline refers to the series of processes involved in extracting data from different sources, transforming it into a suitable format, and loading it into a central repository like a database, datamart, or data warehouse. This pipeline ensures that data is accurately and efficiently moved from its source to the destination, where it can be used for analysis and reporting. The ETL pipeline involves several stages, including data extraction, data transformation, data validation, and data loading, each of which plays a critical role in ensuring the integrity and usability of the data.

Q5) What are the differences between BI tools and ETL tools?

  • ETL Tools: These tools focus on extracting data from various sources, transforming it into a structured format, and loading it into a data warehouse. Common ETL tools include Microsoft SSIS, Oracle Data Integrator (ODI), Informatica, and Clover ETL Open Source. They are essential for preparing data for analysis by ensuring it is cleansed, transformed, and integrated.
  • BI Tools: Business Intelligence ( BI ) tools are designed for generating reports, dashboards, and visualizations from the data stored in the data warehouse. They allow users to perform interactive and ad-hoc analysis, enabling them to gain insights and make data-driven decisions. Well-known BI tools encompass the Microsoft BI platform, Tableau, and Oracle Business Intelligence Enterprise Edition.

Q6) What do you understand by ODS (Operational Data Store)?

An Operational Data Store (ODS) is a central database that provides a real-time, integrated view of business data from multiple sources. It is designed for operational reporting and decision-making, offering a current snapshot of data that supports day-to-day business operations. Unlike traditional ETL systems that may process data in batches, an ODS ingests raw data in its original format and makes it immediately available for analysis and reporting without the need for extensive transformation. This makes it an ideal solution for scenarios requiring up-to-date information for quick decision-making.

Q7) What are the differences between ETL and ELT? 

The following table helps you understand the difference between ETL and ELT :

Here are the most frequently asked ETL testing interview questions and answers that you should review to excel in your next interview:

Q8) What are the steps followed in the ETL testing process?

The ETL testing process involves the following steps:

  • Analyze Business Requirements: Understand the business needs and define the scope of testing based on these requirements.
  • Identify Data Sources: Determine the data sources used for extraction, ensuring they are accurate and reliable.
  • Design Test Cases: Create detailed test cases that cover all aspects of the ETL process, including data extraction, transformation, and loading.
  • Perform Test Execution: Execute the test cases, verifying that data is correctly extracted, transformed, and loaded according to the specifications.
  • Prepare Summary Report: Document the test results, highlighting any discrepancies or issues found during the testing process.
  • Test Closure: Conclude the testing phase by ensuring all identified issues are resolved and the data meets the required quality standards.

Q9) What do ETL Testing operations include? 

ETL testing operations encompass several key activities:

  • Data Transformation Validation: Ensuring data is transformed accurately according to business rules and requirements.
  • Performance and Scalability Checks: Verifying that data loads within the scheduled time frame, ensuring the system can handle increasing volumes of data efficiently.
  • Data Integrity Verification: Confirm that data is loaded into the warehouse without truncation, loss, or corruption, maintaining its integrity throughout the process.
  • Error Handling: Checking that the ETL system appropriately handles invalid data, reports errors, and replaces or corrects data as needed.

Q10) What are ETL bugs? 

ETL bugs refer to issues or defects encountered during the ETL process. Common types of ETL bugs include:

  • Calculation Bug: Errors in data calculations during the transformation process.
  • Source Bug: Issues related to data extraction from the source systems.
  • Version Control Bug: Problems with maintaining and managing different versions of ETL scripts and mappings.
  • Input/Output Bug: Errors in data input or output during the ETL process.
  • User Interface Bug: Issues with the ETL tool’s user interface that affect usability and functionality.
  • Load Condition Bug: Problems encountered during the data loading phase, such as incomplete or failed data loads.

Q11) Differentiate between ETL testing and database testing. 

Q12) what is the staging area in etl testing .

The staging area is a temporary storage space used during ETL processes. It holds data that has been extracted from various sources but has not yet been transformed or loaded into the final data warehouse. The staging area is crucial because it allows for the efficient extraction of data from source systems with minimal impact on their performance. Once data is in the staging area, it can be merged, transformed, verified, and cleaned before being loaded into the data warehouse, ensuring that only high-quality data is stored for analysis.

Q13) Explain the data cleaning process. 

Data cleaning , also known as data cleansing , is the process of identifying and correcting errors, inconsistencies, and inaccuracies in a dataset to ensure data quality. The steps involved in the data cleaning process include:

  • Removing Irrelevant Data: Eliminating unnecessary data that does not contribute to the analysis.
  • Handling Missing Data: Addressing missing values by either filling them with appropriate values or removing the records.
  • Removing Duplicates: Identifying and removing duplicate records to ensure each data entry is unique.
  • Fixing Structural Errors: Correcting structural issues such as inconsistent data formats and typographical errors.
  • Filtering Outliers: Identifying and handling data points that significantly deviate from the norm to avoid skewing the analysis.
  • Validating Data: Ensuring that the data conforms to the required standards and formats for consistency and reliability.

Scenario-based interview questions aren’t something you can ignore. Recruiters frequently pose such interview questions to gauge your profound interest in and understanding of ETL tools and technologies.

Q14) What are the different ways of updating a table when SSIS (SQL Server Integration Service) is used?

There are several methods to update a table using SSIS:

  • Using a SQL Command: Directly update the table by executing an SQL command in the SSIS package.
  • Using a Staging Table: Load data into a staging table first, then update the target table from the staging table to ensure data consistency and integrity.
  • Using Cache: Utilize SSIS cache transformations to store and manage data updates more efficiently.
  • Using Scripts for Scheduling Tasks: Implement scripts to schedule and automate data updates as part of the ETL process.
  • Using Full Database Name in MSSQL Updates: Specify the full database name to ensure the correct table is updated, particularly in environments with multiple databases.

Q15) What are the conditions under which you use dynamic and static cache in connected and unconnected transformations?

Dynamic and static caches are used in different scenarios within connected and unconnected transformations:

  • Dynamic Cache: Used when you need to update tables continuously. It allows for incremental data updates, ensuring that the cache reflects the most recent changes in the data.
  • Static Cache: Used for read-only purposes where the data does not change frequently. It provides a consistent view of the data, making it suitable for scenarios where data integrity is crucial.
  • Static Cache: Used exclusively in unconnected transformations as dynamic cache is not applicable. Static cache ensures that the data remains consistent and unchanged during the transformation process.

Below are several interview questions centered around SQL statements for ETL testing operations:

Q16) What is the difference between ETL and SQL?

SQL , a standardized programming language, is employed for managing and manipulating relational databases . It focuses on retrieving and modifying data within databases. ETL , on the other hand, is a process that extracts data from multiple sources, transforms it into a suitable format, and loads it into a target data warehouse . While SQL is a language for querying and managing databases , ETL is a comprehensive process that uses SQL to perform extraction , transformation , and loading operations . ETL tools leverage SQL to handle data manipulation before moving it to another database.

Q17) What SQL statements may be used to validate data completion?

To validate data completion, you can use the MINUS and INTERSECT commands . Running “target MINUS source” and “source MINUS target” helps identify mismatched rows . If these queries return any values, it indicates discrepancies . Additionally, if the result of the INTERSECT query is less than the count of the source or target table , it suggests the presence of duplicate rows .

Q18) What makes ETL testing in SQL so efficient?

SQL Server includes SQL Server Integration Services (SSIS) , which facilitates efficient data transfer into the server. SSIS supports various data ingestion methods , such as bulk and incremental loads . It also offers features like “slowly changing dimensions” for transforming data records during the loading process. These capabilities make ETL testing in SQL effective and versatile for handling different data integration scenarios .

Python stands out as one of the most versatile programming languages for executing ETL operations . As a result, interviewers may pose questions centered around Python. Below are essential interview questions focusing on the ETL testing process using Python.

Q19) What makes Python a viable choice for coding ETL tasks? 

Python is a versatile programming language with a rich ecosystem of modules and libraries . To effectively use Python for ETL, you need to be familiar with frameworks and libraries like workflow management tools , data access and extraction libraries , and comprehensive ETL toolkits . Python’s flexibility allows users to leverage native data structures to handle nearly any ETL operation. For instance, the Python math module simplifies filtering out null values from a list.

Listed below are some of the most commonly asked interview questions regarding ETL processes for data analysts:

Q20) Explain what is fact and state its type.

Facts are aggregated measures of a business process that can be calculated and grouped to answer business questions. In data designs like the star or snowflake schema , dimension tables surround a central fact table. FaFacts comprise measures or statistics like sales , cost , profit , and loss .

Fact tables have two types of columns: foreign keys and measurement columns . Measures hold numeric facts, while foreign keys link data between tables.

sql tasks and answers

  • Additive: These can be summed over any dimension connected with the fact table, making them the most valuable and flexible.
  • Semi-additive: This can be summed up in some dimensions but not all.
  • Non-additive: Cannot be added up for any dimension, such as ratios.

Download the Full ETL Interview Guide

Master these 50 essential ETL interview questions to boost your confidence for your next ETL job interview.

Download Now

Armed with these top ETL interview questions and answers, you’re better equipped to tackle your next job interview with confidence. Whether you’re discussing ETL architecture, testing procedures, SQL queries, Python integration, or advanced concepts, this comprehensive guide has you covered. Dive into your interview prepared and ready to showcase your expertise in the dynamic field of ETL.

Related References

  • Microsoft Azure Data on Cloud Job-Oriented Step-by-Step Activity Guides.
  • Top 10 Real-life ADF ETL Projects with PySpark & Python
  • Azure Data Factory For Beginners
  • Azure Data Lake For Beginners: All You Need To Know
  • AWS Glue: Overview, Features and Use Cases
  • Azure Synapse Analytics (Azure SQL Data Warehouse)
  • Azure SQL Database | All You Need to Know About Azure SQL Services

Next Task For You

In our  Azure Data Engineer  training program, we will cover  50 Hands-On Labs.  If you want to begin your journey towards becoming a  Microsoft Certified: Azure Data Engineer Associate check out our  FREE CLASS .

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

k21_logo

"Learn Cloud From Experts"

oracle

  • Partner with Us
  • Terms and Conditions
  • Privacy Policy
  • Docker and Kubernetes Job Oriented Program
  • AWS Job Oriented Program
  • Azure Job Oriented Program
  • Azure Data Job Oriented Program
  • DevOps Job Oriented Program
  • Oracle Cloud Job Oriented Program
  • Terraform Job Oriented

Get in touch with us

8 Magnolia Pl, Harrow HA2 6DS, United Kingdom

Email : [email protected]

sql tasks and answers

More From Forbes

Today’s nyt ‘strands’ hints, spangram and answers for monday, june 3.

  • Share to Facebook
  • Share to Twitter
  • Share to Linkedin

Today's NYT Strands hints and answers.

Looking for Sunday’s Strands hints, spangram and answers? You can find them here:

Hey, folks! Welcome to the start of a new week. It’s going to be a great one for you, I can feel it.

Today’s NYT Strands hints, spangram and answers are coming right up.

How To Play Strands

The New York Times’ Strands puzzle is a play on the classic word search. It’s in beta for now, which means it’ll only stick around if enough people play it every day.

There’s a new game of Strands to play every day. The game will present you with a six by eight grid of letters. The aim is to find a group of words that have something in common, and you’ll get a clue as to what that theme is. When you find a theme word, it will remain highlighted in blue.

You’ll also need to find a special word called a spangram. This tells you what the words have in common. The spangram links at least two sides of the board, but it may not start or end there. While the theme words will not be a proper name, the spangram can be a proper name. When you find the spangram, it will remain highlighted in yellow.

Best High-Yield Savings Accounts Of 2024

Best 5% interest savings accounts of 2024.

Every letter is used once in one of the theme words and spangram. You can connect letters vertically, horizontally and diagonally, and it’s possible to switch directions in the middle of a word. If you’re playing on a touchscreen, double tap the last letter to submit your guess.

If you find three valid words of at least four letters that are not part of the theme, you’ll unlock the Hint button. Clicking this will highlight the letters that make up one of the theme words.

Be warned: You’ll need to be on your toes. Sometimes you’ll need to fill the missing word(s) in a phrase. On other days, the game may revolve around synonyms or homophones. The difficulty will vary from day to day, and the puzzle creators will try to surprise you sometimes.

What Is Today’s Strands Hint?

Scroll slowly! Just after the hint for today’s Strands puzzle, I’ll reveal what the answer words are.

The official theme hint for today’s Strand puzzle is...

Better with age

Need some extra help? Here’s another hint...

Food that’s better left alone for some time

There are eight theme words to find today, including the spangram.

What Are Today’s Strands Answers?

Spoiler alert! Don’t scroll any further down the page until you’re ready to find out today’s Strands answers.

I’ll first tell you the spangram and show you where that is on the grid. I’ll then tell you the other words and show you how they fit in.

This is your final warning!

Today’s Strands spangram is...

Here’s where you’ll find it on the grid...

New York Times Strands screenshot, showing the highlighted term FERMENTED.

The rest of today’s Strands theme words are...

Here’s what the completed grid looks like...

Completed Strands grid for June 3 featuring the words KOMBUCHA, KEFIR, FERMENTED, KIMCHI, YOGURT, ... [+] SAUERKRAUT and MISO.

I found this to be a pretty straightforward grid. I immediately spotted KOMBUCHA snaking around the top, so I figured fermented food is what I was looking for. Sure enough, I found MISO in the bottom right. That led me to go looking for the then-obvious spangram.

The spangram sectioned off YOGURT and SAUERKRAUT. That left me with KIMCHI and KEFIR to wrap things up.

I didn't use any hints and the spangram was the third theme word I found.

That’s all there is to it for today’s Strands clues and answers. Be sure to check my blog for hints and the solution for Tuesday’s game if you need them.

Kris Holt

  • Editorial Standards
  • Reprints & Permissions

Join The Conversation

One Community. Many Voices. Create a free account to share your thoughts. 

Forbes Community Guidelines

Our community is about connecting people through open and thoughtful conversations. We want our readers to share their views and exchange ideas and facts in a safe space.

In order to do so, please follow the posting rules in our site's  Terms of Service.   We've summarized some of those key rules below. Simply put, keep it civil.

Your post will be rejected if we notice that it seems to contain:

  • False or intentionally out-of-context or misleading information
  • Insults, profanity, incoherent, obscene or inflammatory language or threats of any kind
  • Attacks on the identity of other commenters or the article's author
  • Content that otherwise violates our site's  terms.

User accounts will be blocked if we notice or believe that users are engaged in:

  • Continuous attempts to re-post comments that have been previously moderated/rejected
  • Racist, sexist, homophobic or other discriminatory comments
  • Attempts or tactics that put the site security at risk
  • Actions that otherwise violate our site's  terms.

So, how can you be a power user?

  • Stay on topic and share your insights
  • Feel free to be clear and thoughtful to get your point across
  • ‘Like’ or ‘Dislike’ to show your point of view.
  • Protect your community.
  • Use the report tool to alert us when someone breaks the rules.

Thanks for reading our community guidelines. Please read the full list of posting rules found in our site's  Terms of Service.

TechRepublic

Male system administrator of big data center typing on laptop computer while working in server room. Programming digital operation. Man engineer working online in database center. Telecommunication.

8 Best Data Science Tools and Software

Apache Spark and Hadoop, Microsoft Power BI, Jupyter Notebook and Alteryx are among the top data science tools for finding business insights. Compare their features, pros and cons.

AI act trilogue press conference.

EU’s AI Act: Europe’s New Rules for Artificial Intelligence

Europe's AI legislation, adopted March 13, attempts to strike a tricky balance between promoting innovation and protecting citizens' rights.

Concept image of a woman analyzing data.

10 Best Predictive Analytics Tools and Software for 2024

Tableau, TIBCO Data Science, IBM and Sisense are among the best software for predictive analytics. Explore their features, pricing, pros and cons to find the best option for your organization.

Tableau logo.

Tableau Review: Features, Pricing, Pros and Cons

Tableau has three pricing tiers that cater to all kinds of data teams, with capabilities like accelerators and real-time analytics. And if Tableau doesn’t meet your needs, it has a few alternatives worth noting.

Futuristic concept art for big data solution for enterprises.

Top 6 Enterprise Data Storage Solutions for 2024

Amazon, IDrive, IBM, Google, NetApp and Wasabi offer some of the top enterprise data storage solutions. Explore their features and benefits, and find the right solution for your organization's needs.

Latest Articles

Ominous virtual AI brain hovering in dark server room with glowing red circuitry.

Some Generative AI Company Employees Pen Letter Wanting ‘Right to Warn’ About Risks

Both the promise and the risk of "human-level" AI has always been part of OpenAI’s makeup. What should business leaders take away from this letter?

A computer screen with program code warning of a detected malware script program.

Cisco Talos: LilacSquid Threat Actor Targets Multiple Sectors Worldwide With PurpleInk Malware

Find out how the cyberespionage threat actor LilacSquid operates, and then learn how to protect your business from this security risk.

The IBM sign logo on Czech Republic Headquarter.

IBM’s Think 2024 News That Should Help Skills & Productivity Issues in Australia

TechRepublic interviewed IBM’s managing director for Australia about how announcements from the recent Think event could impact the tech industry in particular.

Cisco logo near Cisco headquarters campus in Silicon Valley.

Cisco Live 2024: New Unified Observability Experience Packages Cisco & Splunk Insight Tools

The observability suite is the first major overhaul for Splunk products since the Cisco acquisition. Plus, Mistral AI makes a deal with Cisco’s incubator.

Audience at conference hall.

Top Tech Conferences & Events to Add to Your Calendar in 2024

A great way to stay current with the latest technology trends and innovations is by attending conferences. Read and bookmark our 2024 tech events guide.

Intel logo is seen at Intel Corporation's headquarters in Santa Clara, California.

Intel Lunar Lake NPU Brings 48 TOPS of AI Acceleration

Competition for AI speed heats up. Plus, the first of the two new Xeon 6 processors is now available, and Gaudi 3 deals have been cinched with manufacturers.

Concept visualization of observing a blue cluster structure with magnifying glass.

Cisco Live 2024: Cisco Unveils AI Deployment Solution With NVIDIA

A $1 billion commitment will send Cisco money to Cohere, Mistral AI and Scale AI.

Splash graphic featuring the logo of Udemy.

The 5 Best Udemy Courses That Are Worth Taking in 2024

Udemy is an online platform for learning at your own pace. Boost your career with our picks for the best Udemy courses for learning tech skills online in 2024.

Check mark on shield on a background of binary values.

What Is Data Quality? Definition and Best Practices

Data quality refers to the degree to which data is accurate, complete, reliable and relevant for its intended use.

sql tasks and answers

TechRepublic Premium Editorial Calendar: Policies, Checklists, Hiring Kits and Glossaries for Download

TechRepublic Premium content helps you solve your toughest IT issues and jump-start your career or next project.

European Union flag colors and symbols on a printed circuit board.

What is the EU’s AI Office? New Body Formed to Oversee the Rollout of General Purpose Models and AI Act

The AI Office will be responsible for enforcing the rules of the AI Act, ensuring its implementation across Member States, funding AI and robotics innovation and more.

Data science abstract vector background.

What is Data Science? Benefits, Techniques and Use Cases

Data science involves extracting valuable insights from complex datasets. While this process can be technically challenging and time-consuming, it can lead to better business decision-making.

Glowing circuit grid forming a cloud and trickling binary values on a dark background.

Gartner’s 7 Predictions for the Future of Australian & Global Cloud Computing

An explosion in AI computing, a big shift in workloads to the cloud, and difficulties in gaining value from hybrid cloud strategies are among the trends Australian cloud professionals will see to 2028.

sql tasks and answers

OpenAI Adds PwC as Its First Resale Partner for the ChatGPT Enterprise Tier

PwC employees have 100,000 ChatGPT Enterprise seats. Plus, OpenAI forms a new safety and security committee in their quest for more powerful AI, and seals media deals.

Contact management vector illustration. 2 people managing their client's contact information.

What Is Contact Management? Importance, Benefits and Tools

Contact management ensures accurate, organized and accessible information for effective communication and relationship building.

Create a TechRepublic Account

Get the web's best business technology news, tutorials, reviews, trends, and analysis—in your inbox. Let's start with the basics.

* - indicates required fields

Sign in to TechRepublic

Lost your password? Request a new password

Reset Password

Please enter your email adress. You will receive an email message with instructions on how to reset your password.

Check your email for a password reset link. If you didn't receive an email don't forgot to check your spam folder, otherwise contact support .

Welcome. Tell us a little bit about you.

This will help us provide you with customized content.

Want to receive more TechRepublic news?

You're all set.

Thanks for signing up! Keep an eye out for a confirmation email from our team. To ensure any newsletters you subscribed to hit your inbox, make sure to add [email protected] to your contacts list.

  • SI SWIMSUIT
  • SI SPORTSBOOK

Jrue Holiday Had a Comical One-Word Answer on How to Stop Luka Dončić, Kyrie Irving

Karl rasmussen | jun 5, 2024.

Boston Celtics guard Jrue Holiday (4) during the fourth quarter during game four of the Eastern Conference finals.

  • Boston Celtics
  • Dallas Mavericks

The Boston Celtics and Dallas Mavericks will tip-off Game 1 of the NBA Finals on Thursday night, and ahead of the series Celtics guard Jrue Holiday made it clear that he knows it won't be an easy task to slow down Dallas' backcourt tandem of Luka Doncic and Kyrie Irving.

Speaking to reporters on Wednesday, Holiday offered a brutally honest one-word answer when asked how the team is going to slow down the scalding hot Mavericks' duo.

"Pray," said Holiday of how he intends to try to stop Irving in a one-on-one matchup.

"What can you do to nullify/thwart/stop Kyrie?" Jrue Holiday: Pray 🤣 pic.twitter.com/OYr1hMdZ2w — NBA (@NBA) June 5, 2024

Thus far into the postseason, Irving and Doncic are combining to average 51.6 points per game. Through 17 games, Irving has shot 48.5% from the field and 42.1% from three-point range, both of which are the best shooting percentages in the playoffs in his career. Doncic has nearly logged a nightly triple-double, with averages of 28.8 points, 8.8 assists (the most among any player during this year's playoffs) and 9.6 rebounds.

Although Holiday and Derrick White make up one of the most stalwart defensive backcourts in the league, the 33-year-old admitted that simply playing good defense won't be enough to quell the hot hands of Doncic and Irving.

Karl Rasmussen

KARL RASMUSSEN

Top 15 SQL Interview Questions in 2021

Author's photo

  • jobs and career

Table of Contents

1. What Is SQL?

2. what are the basic elements of a sql query, 3. what is the sql where clause, 4. how does group by work, 5. name and explain some common aggregate functions., 6. what does the having clause do, 7. what’s the difference between having and where, 8. describe the action of join and the different join types., 9. what does order by do, 10.  what is a null in sql, 11. what does union do what’s the difference between union and union all, 12. what do the intersect and minus clauses do, 13. describe the role of the distinct keyword., 14. what is a subquery in sql, 15. how do you modify data in a database using sql, tips for a successful sql interview.

If you are on the lookout for a job in the field of data, you’re almost guaranteed to face SQL interview questions. You might even be asked to complete some kind of SQL coding test. According to KDnuggets , irrespective of the specific role in data – data analyst, data engineer, data scientist, or business intelligence analyst – SQL lands in the top three skills found in postings across Indeed, SimplyHired, and Monster.

SQL’s demand arises largely from its widespread application across a whole host of uses, including relational databases, data warehousing, NoSQL databases, and distributed data processing. SQL powers the majority of modern-day transaction processes, cloud storage solutions, search engines, analytics applications, and business intelligence operations across virtually all sectors.

This guide will help you brush up on your SQL skills, get a confidence boost, and be ready to ace your interview!

Below is a curated list of SQL interview questions along with some guidance on how to approach them. They are based on research into top tech companies’ hiring practices and SQL job interview trends. That being said, be sure to put in your due diligence and craft the answers with your own knowledge and experience!

Can You Answer These 15 SQL Interview Questions?

SQL, or Structured Query Language, is the standard language used to access, update, and manipulate relational databases. It allows users to filter, sort, and extract data from a relational database.

 A relational database stores data in tables made up of columns (attributes) and rows (values). Tables can be related to other tables based on row values. For more information on this, see SQL Terms Beginners Should Know and What Is the Benefit of Foreign Keys in SQL? .

SQL can be used in technologies other than relational databases and is considered a key skill for many data and software engineering jobs.

The exact structure of each SQL query will obviously depend on the problem you are trying to solve. However, there are some basic elements that form most SQL queries. SELECT ,  FROM ,  JOIN ,  WHERE ,  GROUP BY ,  HAVING , and ORDER BY are common elements of a SQL query.

The SELECT statement is used to fetch data from a database; the FROM command is used to specify the table(s) within the database; JOIN is used to connect tables within the database using shared column values; ORDER BY is used to sort the data, and GROUP BY is used group the data. One of our prior articles discusses basic SQL query elements in detail.

WHERE is applied after the FROM or JOIN statements. It retrieves those records that meet the specified condition. WHERE conditions can use comparison operators ( Age > 21 ) or logical operators ( Name NOT ‘Jones’ ). You can specify complex WHERE conditions with  AND or OR ( Name NOT ‘Jones’ OR ‘Garcia’ ).

The GROUP BY  clause groups records with the same values in a given column. For example, if you wrote GROUP BY department, all employees with the same value in the department column would be one group. This is very useful when you need to compute aggregate statistics for that group (e.g. if you wanted to find average salaries by department).

GROUP BY follows the optional WHERE clause and is most often used when aggregate functions like COUNT() , SUM() , and AVG() are referenced in the SELECT statement. In one of our prior articles, we went over how GROUP BY works and some practical examples of SQL GROUP BY – feel free to check those out!

In SQL, an aggregate function uses the data from multiple rows to calculate a single result. Common aggregate functions include COUNT (returns the number of rows), SUM (returns the sum of all values in that column), AVG (returns the average value), MIN (returns the smallest value) and MAX (returns the largest value).

Aggregate functions are often used in conjunction with GROUP BY and HAVING to compute statistics for a data set. You can find more detailed information and examples in our article An Overview of SQL Aggregate Functions .

The SQL HAVING clause is used for filtering the data created by the GROUP BY clause according to the specified condition. This clause filters the data on the grouped records rather than the individual records, so it must follow GROUP BY . It cannot be used without a GROUP BY clause.

The difference between the WHERE and HAVING clause is in what each one filters. The WHERE clause filters individual records; it cannot be applied to grouped or aggregated records. The HAVING clause filters grouped or aggregated records.

A query can have both clauses; WHERE is applied on the individual records, followed by GROUP BY and then the HAVING clause.

A JOIN merges data from two or more tables using matching values in specified columns; this is called the join condition and is listed after the ON keyword. For example, you could join the tables employee and role based on the matching values in the employee.role_id and role.id columns.

There are different types of JOINs, and each one gives slightly different results:

  • INNER JOIN returns only rows that have matching values in both tables. This is the default join type.
  • LEFT JOIN returns all rows from the left table (after FROM ) and matching rows from the right table (after JOIN ). If there is no matching row for the right table, NULLs will be returned for those values.
  • RIGHT JOIN returns all rows from the right table and matching rows from the left table. If there is no matching row for the left table, NULLs will be returned for those values.
  • FULL JOIN (or FULL OUTER JOIN ) returns all records from both tables. It is the equivalent of using UNION on a LEFT JOIN and a RIGHT JOIN .

There are lots of applications for SQL JOINs, as well as some less common join types; see our SQL JOIN Cheat Sheet for more details.

ORDER BY sorts records based on user-defined conditions, e.g. ORDER BY Age will return records sorted by age in ascending order. The optional ASC (ascending) and DESC (descending) keywords specify the sort order; sorts are in ascending order by default.

ORDER BY can be applied to one or more columns; if you use multiple columns, it will order them by the first column and then order any matching first-column values by the second column, etc.

In SQL, NULL s represent values that are unknown or unavailable. A NULL is not the same as a blank space (a character) or a zero (a number); it’s something that we don’t yet know (e.g. an arrival date for an order that’s just been placed) or that doesn’t exist (like when someone doesn’t have a middle name).

In database tables, some values cannot be NULL, like primary keys or mandatory fields.

Working with NULL can be quite tricky. You cannot use comparison operators (like =,<,>,or <>) to retrieve NULLs; instead, you have to use IS NULL and IS NOT NULL . You can find more details in How to Use Comparison Operators with NULLs in SQL .

UNION  is a set operator that merges the results of two queries into one table. (Note: the queries must be structurally compatible.) UNION  does not include duplicate records;   UNION ALL  includes all records, even duplicates.

It may also be worthwhile to mention that   UNION ALL  requires less work from the server than UNION , which means the operation is generally faster.

INTERSECT and MINUS are also set operators; both work on two SELECT statements. MINUS subtracts the result of the first SELECT from the second SELECT . In other words, it returns records that are unique to the first SELECT result. INTERSECT , on the other hand, returns distinct rows that appear in both queries – i.e. what both results have in common. For more on SQL set operations, see this Introduction to Set Operations .

DISTINCT is used with the SELECT statement to return only unique values. If the result set contains duplicates, then the DISTINCT statement can be used to return the unique, or distinct, values among duplicate records for selected columns.

You can read up further and see some examples in action in the article What Is the Role of Distinct in SQL .

A subquery (aka an  inner or nested query) is a smaller query included in the body of a larger query (called the main or outer query). The results of the inner query are used in the outer query. They come in useful when you need a subset of the data to get the desired results, e.g. if you wanted to find which sales reps had above-average sales in their region, you’d first need a subquery to calculate the average sales for that region.

Here are some things to know about subquery syntax:

  • The subquery goes inside
  • In some database management systems (DBMSs), subqueries require an alias.
  • If your subquery is in a WHERE or HAVING clause, its SELECT can only return the field being evaluated.

There are also a few different types of SQL subqueries, such as nested subqueries (a subquery within a subquery) scalar subqueries (which return exactly one value for a column), correlated subqueries (which depend on information in the outer query), and multi-row subqueries. You can brush up on those specifics in What are the Different Types of SQL Subqueries?

SQL has a subset called Data Manipulation Language, which include commands like UPDATE , INSERT , and DELETE . As the names of these commands suggest, they manipulate the data inside the database by storing, modifying, deleting, and retrieving it. The use of these commands is relatively straightforward; you can read up on the subject at SQL INSERT, SQL UPDATE and SQL DELETE – Oh My!

I hope this information is useful in your job interview prep. However, I must stress that nothing beats actual hands-on practice. If you want to dive deeper into SQL, check out our SQL Practice Set , which is designed to bring you up to speed on popular SQL concepts.

If you can reasonably do so, always try to link each question with a real-world scenario – that makes your answer resonate better with recruiters. This is another reason to practice SQL and put your knowledge to the test!

By being prepared and familiarizing yourself with these SQL interview questions and answers, you’ll have a much better chance of impressing your interviewer and securing your next job. All the best!

You may also like

sql tasks and answers

How Do You Write a SELECT Statement in SQL?

sql tasks and answers

What Is a Foreign Key in SQL?

sql tasks and answers

Enumerate and Explain All the Basic Elements of an SQL Query

IMAGES

  1. SQL Query 30 tasks with answers

    sql tasks and answers

  2. Sql task answers

    sql tasks and answers

  3. Sample Database Tables With Data For Sql Practice

    sql tasks and answers

  4. Solved SQL Labs Math with SQL Tasks LUI Using the

    sql tasks and answers

  5. Read 50 most frequently asked SQL query questions and improve your SQL

    sql tasks and answers

  6. SQL+Assignment+Answers

    sql tasks and answers

VIDEO

  1. Automating SQL Tasks using Python #python #sql #programming

  2. TOP 50 SQL Server Interview Questions and Answers

  3. SQL answers for the previous question #dataengineer #clouds

  4. SQL Working Session Task 4: Refer description section to know more about this requirement

  5. SQL Working Session Task 1: Refer description section to know more about this requirement

  6. sql server tricky interview questions and answers part 29

COMMENTS

  1. SQL Exercises

    SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases.Whether we are beginners or experienced professionals, practicing SQL exercises is essential for our skills and language mastery. In this article, we'll cover a series of SQL practice exercises covering a wide range of topics suitable for beginners, intermediate, and advanced learners.

  2. SQL Exercises

    We have gathered a variety of SQL exercises (with answers) for each SQL Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  3. Top 100+ SQL Interview Questions and Practice Exercises

    This article is packed with over 100 SQL interview questions and practical exercises, organized by topic, to help you prepare thoroughly and approach your interview with confidence. SQL is essential for many jobs, like data analysis, data science, software engineering, data engineering, testing, and many others.

  4. 10 Beginner SQL Practice Exercises With Solutions

    Speaking of practice, let's start with our exercises! The Dataset. Exercise 1: Selecting All Columns From a Table. Exercise 2: Selecting a Few Columns From a Table. Exercise 3: Selecting a Few Columns and Filtering Numeric Data in WHERE. Exercise 4: Selecting a Few Columns and Filtering Text Data in WHERE.

  5. Free SQL exercises

    Use an inner join to link two tables together in a query. Create an inner join in a query, then change it to an outer join to show categories having no events. Join two tables together in SQL, using alias table names. Link the continent, country and event tables with inner joins, and then filter by fields from 2 tables.

  6. Basic SQL Query Practice Online: 20 Exercises for Beginners

    SQL Query Practice. Dataset. Exercise #1: Show the Final Dates of All Events and the Wind Points. Exercise #2: Show All Finals Where the Wind Was Above .5 Points. Exercise #3: Show All Data for All Marathons. Exercise #4: Show All Final Results for Non-Placing Runners. Exercise #5: Show All the Result Data for Non-Starting Runners.

  7. SQL Exercises, Practice, Solution

    What is SQL? SQL stands for Structured Query Language and it is an ANSI standard computer language for accessing and manipulating database systems. It is used for managing data in relational database management system which stores data in the form of tables and relationship between data is also stored in the form of tables. SQL statements are ...

  8. SQL Practice

    In general, try to select only the columns required and not all. Q2. Create a store procedure that receives the first name of the person table as input and the last name as output. In SQL practice, it is necessary to mention the stored procedures because they are frequently used in SQL Server.

  9. Solve SQL

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  10. Twenty-five SQL practice exercises

    Keep in mind there is usually more than one way to obtain the correct answer to a SQL problem. My preference is to use common table expressions ... The projects table contains three columns: task_id, start_date, and end_date. The difference between end_date and start_date is 1 day for each row in the table. If task end dates are consecutive ...

  11. Learn SQL

    Practice SQL querys with an online terminal. Solve SQL query questions using a practice database. Learn and improve your SQL skills.

  12. 10 SQL Code Challenges for Beginners

    5. 47. Your job is to return whether or not the number in the Value column is even or odd rather than returning the number itself. Your query should return the following values: even, odd, odd, even, odd. 5. Group by age. This is the table structure that you'll use for this SQL challenge: id.

  13. Top 41 Technical SQL Interview Questions & Answers [2024]

    View answer. 5. Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name). If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query: Select * From Emp, Dept.

  14. 18 SQL Questions for Beginners: Theory and Practice

    Single Table Queries. Question 1: Elements of an SQL Query. Question 2: Filtering Data in an SQL Query. Data for Questions 3 - 6. Question 3: Select Cats of a Given Age and Breed. Question 4: List Cats Whose Favorite Toy Is a Ball. Question 5: Find the Most Bored Cat.

  15. SQL Practice, Exercises, Exams

    Beginner - Intermediate - Advanced. 12 SQL Server Developer questions. SQL exercises and challenges with solutions PDF. List of free resources to practice MySQL and PostrgreSQL. SQL test evaluation skills, interview questions and theory tests. Exercises for basic, intermediate and advanced level students.

  16. Exercise 6. SQL

    SQL. Tasks: elementary. SqlSum VIEW START. Calculate sum of elements. easy. SqlEventsDelta VIEW START. Compute the difference between the latest and the second latest value for each event type. medium. SqlWorldCup VIEW START. Given a list of matches in a group stage of the soccer World Cup, compute the number of points each team currently has. ...

  17. 20 Advanced SQL Interview Questions (With Answers!)

    5. Monthly Merchant Balance [Visa SQL Interview Question] Say you have access to all the transactions for a given merchant account. Write a query to print the cumulative balance of the merchant account at the end of each day, with the total balance reset back to zero at the end of the month.

  18. SQL Interview Questions CHEAT SHEET (2024)

    Prepare for an SQL interview in 2023 with these most asked real-world SQL interview questions. Save time in Interview preparation. ... Answer 4 simple questions about you and get a path to a lucrative career ... The client application does the task of connecting to this instance and requests data processing to the services. The client can ...

  19. ChatGPT

    Write a message that goes with a kitten gif for a friend on a rough day (opens in a new window)

  20. 50+ Must-Know ETL Interview Questions and Answers for 2024

    Here are some of the most popular ETL tools: Apache Nifi: Known for its easy-to-use, web-based interface and ability to automate data flow between systems. Ideal for real-time data ingestion. Talend: An open-source ETL tool that offers extensive data integration capabilities, including big data and cloud integration.

  21. Relational Database: Definition, Examples, and More

    An RDBMS is a program that enables you to create, update, and perform administrative tasks with a relational database. The difference between a relational database and an RDBMS is that relational databases organize information based on a relational data model. In contrast, RDBMS is database software that allows users to maintain the database.

  22. 20 SQL Practice Problems for Beginner and Intermediate Users

    Table of Contents. 20 SQL Practice Problems with Solutions. Exercise 1: Select All Columns. Exercise 2: Select Multiple Columns. Exercise 3: Select Distinct Values From a Table. Exercise 4: Select Columns Using WHERE. Exercise 5: Select Columns Using WHERE with Text. Exercise 6: Select Columns Using WHERE and LIKE.

  23. Today's NYT 'Strands' Hints, Spangram And Answers For ...

    That's all there is to it for today's Strands clues and answers. Be sure to check my blog for hints and the solution for Tuesday's game if you need them. Follow me on Twitter or LinkedIn .

  24. 4 Phases of the Project Management Lifecycle Explained

    Burndown chart: This chart breaks down tasks on a granular level and visualizes the amount of time remaining. 4. Close projects. In the closing phase of the project management lifecycle, you'll conclude project activities, turn the finished product or service over to its new owners, and assess the things that went well and didn't go so well.

  25. Big Data: Latest Articles, News & Trends

    Big Data Big Data Tableau Review: Features, Pricing, Pros and Cons . Tableau has three pricing tiers that cater to all kinds of data teams, with capabilities like accelerators and real-time analytics.

  26. Complete SQL Practice for Interviews

    It contains over 600 interactive SQL exercises to help you review and practice SQL before an interview. In this article, I'll help you prepare for the by going over some common questions and SQL exercises that recruiters use during the interview process. Basic SQL Whiteboard Questions for Job Interviews

  27. What Is Machine Learning? Definition, Types, and Examples

    Machine learning is a subfield of artificial intelligence that uses algorithms trained on data sets to create models that enable machines to perform tasks that would otherwise only be possible for humans, such as categorizing images, analyzing data, or predicting price fluctuations.. Today, machine learning is one of the most common forms of artificial intelligence and often powers many of the ...

  28. Jrue Holiday Had a Comical One-Word Answer on How to Stop Luka Dončić

    Speaking to reporters on Wednesday, Holiday offered a brutally honest one-word answer when asked how the team is going to slow down the scalding hot Mavericks' duo. "Pray," said Holiday of how he ...

  29. Top 15 SQL Interview Questions in 2021

    5. Name and Explain Some Common Aggregate Functions. In SQL, an aggregate function uses the data from multiple rows to calculate a single result. Common aggregate functions include COUNT (returns the number of rows), SUM (returns the sum of all values in that column), AVG (returns the average value), MIN (returns the smallest value) and MAX ...