2009-04-10 18 views
43

estoy usando Postgres y yo estoy tratando de escribir una consulta como esta:Postgres - ¿Cómo comprobar si hay una matriz vacía

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

es decir, que quieren saber cuántas filas tiene una matriz vacía para una columna, pero ciertas postgres no le gusta que:

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

... si datasets = NULL representa ARRAY [], las respuestas son correctas ... Acerca de "ARRAY []", es un error de sintaxis (!): Como respondió depesz, una matriz vacía también necesita el tipo de datos, SQL de Rory el script necesita corrección, es "ARRAY [] :: integer". –

Respuesta

60

La sintaxis debe ser:

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

se utiliza citas más llaves t o mostrar literales de matriz.

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

Aunque eso podría funcionar, simplemente se ve un poco desordenado. – Rory

14

Puede utilizar el hecho de que array_upper y array_lower funciones, en matrices vacías devolver null , para que pueda:

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

... ok si datasets = NULL representa ARRAY [], pero y sobre "ARRAY []", es un error de sintaxis (!). ¿Cómo crear una matriz vacía? –

+0

es un error solo porque no puede decir en qué tipo de datos está desactivada la matriz. agregar conversión: seleccione 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} 
Cuestiones relacionadas