VLOOKUP in SQL

VLOOKUP finds a value in one table and returns a matching column from the same row; in SQL the same job is done with a join.

The Excel version

=VLOOKUP(A2, Customers!A:C, 3, FALSE)

The SQL equivalent

This example assumes: orders(id bigint, customer_id bigint, total_amount numeric), customers(id bigint, name text, country text). It is written in PostgreSQL syntax, and your table and column names will differ from these.

SELECT o.id,
       o.total_amount,
       c.country
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
ORDER BY o.id;

How it works

  • The join condition c.id = o.customer_id is the lookup key, like the first argument of VLOOKUP.
  • Selecting c.country returns the column you would have asked for with the column index number.
  • LEFT JOIN keeps every order even when no customer matches, which is the case where Excel shows #N/A; here country is simply null.

Where the results differ from Excel

  • VLOOKUP returns only the first match; a join returns one row per match, so duplicate customer ids multiply your orders and inflate totals.
  • Excel's exact match is case-insensitive; SQL text comparison is case-sensitive in PostgreSQL unless you lower-case both sides.
  • A missing match is #N/A in Excel and null in SQL; wrap it in COALESCE for a default label.

Skip the query: ask in plain English

If you would rather not write SQL, type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. Check that the result matches how your spreadsheet defines the number.

  • Add each customer's country to the orders list.
  • Show orders whose customer is missing from the customers table.

Frequently asked questions

What is the SQL equivalent of VLOOKUP?
VLOOKUP finds a value in one table and returns a matching column from the same row; in SQL the same job is done with a join.
How does the SQL version of VLOOKUP work?
The join condition c.id = o.customer_id is the lookup key, like the first argument of VLOOKUP. Selecting c.country returns the column you would have asked for with the column index number. LEFT JOIN keeps every order even when no customer matches, which is the case where Excel shows #N/A; here country is simply null.
Why can SQL give a different result from VLOOKUP?
VLOOKUP returns only the first match; a join returns one row per match, so duplicate customer ids multiply your orders and inflate totals.