Questions tagged [sql]

Structured Query Language (SQL) is a language for querying databases. Questions should include code examples, table structure, sample data, and a tag for the DBMS implementation (e.g. MySQL, PostgreSQL, Oracle, MS SQL Server, IBM DB2, etc.) being used. If your question relates solely to a specific DBMS (uses specific extensions/features), use that DBMS's tag instead. Answers to questions tagged with SQL should use ISO/IEC standard SQL.

How to write a good SQL question?

There are five ingredients to this recipe:

  1. Provide a clear textual explanation of the problem at hand.
  2. Provide proper sample data, as DDL (create table statement(s)) and DML (insert statement(s)). The sample data should be enough to demonstrate the problem, including edge cases. Usually, a few relevant rows are enough.
  3. Provide the expected output for the sample data you've posted.
  4. Show your attempts to solve the problem.
  5. Tag properly. In addition to , also provide the relevant rdbms tag (i.e. , , ), and the lowest version you need the solution for (i.e , ).
    Remember - different products use different dialects of SQL, and this can have a drastic effect on the answers you might get.
    Different versions of the same product have different built-in functions and capabilities that might also have a drastic effect on the answers.

Do not include images of data or code!

A link to an online SQL test environment such as SQL Fiddle, Rextester, or db<>fiddle might help, but it is not a replacement for having all the data inside the question.
For more information, Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? and Help me write this query in SQL.

General Information

From Wikipedia:

SQL stands for Structured Query Language (informally) and is usually pronounced as Sequel.

SQL is based on relational algebra. In relational algebra, the word relation is synonymous with the word table. SQL is a standard to use relational algebra in a technical environment.

One subset of the SQL standard is DDL (Data Definition Language), used to create tables and constraints. These include:

  • CREATE
  • DROP
  • ALTER

Another subset is DML (Data Manipulation Language), which is used to modify and view data within the database:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE

The final "standard" subset of commands is DCL (Data Control Language):

  • GRANT
  • REVOKE

Many database implementations require the use of SQL, and over the years, vendors have implemented dialects of SQL to provide more functionality and simplify it. Because of these deviations from the standard, SQL is fractured – syntax that works on one implementation does not necessarily work on another.

ISO/IEC (formerly ANSI) standards have been beneficial in resolving such situations, but adoption is selective. Queries conforming to these standards should be portable to other databases, though performance may vary.

Most DBMSs have additional languages for writing stored procedures. In Oracle, it is PL/SQL (Procedural Language/Structured Query Language). In PostgreSQL, it's PL/pgSQL (Procedural Language/PostgreSQL). Outside of stored procedures or functions, Oracle and PostgreSQL use SQL. Thus the tags and should only be used for problems directly related to writing stored procedures. Microsoft SQL Server uses the term T-SQL (Transact-SQL)() for both "plain" SQL (queries, DML, ..) and the language used for stored procedures.

List of Procedural Extensions

  • ANSI/ISO Standard: SQL/PSM (SQL / Persistent Stored Modules)
  • Interbase/Firebird: PSQL (Procedural SQL)
  • IBM DB2 SQL: PL/SQL (Procedural Language, implements SQL/PSM)
  • IBM Informix: SPL (Stored Procedural Language)
  • IBM Netezza: NZPLSQL (based on Postgres PL/pgSQL)
  • Microsoft/Sybase: T-SQL (Transact-SQL)
  • Mimer SQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MySQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MonetDB: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • NuoDB: SSP (Starkey Stored Procedures)
  • Oracle: PL/SQL (Procedural Language / SQL, based on Ada)
  • PostgreSQL: PL/pgSQL (Procedural Language / PostgreSQL Structured Query Language, implements SQL/PSM)
  • Sybase: Watcom-SQL (SQL Anywhere Watcom-SQL Dialect)
  • Teradata: SPL (Stored Procedural Language)
  • SAP: SAP HANA (SQL Script)

Tagging Recommendation

This tag should be used for general SQL programming language questions, in addition to tags for specific products. For example, questions about Microsoft SQL Server should use the tag, while questions regarding MySQL should use the tag. SQL is the umbrella under which these products exist; tagging them by product (including version, e.g , , ) is the easiest way to know what functionality is available for the task at hand. It is very common for questions to omit this tag because query discussions on MySQL are more often stated as MySQL rather than SQL in general.

Please read this summary about the SQL standard (The 1992 one in this case, broadly implemented) and if you can, refer to the book itself.

More specific tags

When you are asking a question about SQL you can also add more specific tags. Here is the list of available tags:

Implementation specific tags

You can specify your question by adding the implementation you used as a tag.

Other Resources

Free SQL Programming Books

Free SQL/Database Online Courses

SQL/Database Online Tutorial

SQL reserved words overview

Online Testing

While you should always provide complete code examples (e.g., schema, data sample and expected result) in your question or answer, you can also isolate problematic code and reproduce it in an online environment:

  • SQL Fiddle MySQL 5.6, Oracle 11g R2, PostgreSQL 9.6, PostgreSQL 9.3, SQLite (WebSQL), SQLite (SQL.js), SQL Server 2017
  • Rextester: SQL Server, PostgreSQL, MySql, Oracle
  • Stack Exchange Data Explorer Microsoft SQL Server 2016
  • db-fiddle MySQL 5.5, 5.6, 5.7, 8.0 PostgreSQL 9.4, 9.5, 9.6, 10, 11, 12, 13 SQLite 3.26, 3.30
  • db <> fiddle Db2 Developer-C 11.1, Firebird 3.0, MariaDB 10.3, 10.4, 10.5, 10.6, MySQL 5.5, 5.6, 5.7, 8.0, Oracle 11g Release 2, Postgres 9.5, 9.6, 10, 11, 12,13, SQLite 3.27, SQL Server 2014, 2016 and 2017, 2017 (Linux), 2019, 2019 (Linux)
  • Hue demo Hive, Trino, MySQL, Flink SQL, Phoenix SQL, ksqlDB, Dask SQL, SparkSQL
665031 questions
1775
votes
29 answers

How do I perform an IF...THEN in an SQL SELECT?

How do I perform an IF...THEN in an SQL SELECT statement? For example: SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
Eric Labashosky
  • 29,484
  • 14
  • 39
  • 32
1715
votes
14 answers

How can I delete using INNER JOIN with SQL Server?

I want to delete using INNER JOIN in SQL Server 2008. But I get this error: Msg 156, Level 15, State 1, Line 15 Incorrect syntax near the keyword 'INNER'. My code: DELETE FROM WorkRecord2 INNER JOIN Employee ON…
nettoon493
  • 17,733
  • 7
  • 30
  • 45
1710
votes
36 answers

Find all tables containing column with specified name - MS SQL Server

Is it possible to query for table names which contain columns being LIKE '%myName%' ?
gruber
  • 28,739
  • 35
  • 124
  • 216
1685
votes
19 answers

What is the difference between UNION and UNION ALL?

What is the difference between UNION and UNION ALL?
Brian G
  • 53,704
  • 58
  • 125
  • 140
1620
votes
27 answers

SQL select only rows with max value on a column

I have this table for documents (simplified version here): id rev content 1 1 ... 2 1 ... 1 2 ... 1 3 ... How do I select one row per id and only the greatest rev? With the above data, the result should contain two rows: [1, 3,…
1594
votes
25 answers

How to reset AUTO_INCREMENT in MySQL

How can I reset the AUTO_INCREMENT of a field? I want it to start counting from 1 again.
homerun
  • 19,837
  • 15
  • 45
  • 70
1580
votes
8 answers

What are the options for storing hierarchical data in a relational database?

Good Overviews Generally speaking, you're making a decision between fast read times (for example, nested set) or fast write times (adjacency list). Usually, you end up with a combination of the options below that best fit your needs. The following…
orangepips
  • 9,891
  • 6
  • 33
  • 57
1578
votes
18 answers

How can I do an UPDATE statement with JOIN in SQL Server?

I need to update this table in SQL Server with data from its 'parent' table, see below: Table: sale id (int) udid (int) assid (int) Table: ud id (int) assid (int) sale.assid contains the correct value to update ud.assid. What query will do…
Ant Swift
  • 20,089
  • 10
  • 38
  • 55
1491
votes
3 answers

Using group by on multiple columns

I understand the point of GROUP BY x. But how does GROUP BY x, y work, and what does it mean?
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
1471
votes
16 answers

Can I concatenate multiple MySQL rows into one field?

Using MySQL, I can do something like: SELECT hobbies FROM peoples_hobbies WHERE person_id = 5; My Output: shopping fishing coding but instead I just want 1 row, 1 col: Expected Output: shopping, fishing, coding The reason is that I'm selecting…
Dean Rather
  • 31,756
  • 15
  • 66
  • 72
1391
votes
6 answers

Difference between JOIN and INNER JOIN

Both these joins will give me the same results: SELECT * FROM table JOIN otherTable ON table.ID = otherTable.FK vs SELECT * FROM table INNER JOIN otherTable ON table.ID = otherTable.FK Is there any difference between the statements in performance…
driis
  • 161,458
  • 45
  • 265
  • 341
1358
votes
18 answers

How can I list the tables in a SQLite database file that was opened with ATTACH?

What SQL can be used to list the tables, and the rows within those tables in an SQLite database file – once I have attached it with the ATTACH command on the sqlite3 command line tool?
izb
  • 50,101
  • 39
  • 117
  • 168
1355
votes
15 answers

How to get the identity of an inserted row?

How am I supposed to get the IDENTITY of an inserted row? I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each. Can someone please explain the differences and when I would be…
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1338
votes
14 answers

How do I escape a single quote in SQL Server?

I am trying to insert some text data into a table in SQL Server 9. The text includes a single quote '. How do I escape that? I tried using two single quotes, but it threw me some errors. eg. insert into my_table values('hi, my name''s tim.');
tim_wonil
  • 14,970
  • 6
  • 29
  • 42
1310
votes
15 answers

How do I limit the number of rows returned by an Oracle query after ordering?

Is there a way to make an Oracle query behave like it contains a MySQL limit clause? In MySQL, I can do this: select * from sometable order by name limit 20,10 to get the 21st to the 30th rows (skip the first 20, give the next 10). The rows are…
Mathieu Longtin
  • 15,922
  • 6
  • 30
  • 40