sql
  1. sql-elt-function

Advanced SQL Topics: ELT Function

Syntax

ELT(n, value1, value2, ..., valueN)

Example

Suppose we have a table named employees with the following columns: employee_id, first_name, last_name, and salary. The table contains the following data:

employee_id first_name last_name salary
1 John Smith 50000
2 Jane Doe 60000
3 Adam Johnson 70000

We can use the ELT function to select the first or nth value from a list:

SELECT ELT(1, first_name, last_name) as name, salary
FROM employees;

Output:

name salary
John 50000
Jane 60000
Adam 70000
SELECT ELT(2, first_name, last_name) as name, salary
FROM employees;

Output:

name salary
Smith 50000
Doe 60000
Johnson 70000

Explanation

The ELT function returns the nth value from a list of values. The first argument is the number of the value to return (an integer). The subsequent arguments are the values to select from. If the first argument is larger than the number of values in the list, the function returns NULL.

Use

The ELT function can be used to select data based on a specific condition or criteria. For example, we can use the ELT function to select the second highest salary from a table of employees:

SELECT last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 1, 1;

Output:

last_name salary
Doe 60000

We can also use the ELT function to select values from different columns and concatenate them into a single output value.

Important Points

  • The ELT function returns the nth value from a list of values.
  • The first argument is the number of the value to return (an integer).
  • The subsequent arguments are the values to select from.
  • If the first argument is larger than the number of values in the list, the function returns NULL.

Summary

The ELT function is a useful tool in SQL that allows you to select specific values from a list based on position. It is particularly useful when you need to select data based on a specific condition or when you need to concatenate values from different columns into a single output.

Published on: