Skip to main content

SQL Interview Question - 3


Consider two tables, employees and departments, with the following structures:

    
    employees:
    | employee_id | employee_name | department_id |
    |-------------|---------------|---------------|
    | 1           | Alice         | 1             |
    | 2           | Bob           | 2             |
    | 3           | Charlie       | 1             |
    | 4           | David         | 3             |

    departments:
    | department_id | department_name |
    |---------------|-----------------|
    | 1             | Sales           |
    | 2             | Marketing       |
    | 3             | Finance         |
    
    

Write an SQL query to list all employees along with their department names. If an employee does not belong to any department, the department name should be displayed as "No Department".

Solution:

    
    SELECT e.employee_name, COALESCE(d.department_name, 'No Department') AS department_name
    FROM employees e
    LEFT JOIN departments d ON e.department_id = d.department_id;
    
    

Explanation:

  • We use a LEFT JOIN to ensure all rows from the employees table are included in the result, regardless of whether there is a matching row in the departments table.
  • The COALESCE function is used to replace NULL values in the department_name column with "No Department", which happens when an employee does not belong to any department.
  • We join the employees table with the departments table on the department_id column to match employees with their respective departments.
  • The COALESCE function ensures that if there's no matching department for an employee, it will display "No Department" instead of a NULL department name.

 

Share your alternate solution in comments.

Comments

Other popular job openings

NTT DATA North America is hiring for an fresher entry level AI/ML Engineer role in India

Position: AI/ML Engineer (AI Data Engineer) - As per the JD, it is a Data Science role, not a DE role Company: NTT DATA North America Location: Hyderabad, Telangana, India Job type: Full-time Job mode: Onsite Job requisition id: 303765 Years of experience: 0–3 years Company Description  NTT DATA is a global IT services provider and part of the NTT Group, operating across more than 50 countries. It serves over 75% of Fortune Global 100 companies and is valued at $30 billion in revenue. With over 26,000 employees in North America alone, it delivers business and technology solutions to help clients innovate and transform. The company invests over $3.6 billion annually in R&D, with particular focus on AI, digital transformation, and sustainable tech infrastructure. Services include consulting, systems integration, application services, data and AI, cloud infrastructure, and managed services. NTT DATA is known for a strong ecosystem of partne...

DeHaat is hiring for a Data Analyst Intern role in India

Position: Data Analyst & Product Support Intern Company: DeHaat Location: Gurugram, Haryana, India Job type: Internship Job mode: Onsite Job requisition id: Not specified Years of experience: Open for college students, freshers and people looking for career transition (but have required skills) Company Description  DeHaat is a leading AgriTech company in India, providing integrated solutions to farmers through its digital platforms and on-ground infrastructure The company supports every stage of the agricultural lifecycle, from input procurement to selling produce It uses AI-based tools to deliver customized crop advisory, high-quality input access, and market linkage for outputs With a growing network and multiple acquisitions like AgriCentral, DeHaat is continuously expanding its reach and capabilities Headquartered in Patna and Delhi NCR, it currently operates across multiple Indian states and serves millions of farmers Its rapid grow...

Numerator is hiring for an fresher entry level REMOTE Data Scientist role in India

Position: Data Scientist (REMOTE) Company: Numerator Location: Remote, India Job type: Full-Time Job mode: Remote Job requisition id: 602503 Years of experience: 0-3 years Company description: Numerator is a global market research company dedicated to transforming the way companies understand their customers and the marketplaces they compete in. The company specializes in delivering advanced and insightful data to some of the world’s most respected brands and retail organizations. By utilizing cutting-edge technology and a range of advanced data science methodologies, Numerator enables companies to respond to changes in customer behavior and make more informed decisions. Numerator is built on a people-first culture that emphasizes the diverse strengths and talents of its employees and celebrates the unique contributions of each member of its team. The company supports its team with competitive benefits like wellness programs, career development op...

Sprinklr is hiring for a fresher entry level Associate Machine Learning role in India

Position: Associate Machine Learning Company: Sprinklr Location: India (Gurgaon, Haryana and Bangalore, Karnataka) Job type: Full-time Job mode: Onsite Job requisition id: 111365-JOB Years of experience: 0–2 years Company Description  Sprinklr is a global enterprise software company focused on delivering unified customer experience management (Unified-CXM). The company was founded with the aim of helping businesses provide seamless, personalized customer interactions across modern communication channels. Headquartered in New York City, Sprinklr employs over 2,400 people globally. It partners with more than 1,000 of the world’s top enterprises, including big names like Microsoft, Procter & Gamble, and Samsung. Sprinklr’s platform integrates various tools that cater to marketing, advertising, research, care, and engagement, enabling a truly connected customer experience. The company positions itself not only as a tech leader but also as an...

DP World is hiring for a fresher entry level Machine Learning Scientist role in India (college Students can also apply)

Position: Machine Learning Scientist Company: DP World Location: Bangalore, Karnataka, India Job type: Full-time Job mode: Onsite Job requisition id: 15097 Years of experience: 0-1 Year ( students who recently started 4th year can also apply ) Company description: DP World is one of the most respected global logistics and supply chain companies operating across diverse geographies and helping businesses navigate complex trade routes with ease. The company believes in creating solutions that transform international trade, making logistics seamless for its customers, and delivering value through innovation and technology. With a strong commitment to sustainability and diversity, DP World integrates smart trade into every part of its operations. They have a proven record of using technology to optimize processes in ports, terminals, and end-to-end supply chains across industries worldwide. DP World fosters an open culture where people collaborate to...

Precision AQ is hiring for a fresher entry level Data Analyst role in India

Position: Data Analyst Company: Precision AQ Location: Pune, Maharashtra, India Job type: Full-time Job mode: Hybrid Job requisition id: 292441 Years of experience: 0-2 years Company description: Precision AQ is a global player in business consulting and services, specializing in helping life sciences companies navigate the complex process of bringing their products to market. The company is highly focused on improving access to new therapies by supporting pricing and reimbursement strategies, as well as offering market access solutions that facilitate commercialization across different geographies. Its teams work across commercial consulting, HEOR, medical communications, data analytics, and international healthcare communications to support clients throughout a product's lifecycle. Driven by the core belief that data-driven decisions and empathy can reduce barriers for patients, Precision AQ fuses scientific excellence with a deep understanding...

Bain & Company is hiring for an fresher entry level Data Analyst role in India

Position: Data Analyst, D&I Consumer Lab Company: Bain & Company Location: Gurugram, Haryana, India Job type: Full-time Job mode: Hybrid Job requisition id: Not specified Years of experience: 0 to 1.5 years (0–18 months) Company description Bain & Company is a global management consulting firm known for working closely with leading businesses, governments, and institutions to drive sustainable and measurable outcomes. With a presence in 65 cities across 40 countries, Bain brings together people, knowledge, and advanced analytics to provide transformative strategies that fuel success. Since its founding in 1973, Bain has built a reputation for delivering results-driven consulting, maintaining a culture of client advocacy, and standing out as a leader in innovation. In India, Bain began operations in 2004 through the Bain Capability Network (BCN), originally known as the Bain Capability Center. BCN supports Bain’s global consulting effor...

Optum is hiring for an fresher entry level AI/ML Engineer role in India

Position: AI/ML Engineer Company: Optum (a part of UnitedHealth Group) Location: New Delhi, Delhi, India Job type: Full-time Job mode: Onsite Job requisition id: 2283519 Years of experience: 0–3 years Company description  Optum is a global health services company that belongs to the UnitedHealth Group family. The company works across the healthcare ecosystem to improve outcomes, reduce costs, and deliver insights using data and technology. They specialize in areas such as pharmacy care services, healthcare delivery, data analytics, and technology-driven solutions for both individuals and organizations. Optum is focused on transforming the healthcare experience by providing tools and services that make systems more efficient and effective. Its workforce includes clinicians, data scientists, engineers, and experts from a wide range of fields. With innovation at its core, Optum continually builds digital platforms and data-driven tools that red...

WeCredit is hiring for an fresher entry level Business Analyst role in India

Position: Business Analyst Company: WeCredit Location: Delhi, India Job type: Full-time Job mode: Onsite Job requisition id: 1499194 Years of experience: 0-1 Years Company description WeCredit is a fast-growing fintech company helping customers navigate the landscape of financial solutions. The company partners with leading Non-Banking Financial Companies to offer seamless financial products. They make the process of loan approvals quick and hassle-free for every applicant. The team at WeCredit takes pride in providing personal assistance to each client at every stage of the process. Customers appreciate their transparent policies, timely updates, and one-stop solutions for their financial needs. Beyond loans, they also aim to deliver data-driven innovations that improve access to credit. With technology at its core, WeCredit simplifies complex financial processes for people. The company culture fosters collaboration, integrity, and continuo...

Kiwi Kisan Window is hiring for a fresher entry level Associate Data Scientist (in Analytics) role in India

📌 Position: Associate Data Scientist (this is more of a Data Analyst role as per the job description) 🏢 Company: Kiwi Kisan Window 📍 Location: Dehradun, Uttarakhand, India 💼 Job type: Full-time 🖥️ Job mode: Onsite 🧑‍💻 Job requisition ID: Not specified 🕰️ Years of experience: 0-1 year 🏭 Company description Kiwi Kisan Window is an innovative social-entrepreneurship venture working toward making organic food accessible and mainstream. The company bridges local farmers with consumers to promote a healthier, more sustainable lifestyle. It operates retail stores in Dehradun and is expanding into e-commerce for organic and conscious foods. Kiwi aims to present farm-fresh produce and healthy staples with a sensory experience that’s appealing across sight, taste, touch, and smell. They focus on integrity and transparency in the supply chain, bringing high-quality products directly to health-conscious customers. Kiwi’s business model supports loc...