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
97
votes
10 answers

Transfer data from one database to another database

How to fetch the data from one database and insert in to another database table? I can't to do this. Please help me in transferring data from one to another.
Bharathi
  • 1,415
  • 3
  • 15
  • 21
96
votes
7 answers

Is this the proper way to do boolean test in SQL?

Assume active is a "boolean field" (tiny int, with 0 or 1) -- Find all active users select * from users where active -- Find all inactive users select * from users where NOT active In words, can the "NOT" operator be applied directly on the…
Eric
  • 1,858
  • 2
  • 16
  • 17
96
votes
6 answers

How can I merge two MySQL tables?

How can I merge two MySQL tables that have the same structure? The primary keys of the two tables will clash, so I have take that into account.
Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
96
votes
4 answers

SQL NOT IN not working

I have two databases, one which holds the inventory, and another which contains a subset of the records of the primary database. The following SQL statement is not working: SELECT stock.IdStock ,stock.Descr FROM …
Sam
  • 4,219
  • 7
  • 52
  • 80
96
votes
11 answers

Delete all but top n from database table in SQL

What's the best way to delete all rows from a table in sql but to keep n number of rows on the top?
Riri
  • 11,501
  • 14
  • 63
  • 88
96
votes
5 answers

How to generate a new Guid in stored procedure?

I currently have a stored procedure in which I want to insert new rows into a table. insert into cars (id, Make, Model) values('A new Guid', "Ford", "Mustang") So the primary key 'id' is a Guid. I know how to create a new Guid in C# code but within…
Mr Cricket
  • 5,663
  • 5
  • 22
  • 14
96
votes
3 answers

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Why do I get this error Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'. when I try to use sp_executesql?
Manoj Wadhwani
  • 1,487
  • 4
  • 20
  • 23
96
votes
2 answers

How to remove duplicates, which are generated with array_agg postgres function

Does anyone an idea how to rewrite following SQL query to generate results, that would contains only one occurrence of name? (results grouped by user). The query SELECT array_to_string(array_agg(CONCAT(u.firstname, ' ', u.lastname)), ', ') FROM…
Peter Jurkovic
  • 2,686
  • 6
  • 36
  • 55
96
votes
6 answers

How to compare datetime with only date in SQL Server

Select * from [User] U where U.DateCreated = '2014-02-07' but in the database the user was created on 2014-02-07 12:30:47.220 and when I only put '2014-02-07' It does not show any data
Muhabutti
  • 1,256
  • 2
  • 15
  • 20
96
votes
3 answers

Difference between language sql and language plpgsql in PostgreSQL functions

Am very new in Database development so I have some doubts regarding my following example: Function f1() - language sql create or replace function f1(istr varchar) returns text as $$ select 'hello! '::varchar || istr; $$ language sql; Function…
user3814846
96
votes
7 answers

How to join only one row in joined table with postgres?

I have the following schema: CREATE TABLE author ( id integer , name varchar(255) ); CREATE TABLE book ( id integer , author_id integer , title varchar(255) , rating integer ); And I want each author with its last…
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
96
votes
7 answers

Can a foreign key refer to a primary key in the same table?

I just think that the answer is false because the foreign key doesn't have uniqueness property. But some people said that it can be in case of self joining the table. I am new to SQL. If its true please explain how and why? Employee table | e_id |…
AmanS
  • 1,490
  • 2
  • 13
  • 22
96
votes
2 answers

SELECT INTO in MySQL

I am a MSSQL user and now I am converting my database to MySQL. I am writing the following query in MySQL: SELECT * INTO new_tbl FROM tbl; And I get the following error Error : Undeclared variable new_tbl How such a query should be properly…
Mandeep Singh
  • 2,016
  • 7
  • 19
  • 32
96
votes
8 answers

Count how many rows have the same value

How do I write an SQL query to count the total number of a specific num value in the num column of a table? Assuming we have the following data. NAME NUM SAM 1 BOB 1 JAKE 2 JOHN 4 Take the following query: SELECT WHERE num =…
user2273278
  • 1,275
  • 2
  • 14
  • 19
96
votes
6 answers

Subquery using Exists 1 or Exists *

I used to write my EXISTS checks like this: IF EXISTS (SELECT * FROM TABLE WHERE Columns=@Filters) BEGIN UPDATE TABLE SET ColumnsX=ValuesX WHERE Where Columns=@Filters END One of the DBA's in a previous life told me that when I do an EXISTS…
Raj More
  • 47,048
  • 33
  • 131
  • 198
1 2 3
99
100