Similar Problems

Similar Problems not available

Arrange Table By Gender - Leetcode Solution

Companies:

LeetCode:  Arrange Table By Gender Leetcode Solution

Difficulty: Medium

Topics: database  

Problem Statement:

Given a table "person", with columns "person_name" and "gender", write a SQL query to rearrange it in such a way that all the female names are listed first and male names come after. The reordered table should have only two columns(person_name, gender).

Solution:

To solve this problem, we need to use the ORDER BY clause to sort the table by gender. We will specify the gender column in the ORDER BY clause and use the ASC keyword to sort the table in ascending order. The table will be sorted in such a way that all the female names are listed first and male names come after.

The SQL query to solve this problem is as follows:

SELECT person_name, gender
FROM person
ORDER BY gender ASC;

Explanation:

The above SQL query will select person_name and gender columns from the person table.

The ORDER BY clause is used to sort the table based on the gender column. The ASC keyword specifies that the table should be sorted in ascending order. This means that all the female names will appear first, followed by male names.

After executing this SQL query, we will get a table that is sorted by gender with all the female names listed first and male names listed after.

Example:

Consider the following person table:

| person_name | gender | |-------------|--------| | John | Male | | Sarah | Female | | Mary | Female | | David | Male |

After running the above SQL query, we will get the following result:

| person_name | gender | |-------------|--------| | Sarah | Female | | Mary | Female | | John | Male | | David | Male |

As we can see from the above result, all the rows with female gender are listed first and male gender comes after. The table is sorted in a way that all the female names are listed first and male names come after.

Arrange Table By Gender Solution Code

1