{"id":26512935,"url":"https://github.com/aswekkk129/sql_interview","last_synced_at":"2026-05-01T03:38:43.589Z","repository":{"id":281810366,"uuid":"946497231","full_name":"Aswekkk129/SQL_Interview","owner":"Aswekkk129","description":"Peparation for SQL technical assessments. Real SQL Interview Questions","archived":false,"fork":false,"pushed_at":"2025-03-12T22:01:18.000Z","size":153,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-21T04:19:03.551Z","etag":null,"topics":["markdown","sql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Aswekkk129.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-11T08:29:51.000Z","updated_at":"2025-03-12T22:01:22.000Z","dependencies_parsed_at":"2025-03-11T09:33:45.583Z","dependency_job_id":"00f0b2bd-dea7-4fc4-8e3a-ba2881b81cbb","html_url":"https://github.com/Aswekkk129/SQL_Interview","commit_stats":null,"previous_names":["vlinling/sql_interview","aswekkk129/sql_interview"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aswekkk129%2FSQL_Interview","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aswekkk129%2FSQL_Interview/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aswekkk129%2FSQL_Interview/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aswekkk129%2FSQL_Interview/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Aswekkk129","download_url":"https://codeload.github.com/Aswekkk129/SQL_Interview/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244734196,"owners_count":20501018,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["markdown","sql"],"created_at":"2025-03-21T04:19:08.154Z","updated_at":"2026-05-01T03:38:43.517Z","avatar_url":"https://github.com/Aswekkk129.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL_Interview\n\n### This repository is primarily my collection of challenging SQL interview questions. I hope that each case not only helps you learn various SQL functions and CTEs, but also guides you through a practical problem-solving process using actual SQL queries, ultimately serving as a valuable resource for enhancing your SQL knowledge and interview preparation.\n---\n\n# SQL Query Analysis and Rewrite\n\nThis document contains the analysis, rewrite, and explanation of two SQL queries. The goal is to improve readability and maintainability by using Common Table Expressions (CTEs). Each query is broken down step-by-step for clarity.\n\n---\n\n## **Query 1: Check if the Second Item Sold by a User is Their Favorite Brand**\n\n### **Problem Statement**\nWe want to determine whether the second item sold by each user (as a seller) matches their favorite brand (`fav_brand`). This involves:\n1. Identifying the second item sold by each user.\n2. Comparing the brand of that item with the user's favorite brand.\n\n### **Rewritten SQL Code**\n```sql\nWITH RankedOrders AS (\n    -- Step 1: Get all items sold by each user and rank them by order time\n    SELECT \n        u.user_id AS seller_id,\n        u.fav_brand,\n        o.item_id,\n        o.order_at,\n        RANK() OVER (PARTITION BY u.user_id ORDER BY o.order_at) AS rank_order\n    FROM tb_users u\n    LEFT JOIN tb_orders o\n    ON u.user_id = o.seller_id\n),\nSecondItemDetails AS (\n    -- Step 2: Filter for the second item sold by each user\n    SELECT \n        ro.seller_id,\n        ro.fav_brand,\n        ro.item_id\n    FROM RankedOrders ro\n    WHERE ro.rank_order = 2\n),\nItemBrandInfo AS (\n    -- Step 3: Get the brand information for the second item\n    SELECT \n        sid.seller_id,\n        sid.fav_brand,\n        i.item_brand\n    FROM SecondItemDetails sid\n    LEFT JOIN tb_items i\n    ON sid.item_id = i.item_id\n)\n-- Step 4: Compare the second item's brand with the user's favorite brand\nSELECT \n    ibi.seller_id AS user_id,\n    CASE \n        WHEN ibi.fav_brand = ibi.item_brand THEN 'yes'\n        ELSE 'no'\n    END AS is_2nd_item_fav_brand\nFROM ItemBrandInfo ibi;\n```\n\n### **Step-by-Step Explanation**\n1. **RankedOrders CTE**:\n   - Joins `tb_users` and `tb_orders` to get all items sold by each user.\n   - Uses the `RANK()` function to assign a ranking to each order based on the `order_at` timestamp.\n\n2. **SecondItemDetails CTE**:\n   - Filters the results to include only the second item sold by each user (`rank_order = 2`).\n\n3. **ItemBrandInfo CTE**:\n   - Joins the second item details with `tb_items` to retrieve the brand of the second item.\n\n4. **Final Query**:\n   - Compares the user's `fav_brand` with the brand of the second item.\n   - Outputs `'yes'` if they match, otherwise `'no'`.\n\n---\n\n## **Query 2: List All Users with Their 2018 Purchase and Sales Amounts**\n\n### **Problem Statement**\nAs a marketing manager, you need a list of all users with the following information:\n1. User ID (`user_id`).\n2. Join date (`joined_at`).\n3. Total purchase amount in 2018.\n4. Total sales amount in 2018.\n\n### **Rewritten SQL Code**\n```sql\nWITH UserPurchases AS (\n    -- Step 1: Calculate the total purchase amount for each user in 2018\n    SELECT \n        u.user_id,\n        DATE(u.joined_at) AS joined_date,\n        SUM(CASE WHEN YEAR(o.order_at) = 2018 THEN o.order_amount ELSE 0 END) AS purchase_amount\n    FROM tb_users u\n    LEFT JOIN tb_orders o\n    ON u.user_id = o.buyer_id\n    GROUP BY u.user_id, DATE(u.joined_at)\n),\nUserSales AS (\n    -- Step 2: Calculate the total sales amount for each user in 2018\n    SELECT \n        u.user_id,\n        SUM(CASE WHEN YEAR(o.order_at) = 2018 THEN o.order_amount ELSE 0 END) AS sales_amount\n    FROM tb_users u\n    LEFT JOIN tb_orders o\n    ON u.user_id = o.seller_id\n    GROUP BY u.user_id\n)\n-- Step 3: Combine purchase and sales amounts\nSELECT \n    up.user_id,\n    up.joined_date,\n    up.purchase_amount,\n    us.sales_amount\nFROM UserPurchases up\nLEFT JOIN UserSales us\nON up.user_id = us.user_id;\n```\n\n### **Step-by-Step Explanation**\n1. **UserPurchases CTE**:\n   - Joins `tb_users` and `tb_orders` to get all orders where the user is the buyer.\n   - Uses a `CASE` statement to calculate the total purchase amount for 2018.\n   - Groups the results by `user_id` and `joined_at`.\n\n2. **UserSales CTE**:\n   - Similar to `UserPurchases`, but focuses on orders where the user is the seller.\n   - Calculates the total sales amount for 2018.\n   - Groups the results by `user_id`.\n\n3. **Final Query**:\n   - Combines the purchase and sales amounts by performing a `LEFT JOIN` between `UserPurchases` and `UserSales`.\n   - Outputs the final result with all required fields.\n\n---\n\n## **Conclusion**\n- Both queries have been rewritten using CTEs to improve readability and maintainability.\n- The step-by-step breakdown ensures that the logic is easy to follow and debug.\n- Using CTEs makes the queries modular, allowing for easier modifications or extensions in the future.\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswekkk129%2Fsql_interview","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faswekkk129%2Fsql_interview","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswekkk129%2Fsql_interview/lists"}