Shortest and longest city name and alphabetical order











up vote
6
down vote

favorite













Problem



Query the two cities in STATION with the shortest and longest CITY
names, as well as their respective lengths (i.e.: number of characters
in the name). If there is more than one smallest or largest city,
choose the one that comes first when ordered alphabetically.



Sample Input



Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY



Sample Output



ABC 3
PQRS 4




Can I get shorter code in MySQL and also an optimal Oracle query? There's no way to have only one sub-query for both min and max, is there?



select city, char_length(city) from STATION 
where city = (select min(city) from STATION
where char_length(city) = (select min(char_length(city)) from STATION))

or city = (select min(city) from STATION
where char_length(city) = (select max(char_length(city)) from STATION));









share|improve this question




















  • 1




    I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
    – Vogel612
    Nov 5 '17 at 10:09










  • Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
    – Phrancis
    Nov 5 '17 at 11:18








  • 1




    SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
    – Barry Carter
    Nov 5 '17 at 13:08












  • @Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
    – ProgramSpree
    Nov 6 '17 at 2:41










  • @BarryCarter What does ORDER BY 2 mean?
    – ProgramSpree
    Nov 6 '17 at 2:41















up vote
6
down vote

favorite













Problem



Query the two cities in STATION with the shortest and longest CITY
names, as well as their respective lengths (i.e.: number of characters
in the name). If there is more than one smallest or largest city,
choose the one that comes first when ordered alphabetically.



Sample Input



Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY



Sample Output



ABC 3
PQRS 4




Can I get shorter code in MySQL and also an optimal Oracle query? There's no way to have only one sub-query for both min and max, is there?



select city, char_length(city) from STATION 
where city = (select min(city) from STATION
where char_length(city) = (select min(char_length(city)) from STATION))

or city = (select min(city) from STATION
where char_length(city) = (select max(char_length(city)) from STATION));









share|improve this question




















  • 1




    I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
    – Vogel612
    Nov 5 '17 at 10:09










  • Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
    – Phrancis
    Nov 5 '17 at 11:18








  • 1




    SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
    – Barry Carter
    Nov 5 '17 at 13:08












  • @Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
    – ProgramSpree
    Nov 6 '17 at 2:41










  • @BarryCarter What does ORDER BY 2 mean?
    – ProgramSpree
    Nov 6 '17 at 2:41













up vote
6
down vote

favorite









up vote
6
down vote

favorite












Problem



Query the two cities in STATION with the shortest and longest CITY
names, as well as their respective lengths (i.e.: number of characters
in the name). If there is more than one smallest or largest city,
choose the one that comes first when ordered alphabetically.



Sample Input



Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY



Sample Output



ABC 3
PQRS 4




Can I get shorter code in MySQL and also an optimal Oracle query? There's no way to have only one sub-query for both min and max, is there?



select city, char_length(city) from STATION 
where city = (select min(city) from STATION
where char_length(city) = (select min(char_length(city)) from STATION))

or city = (select min(city) from STATION
where char_length(city) = (select max(char_length(city)) from STATION));









share|improve this question
















Problem



Query the two cities in STATION with the shortest and longest CITY
names, as well as their respective lengths (i.e.: number of characters
in the name). If there is more than one smallest or largest city,
choose the one that comes first when ordered alphabetically.



Sample Input



Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY



Sample Output



ABC 3
PQRS 4




Can I get shorter code in MySQL and also an optimal Oracle query? There's no way to have only one sub-query for both min and max, is there?



select city, char_length(city) from STATION 
where city = (select min(city) from STATION
where char_length(city) = (select min(char_length(city)) from STATION))

or city = (select min(city) from STATION
where char_length(city) = (select max(char_length(city)) from STATION));






sql mysql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 6 '17 at 3:03









Jamal

30.2k11115226




30.2k11115226










asked Nov 5 '17 at 5:40









ProgramSpree

3316




3316








  • 1




    I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
    – Vogel612
    Nov 5 '17 at 10:09










  • Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
    – Phrancis
    Nov 5 '17 at 11:18








  • 1




    SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
    – Barry Carter
    Nov 5 '17 at 13:08












  • @Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
    – ProgramSpree
    Nov 6 '17 at 2:41










  • @BarryCarter What does ORDER BY 2 mean?
    – ProgramSpree
    Nov 6 '17 at 2:41














  • 1




    I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
    – Vogel612
    Nov 5 '17 at 10:09










  • Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
    – Phrancis
    Nov 5 '17 at 11:18








  • 1




    SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
    – Barry Carter
    Nov 5 '17 at 13:08












  • @Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
    – ProgramSpree
    Nov 6 '17 at 2:41










  • @BarryCarter What does ORDER BY 2 mean?
    – ProgramSpree
    Nov 6 '17 at 2:41








1




1




I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
– Vogel612
Nov 5 '17 at 10:09




I'm not up for writing a review, but you should look into TOP/LIMIT and use ORDER BY to make the query more clear
– Vogel612
Nov 5 '17 at 10:09












Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
– Phrancis
Nov 5 '17 at 11:18






Is there any particular reason you are requesting "also an optimal Oracle query"? Oracle is a completely separate database management system (arguably a better one) than MySQL.
– Phrancis
Nov 5 '17 at 11:18






1




1




SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
– Barry Carter
Nov 5 '17 at 13:08






SELECT city, char_length(city) FROM station ORDER BY char_length(city) DESC, city LIMIT 1 might do the trick (but test). If you're golfing, ORDER BY 2 DESC, 1 might work for the ORDER BY clause.
– Barry Carter
Nov 5 '17 at 13:08














@Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
– ProgramSpree
Nov 6 '17 at 2:41




@Phrancis I have learnt Oracle only. Just for this problem, I did a MySQL query - but it's not what I generally use. That is why I'm looking for an Oracle implementation.
– ProgramSpree
Nov 6 '17 at 2:41












@BarryCarter What does ORDER BY 2 mean?
– ProgramSpree
Nov 6 '17 at 2:41




@BarryCarter What does ORDER BY 2 mean?
– ProgramSpree
Nov 6 '17 at 2:41










4 Answers
4






active

oldest

votes

















up vote
6
down vote



accepted










Formatting



Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).



SELECT
city,
CHAR_LENGTH(city)
FROM STATION
WHERE city = (
SELECT
MIN(city)
FROM STATION
WHERE CHAR_LENGTH(city) = (
SELECT
MIN(CHAR_LENGTH(city))
FROM STATION
)
)
OR city = (
SELECT
MIN(city)
FROM STATION
WHERE CHAR_LENGTH(city) = (
SELECT
MAX(CHAR_LENGTH(city))
FROM STATION
)
);


Now we can see much more easily how deeply nested queries are.





Variables



You could make the code simpler by using a few user-defined variables:



SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
/* Query below only to demonstrate the variables */
SELECT
'@MinCityLen' AS `VariableName`,
@MinCityLen AS `Value`
UNION
SELECT
'@MaxCityLen',
@MaxCityLen;


Which returns this:




VariableName  Value
@MinCityLen 3
@MaxCityLen 4



This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.





Shorter code != Better code



Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.



This is what I came up with. I also have a link on sqlfiddle



# find shortest city name
SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
# find longest city name
SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

SELECT
city,
CHAR_LENGTH(city)
FROM
STATION
WHERE
# find shortest city name sorted alphabetically
city = (
SELECT
city
FROM STATION
WHERE CHAR_LENGTH(city) = @MinCityLen
ORDER BY city ASC
LIMIT 1
)
# find longest city name sorted alphabetically
OR city = (
SELECT
MIN(city)
FROM STATION
WHERE CHAR_LENGTH(city) = @MaxCityLen
ORDER BY city ASC
LIMIT 1
);





share|improve this answer























  • Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
    – ProgramSpree
    Nov 6 '17 at 2:47




















up vote
4
down vote













It took me a while to think about the answer and how to present it in a presentable manner. The following works just fine:



SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;
SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;






share|improve this answer





















  • You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 10:49


















up vote
1
down vote













I think, presentation matters. My solution shows each parts separately in a human readable manner. The steps show how to break the problem before we begin to solve it



Idea : Find all cities that have the smallest length.



STEPS:




  • Find the minimum length of city .

  • Get all cities that have the MIN Length.

  • Sort by CITY .

  • Output the first result only.


Repeat same for MAX



select CITY, length(CITY) from STATION where length(CITY) = (
select MIN(length(CITY)) from STATION
) order by CITY limit 1;

select CITY, length(CITY) from STATION where length(CITY) = (
select MAX(length(CITY)) from STATION
) order by CITY limit 1;





share|improve this answer



















  • 1




    You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 8:15


















up vote
0
down vote













I spent a while on this one and here is what I came up with:



    SELECT CITY, LENGTH(CITY) 
FROM STATION
WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION)
ORDER BY CITY ASC LIMIT 1;

SELECT CITY, LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION);


The reason I tried this is because I was reading on the MySQL Reference Manual about nesting WHERE subqueries, then I looked into it further and I found an article that digs into it further https://community.modeanalytics.com/sql/tutorial/sql-subqueries/ I drew inspiration under the subheading "Subqueries in Conditional Logic". I hope this helps someone.






share|improve this answer








New contributor




Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    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: "196"
    };
    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',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fcodereview.stackexchange.com%2fquestions%2f179651%2fshortest-and-longest-city-name-and-alphabetical-order%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    6
    down vote



    accepted










    Formatting



    Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).



    SELECT
    city,
    CHAR_LENGTH(city)
    FROM STATION
    WHERE city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MIN(CHAR_LENGTH(city))
    FROM STATION
    )
    )
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MAX(CHAR_LENGTH(city))
    FROM STATION
    )
    );


    Now we can see much more easily how deeply nested queries are.





    Variables



    You could make the code simpler by using a few user-defined variables:



    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
    /* Query below only to demonstrate the variables */
    SELECT
    '@MinCityLen' AS `VariableName`,
    @MinCityLen AS `Value`
    UNION
    SELECT
    '@MaxCityLen',
    @MaxCityLen;


    Which returns this:




    VariableName  Value
    @MinCityLen 3
    @MaxCityLen 4



    This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.





    Shorter code != Better code



    Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.



    This is what I came up with. I also have a link on sqlfiddle



    # find shortest city name
    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    # find longest city name
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

    SELECT
    city,
    CHAR_LENGTH(city)
    FROM
    STATION
    WHERE
    # find shortest city name sorted alphabetically
    city = (
    SELECT
    city
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MinCityLen
    ORDER BY city ASC
    LIMIT 1
    )
    # find longest city name sorted alphabetically
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MaxCityLen
    ORDER BY city ASC
    LIMIT 1
    );





    share|improve this answer























    • Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
      – ProgramSpree
      Nov 6 '17 at 2:47

















    up vote
    6
    down vote



    accepted










    Formatting



    Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).



    SELECT
    city,
    CHAR_LENGTH(city)
    FROM STATION
    WHERE city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MIN(CHAR_LENGTH(city))
    FROM STATION
    )
    )
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MAX(CHAR_LENGTH(city))
    FROM STATION
    )
    );


    Now we can see much more easily how deeply nested queries are.





    Variables



    You could make the code simpler by using a few user-defined variables:



    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
    /* Query below only to demonstrate the variables */
    SELECT
    '@MinCityLen' AS `VariableName`,
    @MinCityLen AS `Value`
    UNION
    SELECT
    '@MaxCityLen',
    @MaxCityLen;


    Which returns this:




    VariableName  Value
    @MinCityLen 3
    @MaxCityLen 4



    This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.





    Shorter code != Better code



    Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.



    This is what I came up with. I also have a link on sqlfiddle



    # find shortest city name
    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    # find longest city name
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

    SELECT
    city,
    CHAR_LENGTH(city)
    FROM
    STATION
    WHERE
    # find shortest city name sorted alphabetically
    city = (
    SELECT
    city
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MinCityLen
    ORDER BY city ASC
    LIMIT 1
    )
    # find longest city name sorted alphabetically
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MaxCityLen
    ORDER BY city ASC
    LIMIT 1
    );





    share|improve this answer























    • Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
      – ProgramSpree
      Nov 6 '17 at 2:47















    up vote
    6
    down vote



    accepted







    up vote
    6
    down vote



    accepted






    Formatting



    Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).



    SELECT
    city,
    CHAR_LENGTH(city)
    FROM STATION
    WHERE city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MIN(CHAR_LENGTH(city))
    FROM STATION
    )
    )
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MAX(CHAR_LENGTH(city))
    FROM STATION
    )
    );


    Now we can see much more easily how deeply nested queries are.





    Variables



    You could make the code simpler by using a few user-defined variables:



    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
    /* Query below only to demonstrate the variables */
    SELECT
    '@MinCityLen' AS `VariableName`,
    @MinCityLen AS `Value`
    UNION
    SELECT
    '@MaxCityLen',
    @MaxCityLen;


    Which returns this:




    VariableName  Value
    @MinCityLen 3
    @MaxCityLen 4



    This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.





    Shorter code != Better code



    Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.



    This is what I came up with. I also have a link on sqlfiddle



    # find shortest city name
    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    # find longest city name
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

    SELECT
    city,
    CHAR_LENGTH(city)
    FROM
    STATION
    WHERE
    # find shortest city name sorted alphabetically
    city = (
    SELECT
    city
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MinCityLen
    ORDER BY city ASC
    LIMIT 1
    )
    # find longest city name sorted alphabetically
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MaxCityLen
    ORDER BY city ASC
    LIMIT 1
    );





    share|improve this answer














    Formatting



    Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).



    SELECT
    city,
    CHAR_LENGTH(city)
    FROM STATION
    WHERE city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MIN(CHAR_LENGTH(city))
    FROM STATION
    )
    )
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
    SELECT
    MAX(CHAR_LENGTH(city))
    FROM STATION
    )
    );


    Now we can see much more easily how deeply nested queries are.





    Variables



    You could make the code simpler by using a few user-defined variables:



    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
    /* Query below only to demonstrate the variables */
    SELECT
    '@MinCityLen' AS `VariableName`,
    @MinCityLen AS `Value`
    UNION
    SELECT
    '@MaxCityLen',
    @MaxCityLen;


    Which returns this:




    VariableName  Value
    @MinCityLen 3
    @MaxCityLen 4



    This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.





    Shorter code != Better code



    Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.



    This is what I came up with. I also have a link on sqlfiddle



    # find shortest city name
    SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
    # find longest city name
    SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

    SELECT
    city,
    CHAR_LENGTH(city)
    FROM
    STATION
    WHERE
    # find shortest city name sorted alphabetically
    city = (
    SELECT
    city
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MinCityLen
    ORDER BY city ASC
    LIMIT 1
    )
    # find longest city name sorted alphabetically
    OR city = (
    SELECT
    MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = @MaxCityLen
    ORDER BY city ASC
    LIMIT 1
    );






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 5 '17 at 12:32

























    answered Nov 5 '17 at 12:21









    Phrancis

    14.7k646139




    14.7k646139












    • Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
      – ProgramSpree
      Nov 6 '17 at 2:47




















    • Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
      – ProgramSpree
      Nov 6 '17 at 2:47


















    Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
    – ProgramSpree
    Nov 6 '17 at 2:47






    Thank you for your formatting help! The shorter MySQL code returns "@MinCityLen", but I want the city name to be displayed. Also, thank you for the last documented code. Is there any way to merge both max and min finding queries into one?
    – ProgramSpree
    Nov 6 '17 at 2:47














    up vote
    4
    down vote













    It took me a while to think about the answer and how to present it in a presentable manner. The following works just fine:



    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;
    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;






    share|improve this answer





















    • You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 10:49















    up vote
    4
    down vote













    It took me a while to think about the answer and how to present it in a presentable manner. The following works just fine:



    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;
    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;






    share|improve this answer





















    • You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 10:49













    up vote
    4
    down vote










    up vote
    4
    down vote









    It took me a while to think about the answer and how to present it in a presentable manner. The following works just fine:



    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;
    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;






    share|improve this answer












    It took me a while to think about the answer and how to present it in a presentable manner. The following works just fine:



    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;
    SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 7 '17 at 16:25









    Simas

    411




    411












    • You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 10:49


















    • You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 10:49
















    You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 10:49




    You have presented a good alternative solution (exactly how I would approach the problem), but you haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and why that is an improvement upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 10:49










    up vote
    1
    down vote













    I think, presentation matters. My solution shows each parts separately in a human readable manner. The steps show how to break the problem before we begin to solve it



    Idea : Find all cities that have the smallest length.



    STEPS:




    • Find the minimum length of city .

    • Get all cities that have the MIN Length.

    • Sort by CITY .

    • Output the first result only.


    Repeat same for MAX



    select CITY, length(CITY) from STATION where length(CITY) = (
    select MIN(length(CITY)) from STATION
    ) order by CITY limit 1;

    select CITY, length(CITY) from STATION where length(CITY) = (
    select MAX(length(CITY)) from STATION
    ) order by CITY limit 1;





    share|improve this answer



















    • 1




      You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 8:15















    up vote
    1
    down vote













    I think, presentation matters. My solution shows each parts separately in a human readable manner. The steps show how to break the problem before we begin to solve it



    Idea : Find all cities that have the smallest length.



    STEPS:




    • Find the minimum length of city .

    • Get all cities that have the MIN Length.

    • Sort by CITY .

    • Output the first result only.


    Repeat same for MAX



    select CITY, length(CITY) from STATION where length(CITY) = (
    select MIN(length(CITY)) from STATION
    ) order by CITY limit 1;

    select CITY, length(CITY) from STATION where length(CITY) = (
    select MAX(length(CITY)) from STATION
    ) order by CITY limit 1;





    share|improve this answer



















    • 1




      You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 8:15













    up vote
    1
    down vote










    up vote
    1
    down vote









    I think, presentation matters. My solution shows each parts separately in a human readable manner. The steps show how to break the problem before we begin to solve it



    Idea : Find all cities that have the smallest length.



    STEPS:




    • Find the minimum length of city .

    • Get all cities that have the MIN Length.

    • Sort by CITY .

    • Output the first result only.


    Repeat same for MAX



    select CITY, length(CITY) from STATION where length(CITY) = (
    select MIN(length(CITY)) from STATION
    ) order by CITY limit 1;

    select CITY, length(CITY) from STATION where length(CITY) = (
    select MAX(length(CITY)) from STATION
    ) order by CITY limit 1;





    share|improve this answer














    I think, presentation matters. My solution shows each parts separately in a human readable manner. The steps show how to break the problem before we begin to solve it



    Idea : Find all cities that have the smallest length.



    STEPS:




    • Find the minimum length of city .

    • Get all cities that have the MIN Length.

    • Sort by CITY .

    • Output the first result only.


    Repeat same for MAX



    select CITY, length(CITY) from STATION where length(CITY) = (
    select MIN(length(CITY)) from STATION
    ) order by CITY limit 1;

    select CITY, length(CITY) from STATION where length(CITY) = (
    select MAX(length(CITY)) from STATION
    ) order by CITY limit 1;






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 26 at 12:59

























    answered Jun 26 at 6:57









    Arindam Roychowdhury

    1114




    1114








    • 1




      You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 8:15














    • 1




      You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
      – Toby Speight
      Jun 26 at 8:15








    1




    1




    You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 8:15




    You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process.
    – Toby Speight
    Jun 26 at 8:15










    up vote
    0
    down vote













    I spent a while on this one and here is what I came up with:



        SELECT CITY, LENGTH(CITY) 
    FROM STATION
    WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION)
    ORDER BY CITY ASC LIMIT 1;

    SELECT CITY, LENGTH(CITY)
    FROM STATION
    WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION);


    The reason I tried this is because I was reading on the MySQL Reference Manual about nesting WHERE subqueries, then I looked into it further and I found an article that digs into it further https://community.modeanalytics.com/sql/tutorial/sql-subqueries/ I drew inspiration under the subheading "Subqueries in Conditional Logic". I hope this helps someone.






    share|improve this answer








    New contributor




    Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      0
      down vote













      I spent a while on this one and here is what I came up with:



          SELECT CITY, LENGTH(CITY) 
      FROM STATION
      WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION)
      ORDER BY CITY ASC LIMIT 1;

      SELECT CITY, LENGTH(CITY)
      FROM STATION
      WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION);


      The reason I tried this is because I was reading on the MySQL Reference Manual about nesting WHERE subqueries, then I looked into it further and I found an article that digs into it further https://community.modeanalytics.com/sql/tutorial/sql-subqueries/ I drew inspiration under the subheading "Subqueries in Conditional Logic". I hope this helps someone.






      share|improve this answer








      New contributor




      Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















        up vote
        0
        down vote










        up vote
        0
        down vote









        I spent a while on this one and here is what I came up with:



            SELECT CITY, LENGTH(CITY) 
        FROM STATION
        WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION)
        ORDER BY CITY ASC LIMIT 1;

        SELECT CITY, LENGTH(CITY)
        FROM STATION
        WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION);


        The reason I tried this is because I was reading on the MySQL Reference Manual about nesting WHERE subqueries, then I looked into it further and I found an article that digs into it further https://community.modeanalytics.com/sql/tutorial/sql-subqueries/ I drew inspiration under the subheading "Subqueries in Conditional Logic". I hope this helps someone.






        share|improve this answer








        New contributor




        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        I spent a while on this one and here is what I came up with:



            SELECT CITY, LENGTH(CITY) 
        FROM STATION
        WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION)
        ORDER BY CITY ASC LIMIT 1;

        SELECT CITY, LENGTH(CITY)
        FROM STATION
        WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION);


        The reason I tried this is because I was reading on the MySQL Reference Manual about nesting WHERE subqueries, then I looked into it further and I found an article that digs into it further https://community.modeanalytics.com/sql/tutorial/sql-subqueries/ I drew inspiration under the subheading "Subqueries in Conditional Logic". I hope this helps someone.







        share|improve this answer








        New contributor




        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 14 mins ago









        Nikimaria87

        11




        11




        New contributor




        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Nikimaria87 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f179651%2fshortest-and-longest-city-name-and-alphabetical-order%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

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga