2009-04-10 12 views
43

sto usando Postgres e sto cercando di scrivere una query come questa:Postgres - Come verificare la presenza di un array vuoto

select count(*) from table where datasets = ARRAY[] 

cioè voglio sapere quante righe hanno una matrice vuota per un alcune delle colonne, ma Postgres non piace che:

select count(*) from super_eds where datasets = ARRAY[]; 
ERROR: syntax error at or near "]" 
LINE 1: select count(*) from super_eds where datasets = ARRAY[]; 
                  ^
+0

... se set di dati = NULL rappresenta ARRAY [], le risposte sono OK ... Informazioni su "ARRAY []", è un errore di sintassi (!): Come ha risposto Depesz, anche un array vuoto ha bisogno di un datatype, Rory's SQL lo script necessita di correzione, è "ARRAY [] :: intero". –

risposta

60

La sintassi dovrebbe essere:

SELECT 
    COUNT(*) 
FROM 
    table 
WHERE 
    datasets = '{}' 

Si utilizza citazioni più parentesi graffe t o mostra letterali di array.

0
SELECT COUNT(*) 
FROM table 
WHERE datasets = ARRAY(SELECT 1 WHERE FALSE) 
+0

Anche se potrebbe funzionare, sembra un po 'disordinato. – Rory

14

È possibile utilizzare il fatto che array_upper e array_lower funzioni, su array vuoti restituire null , in modo da poter:

select count(*) from table where array_upper(datasets, 1) is null; 
+0

... ok se set di dati = NULL rappresenta ARRAY [], ma riguardo a "ARRAY []", si tratta di un errore di sintassi (!). Come creare un array vuoto ?? –

+0

è un errore solo perché non è in grado di dire quale tipo di dati è fuori dalla matrice. aggiungere cast: selezionare ARRAY [] :: int4 []; –

2
 
Solution Query: 
select * from table where array_column = ARRAY[NULL]::array_datatype; 
 
Example: 

table_emp:

id (int)| name (character varying) | (employee_id) (uuid[]) 
1  | john doe     | {4f1fabcd-aaaa-bbbb-cccc-f701cebfabcd, 2345a3e3-xxxx-yyyy-zzzz-f69d6e2edddd } 
2  | jane doe     | {NULL} 


select * from tab_emp where employee_id = ARRAY[NULL]::uuid[]; 

    ------- 
2  | jane doe     | {NULL} 
Problemi correlati