Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rows that no foreign keys point to

Tags:

sql

postgresql

I have two tables

CREATE TABLE public.city_url
(
  id bigint NOT NULL DEFAULT nextval('city_url_id_seq'::regclass),
  url text,
  city text,
  state text,
  country text,
  common_name text,
  CONSTRAINT city_url_pkey PRIMARY KEY (id)
)

and

CREATE TABLE public.email_account
(
  id bigint NOT NULL DEFAULT nextval('email_accounts_id_seq'::regclass),
  email text,
  password text,
  total_replied integer DEFAULT 0,
  last_accessed timestamp with time zone,
  enabled boolean NOT NULL DEFAULT true,
  deleted boolean NOT NULL DEFAULT false,
  city_url_id bigint,
  CONSTRAINT email_accounts_pkey PRIMARY KEY (id),
  CONSTRAINT email_account_city_url_id_fkey FOREIGN KEY (city_url_id)
      REFERENCES public.city_url (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I want to come up with a query that fetches rows in the city_url only if there is no row in the email_account pointing to it with the city_url_id column.

like image 608
Arya Avatar asked Jan 20 '17 13:01

Arya


People also ask

What if there is no foreign key?

The obvious problem with the lack of foreign keys is that a database can't enforce referential integrity and if it wasn't taken care of properly at the higher level then this might lead to inconsistent data (child rows without corresponding parent rows).

How do you select rows with no matching entry in another table?

1 Answer. Here, LEFT JOIN is used to return all the rows from TableA even though they don't match with the rows in TableB. You can observe that WHERE tb.ID IS NULL clause; there will be no records in TableB for the particular ID from TableA.

How do you ignore foreign key constraints?

To disable a foreign key constraint for INSERT and UPDATE statements. In Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu.

Can a table have 0 foreign keys?

So, in short, you can either set the value to NULL , remove the foreign key constraint and set the value to whatever you desire, including 0 , or add a record with a 0 in the referenced table.


2 Answers

NOT EXISTS comes to mind:

select c.*
from city_url c
where not exists (select 1
                  from email_account ea
                  where ea.city_url_id = c.id
                 );
like image 182
Gordon Linoff Avatar answered Sep 28 '22 13:09

Gordon Linoff


There's also this option:

SELECT city_url.*
FROM city_url
LEFT JOIN email_account ON email_account.city_url_id = city_url.id
WHERE email_account.id IS NULL
like image 30
Edson Horacio Junior Avatar answered Sep 28 '22 13:09

Edson Horacio Junior