CS TECHIIE

SQL Program 35: Categorise salary using CASE

SQL learning illustration

CS TECHIIE | SQL Notes and Solutions

Practical SQL exercise: Assigns a category based on salary.

Objective

Assigns a category based on salary.

Explanation

Read the statement clause by clause and predict the result before executing it. These examples use common relational SQL; table setup and exact syntax can vary between MySQL, PostgreSQL, SQL Server, Oracle and SQLite.

Safety check

Before running UPDATE or DELETE, run a SELECT with the same WHERE condition. Use a test database and a transaction for changes you need to verify.

Program / SQL Solution

SELECT employee_name,salary,CASE WHEN salary>=70000 THEN 'High' WHEN salary>=40000 THEN 'Medium' ELSE 'Entry' END AS band FROM employees;

Practice and revision

  • Run the example and verify the output.
  • Change the input and test normal, boundary and invalid cases.
  • Write the solution again without looking at the notes.

Learn • Practise • Build • Secure — CS TECHIIE