I am trying to remove and drop a table if the the table has no data or empty, so I wrote this Statement in PostgreSQL, but I am encountering an error saying syntax error near IF.
I can divide this to 2 different SQL statements, but I want to run this as one query.
IF (SELECT COUNT(*) FROM ${tableName}) > 0
BEGIN
DROP TABLE ${tableName}
END
I also tried this:
IF (SELECT COUNT(*) FROM zzz > 0) THEN
DROP TABLE zzz
END IF
ERROR: syntax error at or near "SELECT"
LINE 2: SELECT COUNT(*) FROM zzz > 0
^
SQL state: 42601
Character: 7
If you want to do this with SQL, you'll have to use a DO statement:
DO
$$BEGIN
IF (SELECT Count(*) FROM zzz) > 0 THEN
DROP TABLE zzz;
END IF;
END;$$;
Related
I am trying to create a CTE which establishes a parent child relationship and return the ids of the required childs. The Childs can also be the parent of their respective children. I have tried writing a postgresql function for that but I am facing an error, for which I am not able to understand the cause. Might be a very silly reason or syntax error, so far I have no clue. The error is 'ERROR: syntax error at or near "return"
LINE 22: return query
^
SQL state: 42601
Character: 472'
create or replace function fn_Get_All_Child_For_Process(
client_id integer,process_id integer,level integer)
returns table (id integer)
language 'plpgsql'
as
$$
begin
WITH CTE_Child AS
(
SELECT Id,level,ParentId
FROM ClientProcesses
WHERE ID = process_id and ClientId=client_id and Level < level
UNION ALL
SELECT t.Id,t.level,t.ParentId
FROM ClientProcesses t,CTE_Child C
where t.ParentID = C.ID and t.Level < level and t.ClientId=client_id
)
return query
SELECT C.Id FROM CTE_Child C where C.Id not in (process_id) ;
end;
$$;
Please can someone help on how to do this.
I have a log table as below where i am deleting all tables beyond 3 months.
Now i want add another step to clear the log table as well when the above step has been actioned. Example: drop the table if > 90 days then delete the associated rows from the log table too.
thanks
ddl_date ddl_tag ID object_name
2022-07-07 16:40:06 CREATE FOREIGN 1 raj.auth
2022-02-07 17:14:33 CREATE TABLE 6 john.plots_source
2022-03-07 17:14:33 CREATE TABLE 7 john.plots1
2022-04-07 17:14:33 CREATE TABLE 8 johnb.plots_pkey2
2022-05-07 17:14:33 CREATE TABLE 9 johna.plots_address3
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN
(
SELECT id, object_name from user_monitor.ddl_history WHERE ddl_date < NOW() - INTERVAL '90 days'
)
LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || r.object_name || ' CASCADE';
END LOOP;
delete from user_monitor.ddl_history where not exists (select tablename from pg_catalog.pg_tables b where r.object_name = b.tablename);
commit;
END $$ ;
SQL Error [42601]: ERROR: query has no destination for result data
Hint: If you want to discard the results of a SELECT, use PERFORM
instead. Where: PL/pgSQL function inline_code_block line 12 at SQL
statement
You're referencing r.object_name outside of the LOOP.
Try pulling the DELETE statement inside the LOOP so that "r" is a valid reference that can cycle among all cursor values within the execution context.
I have an Employee table with column - Id, FirstName, isGlobal, Age. I am writing below SQL to check if the Employee already exists in DB or not. I want to store the Id and isGlobal into variable for further processing in my stored function.
SELECT Id, CASE WHEN (isGlobal IS NULL) THEN 1 ELSE 0 END
INTO o_NameId, o_IsGlobal
FROM Employee
WHERE firstName='test';
On running this SQL, it gives me syntax error.
ERROR: syntax error at or near ","
LINE 2: INTO o_NameId, o_IsGlobal
^
SQL state: 42601
What's wrong with my SQL?
Any help would be greatly appreciated.
looks like o_NameId and o_IsGlobal are not declared,
try:
DO
$$
DECLARE
o_NameId int;
o_IsGlobal int;
BEGIN
SELECT Id, CASE WHEN (isGlobal IS NULL) THEN 1 ELSE 0 END
INTO o_NameId, o_IsGlobal
FROM Employee
WHERE firstName='test';
END
$$;
also try to follow SQL name convention like:
SQL keywords: UPPER CASE
names (identifiers) lower_case_with_underscores List item
I have a crosstab function that I've used successfully many times in the past, but now it's dumping all the data at the end instead of pivoting it into the output table. It can't seem to find Crosstab. I've researched it doing the following;
create extension if not exists tablefunc; --- answer is: extension "tablefunc" already exists
create extension tablefunc with schema animals; answer is: as above
select count(*) from information_schema.routines where routine_name like 'crosstab%'; ---- answer is 6.
The following is a section of the function code:
BEGIN
str := '" " text,'; -- blanks in A1 cell
FOR rec IN SELECT DISTINCT col_name
FROM an_in_tbl
ORDER BY col_name
LOOP
str := str || '"' || rec.col_name || '" text' ||',';
END LOOP;
str:= substring(str, 0, length(str));
EXECUTE 'CREATE EXTENSION IF NOT EXISTS tablefunc;
DROP TABLE IF EXISTS an_out_tbl;
CREATE TABLE an_out_tbl AS
SELECT *
FROM crosstab(''select row_name, col_name, row_value from an_in_tbl order by 1'',
''SELECT DISTINCT col_name FROM an_in_tbl ORDER BY 1'')
AS final_result ('|| str ||')';
select animal_pivot_fn()
NOTICE: extension "tablefunc" already exists, skipping
NOTICE: table "an_out_tbl" does not exist, skipping
ERROR: function crosstab(unknown, unknown) does not exist
LINE 5: FROM crosstab('select row_name, col_name, row_value from...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
QUERY: CREATE EXTENSION IF NOT EXISTS tablefunc;
DROP TABLE IF EXISTS an_out_tbl;
CREATE TABLE an_out_tbl AS
SELECT *
FROM crosstab('select row_name, col_name, row_value from an_in_tbl order by 1',
'SELECT DISTINCT col_name FROM an_in_tbl ORDER BY 1')
AS final_result (" " text,"CAT" text,"DOG" text,"SNAKE" text,"HORSE" text,"ELEPHANT" text,"MOUSE" text,"MONKEY"... and many more... HERE IS WHERE THE DATA GETS DUMPED AND NO PIVOTED TABLE GETS CREATED.
Need to run below query
Run \dx command .
if result like below need to run following query
CREATE EXTENSION tablefunc;
Run \dx command again,result should be like below.
Now you can run crosstab query it should be solved.
I am trying to execute an SQL statement in pgadmin3 that do the following:
If a student with a specific name and age already exists then get the student_id else insert a new record with the specified name and age and then get the created student_id
I have tried this code:
IF EXISTS (SELECT 1 FROM main.student WHERE studentname='hhh' and studentage=15)
BEGIN
SELECT student_id FROM main.student WHERE studentname='hhh' and studentage=15
END
ELSE
BEGIN
INSERT INTO main.student(studentname,studentage) VALUES('hhh',15)
END;
END IF;
But I am always getting this error:
syntax error at or near "IF"
SQL state: 42601
Character: 1
Can you please tell me what I am doing wrong. Also how can I get the student_id after the insert statement?
Actually your statement is not SQL. it is PL/PGSQL statement.
So obviously when you send this to Postgres as SQL query it will throw an exception.
If you are doing this from pgAdmin3 it has nice feature to run pl/psql scripts. use it
IF EXISTS (SELECT 1 FROM main.student WHERE studentname='hhh' and studentage=15) THEN
SELECT student_id FROM main.student WHERE studentname='hhh' and studentage=15;
ELSE
INSERT INTO main.student(studentname,studentage) VALUES('hhh',15);
END IF;
Some points you need to consider:
For IF statement, you need to use THEN
To run just one syntax, you don't need the BEGIN/END
Use ; at the end of each statement
Also if you are running an ad-hoc statement, you need to run it within DO command
DO
$do$
IF EXISTS (SELECT 1 FROM main.student WHERE studentname='hhh' and studentage=15) THEN
SELECT student_id FROM main.student WHERE studentname='hhh' and studentage=15;
ELSE
INSERT INTO main.student(studentname,studentage) VALUES('hhh',15);
END IF;
END
$do$
For the last part of your question, you can return the id you are inserting
INSERT INTO main.student(studentname,studentage) VALUES('hhh',15) RETURNING student_id