Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql select null and non null values in WHERE clause

I am trying to run a query that selects values from a table using a WHERE clause , the query only returns the rows where all of the conditions have values, hoe do I go about returning the values that are also null?

     Language Table                            Students Table
 ID    Language                        ID      Student      LanguageID
  1     English                         1        Joe
  2     Spanish                         2        Mike          1

Running a query such as

Select student.ID , Student.Student , Language.language 
FROM 
    Students, Language 
WHERE 
    student.LanguageID = Language.id 

The query only returns a single row for student mike I would like to return all student even if the language setting is null.

like image 674
Adonis L Avatar asked Apr 10 '26 01:04

Adonis L


2 Answers

You want something like this:

select
  student.id, student.student, language.language
from
  student left join language
      on student.languageid = language.languageid
like image 90
Ken Redler Avatar answered Apr 12 '26 15:04

Ken Redler


You should not use the comma syntax for joining tables. Use the ISO syntax of JOIN or in this case LEFT OUTER JOIN (which in pretty much all DBMS can be shortened to Left Join):

Select Student.Id, Student.Student. Language.Language
From Students 
    Left Join Language
        On Language.Id = Student.LanguageId

This will return all students and their language if they have one or null if they do not have one.

like image 32
Thomas Avatar answered Apr 12 '26 14:04

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!