Skip to content

Instantly share code, notes, and snippets.

@f3l1x
Last active May 26, 2022 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f3l1x/a68e2bfe3a5be13db95ddc0d3d6bcc6b to your computer and use it in GitHub Desktop.
Save f3l1x/a68e2bfe3a5be13db95ddc0d3d6bcc6b to your computer and use it in GitHub Desktop.
SQL utils (Postgres / MySQL MariaDB)
select 'SELECT SETVAL(' || seq [ 1] || ', COALESCE(MAX('||column_name||')+1, 1) ) FROM '||table_name||';'
from (
SELECT table_name, column_name, column_default, regexp_match(column_default, '''.*''') as seq
from information_schema.columns
where column_default ilike 'nextval%'
) as sequense_query
-- Reset sequence
DO $$
DECLARE
i TEXT;
BEGIN
FOR i IN (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public') LOOP
EXECUTE 'Select setval('''||i||'_id_seq'', (SELECT max(id) as a FROM "'||i||'")+1);';
END LOOP;
END$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment