October 24, 2024
Chicago 12, Melborne City, USA
SQL

Query SQL prioritizing presence of two columns


I have a table zipnames with four columns: id, zipcode, name_fi and name_sv. Both of the name_* columns are nullable. For each possible zipcode, I might have up to four rows: both names present, only name_fi present, only name_sv present, or both null.

How can I write a SELECT for this table so that I can get only one row back for each zipcode, prioritizing rows with both languages present, then rows with only one language, and only returning nulls for both languages if we really don’t have a row with either name?

If it makes a difference, I’m working with PostgreSQL v14, and using SQLAlchemy in Python. Feel free to answer either in plain SQL or as SQLAlchemy code.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video