Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select Column if Not Null only

I have this mysql code:

SELECT firstname, lastname, age, gender from persons WHERE id = 1;

Display:

> firstname: Marlon 
> 
> lastname: Null
> 
> age: 26
> 
> gender: male

What I want to do is:

SELECT IF NULL DONT SELECT(firstname), IF NULL DONT SELECT(lastname), IF NULL DONT SELECT(age), IF NULL DONT SELECT(gender) from persons WHERE id = 1;

Display:

> firstname: Marlon 
> 
> age: 26
> 
> gender: male

lastname didn't display because its null

like image 223
Marlon Buendia Avatar asked Aug 12 '15 10:08

Marlon Buendia


People also ask

How do you SELECT records without NULL values in SQL?

Below is the syntax to filter the rows without a null value in a specified column. Syntax: SELECT * FROM <table_name> WHERE <column_name> IS NOT NULL; Example: SELECT * FROM demo_orders WHERE ORDER_DATE IS NOT NULL; --Will output the rows consisting of non null order_date values.

IS NOT NULL condition in MySQL?

MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used with SELECT, INSERT, UPDATE and DELETE statements. Syntax: expression IS NOT NULL.

How do you SELECT a column if it is not null in SQL?

To display records without NULL in a column, use the operator IS NOT NULL. You only need the name of the column (or an expression) and the operator IS NOT NULL (in our example, the price IS NOT NULL ).

Is not null or empty in MySQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

Certainly you can't do that; rather you can use COALESCE() or IFNULL() function to provide a default value in case of NULL like

SELECT firstname, 
COALESCE(lastname,'N/A'),
age,
gender from persons WHERE id = 1;

(OR) if you want to remove that record completely then use a WHERE condition like

SELECT firstname, lastname, age, gender from persons 
WHERE id = 1 AND lastname IS NOT NULL;
like image 52
Rahul Avatar answered Sep 30 '22 19:09

Rahul


even there is no way to hide column but yes you can avoid null value in output. So there can be below 2 ways-

Method 1: You can keep field blank where it is null.

SELECT IFNULL(firstname,'') AS firstname, 
IFNULL(lastname,'') AS lastname, 
IFNULL(age,'') AS age, 
IFNULL(gender,'') AS gender 
FROM persons WHERE id = 1;

Method2: You can get all values in single column using concatenate function.

SELECT CONCAT
(
IFNULL(firstname,''),' ',
 IFNULL(lastname,''),' ', 
IFNULL(age,''),' ', 
IFNULL(gender,'')
) 
FROM persons WHERE id = 1;
like image 27
Zafar Malik Avatar answered Sep 30 '22 19:09

Zafar Malik