Problem Statement
Table: Rectangle
This table stores the dimensions of rectangles. Each row contains the lengths of four sides of a rectangle.
+---------------+------+
| Column Name | Type |
+---------------+------+
| a | int |
| b | int |
| c | int |
| d | int |
+---------------+------+
(a, b, c, d) is the primary key for this table.
Each row of this table contains the lengths of four sides of a rectangle.Determine for each set of four line segments whether they can form a rectangle. A set of line segments can form a rectangle if opposite sides are equal.
Return the result table in any order.
Example
Input:
Rectangle table:
+----+----+----+----+
| a | b | c | d |
+----+----+----+----+
| 15 | 10 | 15 | 10 |
| 15 | 10 | 15 | 20 |
+----+----+----+----+Output:
+----+----+----+----+-----------+
| a | b | c | d | rectangle |
+----+----+----+----+-----------+
| 15 | 10 | 15 | 10 | Yes |
| 15 | 10 | 15 | 20 | No |
+----+----+----+----+-----------+In this example, the first set of sides (15, 10, 15, 10) can form a rectangle because the opposite sides are equal. The second set of sides (15, 10, 15, 20) cannot form a rectangle because not all opposite sides are equal.
Try It YourSelf
Database Exercise
Database Schema:
-- Database schema would be rendered hereExercise Script:
-- Exercise script would be rendered hereAvailable actions: Execute
Solution
To solve this problem, we need to check each row in the Rectangle table to determine if the given sides can form a rectangle based on the condition that opposite sides must be equal.
- Check Opposite Sides: Verify if sides (a, c) and (b, d) are equal for each row.
- Return Result: Based on the equality of opposite sides, return ‘Yes’ if the sides can form a rectangle, otherwise return ‘No’.
SQL Query
SELECT a, b, c, d,
CASE
WHEN a = c AND b = d THEN 'Yes'
ELSE 'No'
END as rectangle
FROM Rectangle;Step by Step Approach
Step 1: Check Opposite Sides
Check if opposite sides are equal for each row in the table.
SELECT a, b, c, d,
(a = c AND b = d) as is_rectangle
FROM RectangleOutput After Step 1:
+----+----+----+----+--------------+
| a | b | c | d | is_rectangle |
+----+----+----+----+--------------+
| 15 | 10 | 15 | 10 | 1 |
| 15 | 10 | 15 | 20 | 0 |
+----+----+----+----+--------------+Step 2: Return Result
Based on the equality check, return ‘Yes’ if the sides can form a rectangle, otherwise return ‘No’.
SELECT a, b, c, d,
CASE
WHEN a = c AND b = d THEN 'Yes'
ELSE 'No'
END as rectangle
FROM RectangleFinal Output:
+----+----+----+----+-----------+
| a | b | c | d | rectangle |
+----+----+----+----+-----------+
| 15 | 10 | 15 | 10 | Yes |
| 15 | 10 | 15 | 20 | No |
+----+----+----+----+-----------+