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
99
votes
4 answers

Select Top 1 field and assign to local variable

I want to take the value of ExtractedDate from this query and use it as @LastExtractDate in the next query. How do I do that? SELECT TOP 1 [ExtractedDate] FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc next query: …
Steve Staple
  • 2,983
  • 9
  • 38
  • 73
99
votes
5 answers

is there an advantage to varchar(500) over varchar(8000)?

I've read up on this on MSDN forums and here and I'm still not clear. I think this is correct: Varchar(max) will be stored as a text datatype, so that has drawbacks. So lets say your field will reliably be under 8000 characters. Like a BusinessName…
jcollum
  • 43,623
  • 55
  • 191
  • 321
99
votes
5 answers

When is a timestamp (auto) updated?

If I have a column in a table of type TIMESTAMP and has as default: CURRENT_TIMESTAMP does this column get updated to the current timestamp if I update the value of any other column in the the same row? It seems that it does not but I am not sure if…
Jim
  • 18,826
  • 34
  • 135
  • 254
99
votes
5 answers

What is the difference between IFNULL and COALESCE in MySQL?

SELECT IFNULL(NULL, 'Replaces the NULL') --> Replaces the NULL SELECT COALESCE(NULL, NULL, 'Replaces the NULL') --> Replaces the NULL In both clauses the main difference is argument passing. For IFNULL it's two parameters and for COALESCE it's…
shree18
  • 1,279
  • 1
  • 11
  • 15
99
votes
3 answers

How to order by column A and then by column B?

How to write SQL so that the result can be ordered first by column A then by column B. Something like below: SELECT * FROM tbl WHERE predictor ORDER by col_A and ORDER by col_B
pierrotlefou
  • 39,805
  • 37
  • 135
  • 175
99
votes
7 answers

How to check the maximum number of allowed connections to an Oracle database?

What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80…
Niklas Gustavsson
  • 1,223
  • 1
  • 9
  • 8
99
votes
3 answers

SQL - IF EXISTS UPDATE ELSE INSERT INTO

What I'm trying to do is INSERT subscribers in my database, but IF EXISTS it should UPDATE the row, ELSE INSERT INTO a new row. Ofcourse I connect to the database first and GET the $name, $email and $birthday from the url…
Laurence Cooper
  • 1,215
  • 1
  • 12
  • 21
99
votes
22 answers

Natural Sort in MySQL

Is there an elegant way to have performant, natural sorting in a MySQL database? For example if I have this data set: Final Fantasy Final Fantasy 4 Final Fantasy 10 Final Fantasy 12 Final Fantasy 12: Chains of Promathia Final Fantasy…
BlaM
  • 28,465
  • 32
  • 91
  • 105
99
votes
10 answers

SQL Server JOIN missing NULL values

Suppose I had the following 2 tables: Table1: Table2: Col1: Col2: Col3: Col1: Col2: Col4: a b c a b d e f …
John Bustos
  • 19,036
  • 17
  • 89
  • 151
98
votes
7 answers

I want to copy table contained from one database and insert onto another database table

I want to copy a table's schema as well as the data within that table to another database table in another database on a live server. How could I do this?
user1031092
  • 989
  • 1
  • 7
  • 3
98
votes
4 answers

Get all characters before space in MySQL

I would like to get all the characters in a field before a space For example, if field1 is "chara ters" I want it to return "chara" What would this select statement look like?
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
98
votes
9 answers

Rebuild all indexes in a Database

I have a very large SQL Server 2008 R2 database (1.5TB) and will be copying some data from column to column within the same table. I've been told that the schema has a large number of indexes and was wondering if there is a default query or script…
ChrisD
  • 1,099
  • 1
  • 8
  • 6
98
votes
4 answers

Difference between RIGHT & LEFT JOIN vs RIGHT & LEFT OUTER JOIN in SQL

What is the difference in results between: RIGHT JOIN and RIGHT OUTER JOIN LEFT JOIN and LEFT OUTER JOIN ? Can you please explain it through some examples?
Puru
  • 8,913
  • 26
  • 70
  • 91
98
votes
10 answers

How to rethrow the same exception in SQL Server

I want to rethrow the same exception in SQL Server that has just occurred in my try block. I am able to throw same message but I want to throw same error. BEGIN TRANSACTION BEGIN TRY INSERT INTO Tags.tblDomain (DomainName, SubDomainId,…
Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286
98
votes
14 answers

Explanation of self-joins

I don't understand the need for self-joins. Can someone please explain them to me? A simple example would be very helpful.
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062