How to find people in a database who live in the same cities?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm new to SQL, and I'm asking for help in an apparently easy question, but it gets cumbersome in my mind.



I have the following table:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
5 Jan chicago
6 Ted san francisco
7 Kat boston


I want a query that returns all the people who live in a city that another person registered in the database also lives in.



The answer, for the table I showed above, would be:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
7 Kat boston









share|improve this question
























  • The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

    – Larry Lustig
    Nov 15 '18 at 17:38

















1















I'm new to SQL, and I'm asking for help in an apparently easy question, but it gets cumbersome in my mind.



I have the following table:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
5 Jan chicago
6 Ted san francisco
7 Kat boston


I want a query that returns all the people who live in a city that another person registered in the database also lives in.



The answer, for the table I showed above, would be:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
7 Kat boston









share|improve this question
























  • The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

    – Larry Lustig
    Nov 15 '18 at 17:38













1












1








1








I'm new to SQL, and I'm asking for help in an apparently easy question, but it gets cumbersome in my mind.



I have the following table:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
5 Jan chicago
6 Ted san francisco
7 Kat boston


I want a query that returns all the people who live in a city that another person registered in the database also lives in.



The answer, for the table I showed above, would be:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
7 Kat boston









share|improve this question
















I'm new to SQL, and I'm asking for help in an apparently easy question, but it gets cumbersome in my mind.



I have the following table:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
5 Jan chicago
6 Ted san francisco
7 Kat boston


I want a query that returns all the people who live in a city that another person registered in the database also lives in.



The answer, for the table I showed above, would be:



ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
7 Kat boston






sql postgresql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 17:45









Laurenz Albe

53.8k103052




53.8k103052










asked Nov 15 '18 at 17:29









Matt_GeoMatt_Geo

1838




1838












  • The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

    – Larry Lustig
    Nov 15 '18 at 17:38

















  • The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

    – Larry Lustig
    Nov 15 '18 at 17:38
















The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

– Larry Lustig
Nov 15 '18 at 17:38





The answer does not depend on which SQL engine is being used, it can easily be answered in engine-neutral SQL.

– Larry Lustig
Nov 15 '18 at 17:38












6 Answers
6






active

oldest

votes


















1














To avoid a correlated subquery which leads to a nested loop, you could perform a self join:



SELECT id, name, city
FROM persons
JOIN (SELECT city
FROM persons
GROUP BY city HAVING count(*) > 1) AS cities
USING (city);


This might be the most performant solution.






share|improve this answer






























    3














    I would use EXISTS :



    SELECT t.*
    FROM table t
    WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);





    share|improve this answer






























      2














      This is really a two part question:



      1. What cities have more than one user located in them?

      2. What users live in that subset of cities?

      Let's answer it in two parts. Let's also make the simplifying assumption (not stated in your question) that the Users table has only one entry per user per city.



      To find cities with more than one user:



       SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1


      Now, let's find all the users for those cities:



      SELECT ID, User, City FROM Users 
      WHERE City IN (SELECT City FROM Users GROUP BY CITY HAVING COUNT(*) > 1)





      share|improve this answer






























        1














        This will give you the rows that have the same city more than 1 time:



        SELECT persons.*
        FROM persons
        WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1





        share|improve this answer






























          0














          This is just a different flavor from the others that have posted.



           SELECT ID,
          name,
          city
          FROM (SELECT DISTINCT
          ID,
          name,
          city,
          COUNT(1) OVER (PARTITION BY city) AS cityCount
          FROM table) t
          WHERE cityCount > 1





          share|improve this answer






























            0














            This can be expressed many ways. Here is one possible way:

            select * from persons p
            where exists (
            select 1 from persons p2
            where p2.city = p.city and p2.name <> p.name
            )





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324952%2fhow-to-find-people-in-a-database-who-live-in-the-same-cities%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              To avoid a correlated subquery which leads to a nested loop, you could perform a self join:



              SELECT id, name, city
              FROM persons
              JOIN (SELECT city
              FROM persons
              GROUP BY city HAVING count(*) > 1) AS cities
              USING (city);


              This might be the most performant solution.






              share|improve this answer



























                1














                To avoid a correlated subquery which leads to a nested loop, you could perform a self join:



                SELECT id, name, city
                FROM persons
                JOIN (SELECT city
                FROM persons
                GROUP BY city HAVING count(*) > 1) AS cities
                USING (city);


                This might be the most performant solution.






                share|improve this answer

























                  1












                  1








                  1







                  To avoid a correlated subquery which leads to a nested loop, you could perform a self join:



                  SELECT id, name, city
                  FROM persons
                  JOIN (SELECT city
                  FROM persons
                  GROUP BY city HAVING count(*) > 1) AS cities
                  USING (city);


                  This might be the most performant solution.






                  share|improve this answer













                  To avoid a correlated subquery which leads to a nested loop, you could perform a self join:



                  SELECT id, name, city
                  FROM persons
                  JOIN (SELECT city
                  FROM persons
                  GROUP BY city HAVING count(*) > 1) AS cities
                  USING (city);


                  This might be the most performant solution.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 17:44









                  Laurenz AlbeLaurenz Albe

                  53.8k103052




                  53.8k103052























                      3














                      I would use EXISTS :



                      SELECT t.*
                      FROM table t
                      WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);





                      share|improve this answer



























                        3














                        I would use EXISTS :



                        SELECT t.*
                        FROM table t
                        WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);





                        share|improve this answer

























                          3












                          3








                          3







                          I would use EXISTS :



                          SELECT t.*
                          FROM table t
                          WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);





                          share|improve this answer













                          I would use EXISTS :



                          SELECT t.*
                          FROM table t
                          WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 15 '18 at 17:43









                          Yogesh SharmaYogesh Sharma

                          35.3k51440




                          35.3k51440





















                              2














                              This is really a two part question:



                              1. What cities have more than one user located in them?

                              2. What users live in that subset of cities?

                              Let's answer it in two parts. Let's also make the simplifying assumption (not stated in your question) that the Users table has only one entry per user per city.



                              To find cities with more than one user:



                               SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1


                              Now, let's find all the users for those cities:



                              SELECT ID, User, City FROM Users 
                              WHERE City IN (SELECT City FROM Users GROUP BY CITY HAVING COUNT(*) > 1)





                              share|improve this answer



























                                2














                                This is really a two part question:



                                1. What cities have more than one user located in them?

                                2. What users live in that subset of cities?

                                Let's answer it in two parts. Let's also make the simplifying assumption (not stated in your question) that the Users table has only one entry per user per city.



                                To find cities with more than one user:



                                 SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1


                                Now, let's find all the users for those cities:



                                SELECT ID, User, City FROM Users 
                                WHERE City IN (SELECT City FROM Users GROUP BY CITY HAVING COUNT(*) > 1)





                                share|improve this answer

























                                  2












                                  2








                                  2







                                  This is really a two part question:



                                  1. What cities have more than one user located in them?

                                  2. What users live in that subset of cities?

                                  Let's answer it in two parts. Let's also make the simplifying assumption (not stated in your question) that the Users table has only one entry per user per city.



                                  To find cities with more than one user:



                                   SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1


                                  Now, let's find all the users for those cities:



                                  SELECT ID, User, City FROM Users 
                                  WHERE City IN (SELECT City FROM Users GROUP BY CITY HAVING COUNT(*) > 1)





                                  share|improve this answer













                                  This is really a two part question:



                                  1. What cities have more than one user located in them?

                                  2. What users live in that subset of cities?

                                  Let's answer it in two parts. Let's also make the simplifying assumption (not stated in your question) that the Users table has only one entry per user per city.



                                  To find cities with more than one user:



                                   SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1


                                  Now, let's find all the users for those cities:



                                  SELECT ID, User, City FROM Users 
                                  WHERE City IN (SELECT City FROM Users GROUP BY CITY HAVING COUNT(*) > 1)






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 15 '18 at 17:37









                                  Larry LustigLarry Lustig

                                  40.6k1284131




                                  40.6k1284131





















                                      1














                                      This will give you the rows that have the same city more than 1 time:



                                      SELECT persons.*
                                      FROM persons
                                      WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1





                                      share|improve this answer



























                                        1














                                        This will give you the rows that have the same city more than 1 time:



                                        SELECT persons.*
                                        FROM persons
                                        WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1





                                        share|improve this answer

























                                          1












                                          1








                                          1







                                          This will give you the rows that have the same city more than 1 time:



                                          SELECT persons.*
                                          FROM persons
                                          WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1





                                          share|improve this answer













                                          This will give you the rows that have the same city more than 1 time:



                                          SELECT persons.*
                                          FROM persons
                                          WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 15 '18 at 17:39









                                          forpasforpas

                                          22k4830




                                          22k4830





















                                              0














                                              This is just a different flavor from the others that have posted.



                                               SELECT ID,
                                              name,
                                              city
                                              FROM (SELECT DISTINCT
                                              ID,
                                              name,
                                              city,
                                              COUNT(1) OVER (PARTITION BY city) AS cityCount
                                              FROM table) t
                                              WHERE cityCount > 1





                                              share|improve this answer



























                                                0














                                                This is just a different flavor from the others that have posted.



                                                 SELECT ID,
                                                name,
                                                city
                                                FROM (SELECT DISTINCT
                                                ID,
                                                name,
                                                city,
                                                COUNT(1) OVER (PARTITION BY city) AS cityCount
                                                FROM table) t
                                                WHERE cityCount > 1





                                                share|improve this answer

























                                                  0












                                                  0








                                                  0







                                                  This is just a different flavor from the others that have posted.



                                                   SELECT ID,
                                                  name,
                                                  city
                                                  FROM (SELECT DISTINCT
                                                  ID,
                                                  name,
                                                  city,
                                                  COUNT(1) OVER (PARTITION BY city) AS cityCount
                                                  FROM table) t
                                                  WHERE cityCount > 1





                                                  share|improve this answer













                                                  This is just a different flavor from the others that have posted.



                                                   SELECT ID,
                                                  name,
                                                  city
                                                  FROM (SELECT DISTINCT
                                                  ID,
                                                  name,
                                                  city,
                                                  COUNT(1) OVER (PARTITION BY city) AS cityCount
                                                  FROM table) t
                                                  WHERE cityCount > 1






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 15 '18 at 17:56









                                                  RyanRyan

                                                  9152711




                                                  9152711





















                                                      0














                                                      This can be expressed many ways. Here is one possible way:

                                                      select * from persons p
                                                      where exists (
                                                      select 1 from persons p2
                                                      where p2.city = p.city and p2.name <> p.name
                                                      )





                                                      share|improve this answer





























                                                        0














                                                        This can be expressed many ways. Here is one possible way:

                                                        select * from persons p
                                                        where exists (
                                                        select 1 from persons p2
                                                        where p2.city = p.city and p2.name <> p.name
                                                        )





                                                        share|improve this answer



























                                                          0












                                                          0








                                                          0







                                                          This can be expressed many ways. Here is one possible way:

                                                          select * from persons p
                                                          where exists (
                                                          select 1 from persons p2
                                                          where p2.city = p.city and p2.name <> p.name
                                                          )





                                                          share|improve this answer















                                                          This can be expressed many ways. Here is one possible way:

                                                          select * from persons p
                                                          where exists (
                                                          select 1 from persons p2
                                                          where p2.city = p.city and p2.name <> p.name
                                                          )






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Nov 15 '18 at 19:35









                                                          JoeG

                                                          3,00333573




                                                          3,00333573










                                                          answered Nov 15 '18 at 17:52









                                                          shawnt00shawnt00

                                                          9,95421118




                                                          9,95421118



























                                                              draft saved

                                                              draft discarded
















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid


                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.

                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function ()
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324952%2fhow-to-find-people-in-a-database-who-live-in-the-same-cities%23new-answer', 'question_page');

                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                                                              Syphilis

                                                              Darth Vader #20