Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Draw an SQL Output Table

I'm sure most of us have seen SQL results in a terminal, all neatly formatted into rows and columns. If you haven't, here's an example:

+----------+-----------+----------------+
| column 1 | column 2  | column 3       |
+----------+-----------+----------------+
| data     | more data | even more data |
| etc      | just goes | on and on      |
+----------+-----------+----------------+

Your goal for this challenge is, given the columns and row data for a table, draw the table in this style. There should be a horizontal line at the top and bottom of the table, and one right below the header row. There should be vertical lines between every column, and one on both sides of the table. You should use pipes for vertical lines, hyphens for horizontal lines, and plusses for where they intersect.

Specifics:

  • The data can be entered via stdin, or as the argument to a function, but it must be in some form of string
  • The data should be split by the string delimiter ;
  • The data will consist of only ASCII characters, is not quoted, and will not contain the delimiter.
  • The first row of the data will be used for column headers
  • The data will always have the same number of columns
  • The input will always contain at least two rows (one header, one data). You do not have to handle empty sets.
  • A trailing or preceding newline is permitted
  • Each column should be as wide as the widest element, padding shorter elements on the right (bonus -5% if you pad numbers on the left)
  • There should be 1 space of padding before and after the headers and data, except when the column is wider
  • You are not allowed to use the actual mysql program to generate the table
  • Standard loopholes apply

Sample Input:

column 1;column 2;column 3
hello;world;test
longer data;foo;bar

Output

+-------------+----------+----------+
| column 1    | column 2 | column 3 |
+-------------+----------+----------+
| hello       | world    | test     |
| longer data | foo      | bar      |
+-------------+----------+----------+

Scoring:

Lowest number of bytes wins, of course. -5% bonus for padding numbers on the left (see specifics).

Answer*

Cancel