63

Are there some particular items I should be including in my SQL questions that would help others better understand the problem and attract more useful answers?

Return to FAQ index

Canonical link (of this post for reference):

https://meta.stackoverflow.com/questions/271055

[Tips for asking a good Structured Query Language (SQL) question](https://meta.stackoverflow.com/questions/271055)

1

1 Answer 1

106

Figure Out What is Essential For Us - Keep it Brief and Relevant

If you're asking why something in SQL works the way it does, keep in mind that SQL is declarative, not procedural. SQL describes what you want, not how to get it. (By contrast, most programming languages are procedural.) The various table servers contain elaborate query planners to work out the best way to get what you want. Please consider reading this about the basic technology, and this about indexing.

Ask yourself this question: If I have no idea about my system/setup/situation what is a simple way to describe it?

Don't waste our time on loads of code or paragraphs of information when it is not directly related to the question at hand. Keep it brief, to the point, detailed, and include the specific snippet of code related. If we need more information, we will let you know.

Writing a Good Question - Keep it Structured / Ordered

Think of it this way. When you write your question you are writing an essay. There are key pieces of information that we need before we can help you and those would be the following points.

1. Problem Statement - What problem are you stuck with?

+-----------------------+-----------------------------------------------------+
|          BAD          |                      GOOD                           |
+-----------------------+-----------------------------------------------------+
|  "it errors"          |  "It errors with the message (your error message)"  |
|  "it's not working"   |  "I'm stuck on the next part of this query"         |
|  "what happened"      |  "how do I do (whatever you need to do)"            |
+-----------------------+-----------------------------------------------------+

The BAD examples aren't problem statements. They give the community no help or guidance on what the error is.
The GOOD examples are good ways to tell the community if you are running into an error or can't wrap your mind around the next step in your query.
It's hard for us to look at a question that doesn't detail these things out, and understand what you want unless you provide some detail yourself! More specific problem statements will help attract better answers and even upvotes.

2. Give the Background - Relevant Data? Attempts?

A. The first thing you should do is lay out some data for the community to visually see what you are working with.

This data should be minimized and just enough to show what you are working with. Generally 5-15 rows is enough data for question readers to get a good feel for the data.

For example:

table : people
+-------+-----------+-----------+-------------------+
|    id |    name   |    status |        phone      |
+-------+-----------+-----------+-------------------+
|    1  |    John   |        1  |    214-444-1234   |
|    2  |    Mary   |        0  |    555-111-1234   |
|    3  |    Jeff   |        0  |    214-222-1234   |
|    4  |    Bill   |        1  |    817-333-1234   |
|    5  |    Bob    |        1  |    214-555-1234   |
+-------+-----------+-----------+-------------------+

B. After showing what the data is like, you should also show what attempts you have made.

My Attempt:
I have written the query up to this point, but am stuck on what to do next

    SELECT id, name, status, phone
    FROM people
    WHERE status = 1;

The issue I'm having is I need to filter not only by a status of 1 but
also by the phone number starting with 214

This tells us not only what you want, but what you have tried, and you will get an answer a LOT faster.

C. Consider providing an SQL Fiddle or DB Fiddle

Here would be mine for the examples in this answer SQL fiddle and in DB Fiddle.
It is very easy to use: put your DDL and DML statements (the create, insert, update, alter... etc. statements) on the left and your query statements (the select, set... etc statements) on the right.

By providing a SQL fiddle, you allow people to execute queries to test and not only give you a faster answer, but also a more accurate answer, as it will already be tested.

Keep in mind that providing an SQL Fiddle is no substitute for providing the actual table structure and other details in your problem. You must still include those details (preferably as text) in your question. The SQL Fiddle enhances your question, but it is not sufficient by itself.

Note: SQLFiddle or DBFiddle may not work for some databases. As alternatives, you can try to use Rextester.com or dbfiddle.uk and choose the database.

3. Show Your Expected Outcome

This is a MUST and is often overlooked. You need to show what you want to do with the data in case someone doesn't understand your question or your problem statement. This way they can see how you want the data manipulated, and do it for you!

For Example:

I want my final results to look like this:
+-------+-----------+-----------+-------------------+
|    id |    name   |    status |        phone      |
+-------+-----------+-----------+-------------------+
|    1  |    John   |        1  |    214-444-1234   |
|    5  |    Bob    |        1  |    214-555-1234   |
+-------+-----------+-----------+-------------------+

4. If you're asking about query performance

If you're asking "Why is my query slow?" or something like that, you need to do a little extra homework to get good answers from Stack Overflow.

Put the tag on your question.

Please figure out approximately how many rows you expect in your result set, and approximately how many rows are in each table involved with the query. Mention those numbers in your question. Please mention how long you hope your query needs to take, and how long it's taking. (That is, tell us what you mean by slow).

Don't try to simplify your question by replacing your actual SELECT column lists with *. Using * in SELECT clauses is harmful to query performance compared to specifying the list of columns you need.

In your question please show the EXPLAIN PLAN output (it's just EXPLAIN in some table server makes and models) for your query. Also please show the output from SHOW CREATE TABLE tablename for each table involved in your query. Make sure your question shows all indexes in all relevant tables. When you're asking a performance question, please don't oversimplify your question by omitting indexes or columns you think might be irrelevant. The strangest things can be relevant to performance!

Please be aware that query performance optimization can be an inexact science. This is a good reference. http://use-the-index-luke.com/

5. Some Additional Suggestions

Another thing you can do to improve your questions is to try and add the actual DDL / DML statements to your question.

You can put the data directly in your question or if its a lot of information to show in a question you can Create a Gist to share code snippets

CREATE TABLE people(
  id int,
  name varchar(55),
  status int,
  phone varchar(55)
);

INSERT INTO people VALUES
(1, 'John', 1, '214-444-1234'),
(2, 'Mary', 0, '555-111-1234'),
(3, 'Jeff', 0, '214-222-1234'),
(4, 'Bill', 1, '817-333-1234'),
(5, 'Bob' , 1, '214-555-1234');

You can also post the EXPLAIN execution plan for the table. I prefer EXPLAIN (query) \g as it puts it in rows instead of columns which is easier to read.

EXPLAIN SELECT id, name, status, phone
FROM people
WHERE status = 1;
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+---------------+
|    ID |    SELECT_TYPE|    TABLE  |    TYPE   |    POSSIBLE_KEYS  |    KEY    |    KEY_LEN    |    REF    |    ROWS   |        EXTRA  |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+---------------+
|    1  |    SIMPLE     |    people |    ALL    |    (null)         |    (null) |    (null)     | (null)    |    5      |   Using where |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+---------------+

These are VERY helpful for when you want help increasing the performance / speed of a query or want help with indexing

Formatting Your Post - Gotta Make it Pretty!

For help with formatting code using Stack Overflow's methods read this post or visit the help center
For help with formatting your sql queries you can use an SQL formatter like this SQL formatter
For help with formatting the output just copy the output into this table builder

One Last Note

DO NOT take a working solution/answer and forget to Accept it when the answer solves your issue! There's nothing more annoying when you post a perfectly good and correct answer and there is no activity on the question again. Don't forget to upvote helpful answers and downvote unhelpful ones.

41
  • not sure how this is considered too broad.. this is specific to all server side queries. Commented Sep 9, 2014 at 21:09
  • 2
    The tag wiki would be a good place for a condensed form of this answer.
    – jscs
    Commented Sep 9, 2014 at 21:09
  • @JoshCaswell but why not just remove MySQL from the title.. add a MySQL header in this answer to be for all server side server queries(sql), and then put up two more answers.. one for server side programming languages, and one for front end where you include a jsfiddle for front end.. etc? could even close it afterwards to prevent other answers Commented Sep 9, 2014 at 21:12
  • I agree with @Josh that this would be good information to add to the tag wiki, although I don't agree with the close votes on the question (at least, not when the scope was limited to MySQL). Commented Sep 9, 2014 at 22:06
  • @ThisSuitIsBlackNot I changed it to be more generic so that we could put in three answers for the three main types of areas for programming (from the downvotes and comments saying it needed to be more generic)... if this is added to the tag wiki then you would need to add it to each tag.. and that is tedious.. i still think three answers focusing generally on those three areas would be a great resource for others. but maybe i'm mistaken Commented Sep 9, 2014 at 22:09
  • 1
    @John Sorry, I wasn't clear in my last comment. I agree that this is great information to have, and I think it belongs on meta (hence my disagreement with the close votes). I think it would also be useful to add in a reduced form to some tag wikis. However, I think having three long answers to this question would require a lot of scrolling, so personally I think three separate questions would be better. But that's just me. Commented Sep 9, 2014 at 22:22
  • 4
    This kind of thing should be in the Tag Wiki, not here on Meta.
    – Robert Harvey Mod
    Commented Sep 9, 2014 at 22:26
  • 4
    @RobertHarvey Given that the SO Academy proposal was closed and was intended for this sort of stuff, I'd rather it be here where it will actually be seen.
    – Mysticial
    Commented Sep 9, 2014 at 22:31
  • 1
    I don't have a problem with it being here in principle, but most of what you're describing here is already adequately covered by the "insufficient information" close reason. Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.
    – Robert Harvey Mod
    Commented Sep 9, 2014 at 22:33
  • 1
    Not SO tools, that's already documented. Pretty-printing SQL resources and resources for creating ascii tables would be very useful for your hypothetical audience, I would believe.
    – user1228
    Commented Sep 10, 2014 at 17:11
  • 1
    My only comment is that the question should also strive to be brief'ish. One could follow your guidelines and write a question spanning many pages -- and it would never get answered. And, you should highlight SQL Fiddle a bit more. Commented Sep 14, 2014 at 20:56
  • 1
    @Fred-ii- thanks! (too bad you don't get rep for it on meta lol) feel free to edit it if you do think of something and feel free to link to it whenever you see a question that needs some help :) Commented Oct 6, 2014 at 19:24
  • 1
    Actually, I think adding the relevant tables DDL as well as DML for sample data is better and more important then creating a fiddle. The reason for this is that SqlFiddle.com is limited to a very small subset of versions, and also suffers from a lot of downtime. By adding the DDL+DML to the question directly you are increasing your chances of getting the correct answer faster even if sql fiddle is down. Commented May 31, 2015 at 13:54
  • 1
    ad 5) CTE with test data (i.e. with t as (values (...),(...),...)) should be IMHO explicitly mentioned as alternative to create table + insert into tandem. At least where the question is matter of logic rather than performance. Sometimes I cannot (or am too lazy to do it) build schema or start docker container, not speaking about manual rewriting. I observe many novice OPs don't know this construct and place plain text or csv into questions (or some fancy ascii-art borders or even screenshots in worst cases), so this could be helpful for them in the first place. Commented Jan 23, 2020 at 11:49
  • 2
    It would be very helpful to have a reference to this question from relevant tag wiki's, such as sql, sqlite, etc.
    – PChemGuy
    Commented Aug 13, 2022 at 10:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .