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
101
votes
6 answers

Performance differences between equal (=) and IN with one literal value

How does SQL engines differ when we use equal sign and IN operator have same value? Does execution time changes? 1st one using equality check operator WHERE column_value = 'All' 2nd one using IN operator and single value WHERE column_value IN…
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
101
votes
7 answers

Create or replace trigger postgres

I want to "create or replace" a trigger for a postgres table. However, there is not such sql expression. I see that I can do a "DROP TRIGGER IF EXISTS" first (http://www.postgresql.org/docs/9.5/static/sql-droptrigger.html). My question are: Is…
jbarrameda
  • 1,927
  • 2
  • 16
  • 19
101
votes
4 answers

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

I am reading up on transactions in MySQL and am not sure whether I have grasped something specific correctly, and I want to be sure I understood that correctly, so here goes. I know what a transaction is supposed to do, I'm just not sure whether I…
ralokt
  • 1,855
  • 3
  • 17
  • 19
101
votes
12 answers

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

I run the following query: SELECT orderdetails.sku, orderdetails.mf_item_number, orderdetails.qty, orderdetails.price, supplier.supplierid, supplier.suppliername, supplier.dropshipfees, cost = (SELECT supplier_item.price …
Anilkumar
  • 1,107
  • 3
  • 10
  • 11
101
votes
6 answers

How to drop all NOT NULL constraints from a PostgreSQL table in one go

Is it possible to drop all NOT NULL constraints from a table in one go? I have a big table with a lot of NOT NULL constraints and I'm searching for a solution that is faster than dropping them separately.
Stefan
  • 1,383
  • 2
  • 15
  • 25
101
votes
6 answers

Copy a table (including indexes) in postgres

I have a postgres table. I need to delete some data from it. I was going to create a temporary table, copy the data in, recreate the indexes and the delete the rows I need. I can't delete data from the original table, because this original table is…
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248
101
votes
5 answers

How to use a calculated column to calculate another column in the same view

I am hoping you can help with this question. I am using Oracle SQL (SQL Developer for this view)... If I have a table with the following columns: ColumnA (Number) ColumnB (Number) ColumnC (Number) In my view I have Select …
Ewaver
  • 1,121
  • 5
  • 13
  • 22
101
votes
15 answers

How to get First and Last record from a sql query?

In PostgreSQL I run a query on it with several conditions that returns multiple rows, ordered by one of the columns. Example: SELECT FROM mytable WHERE ORDER BY date DESC How would one…
kender
  • 85,663
  • 26
  • 103
  • 145
101
votes
6 answers

How to separate DATE and TIME from DATETIME in MySQL?

I am storing a DATETIME field in a table. Each value looks something like this: 2012-09-09 06:57:12 I am using this syntax: date("Y-m-d H:i:s"); Now my question is, while fetching the data, how can get both date and time separately, using a…
Miss Rosy
  • 1,053
  • 2
  • 9
  • 9
100
votes
5 answers

Find all columns of a certain type in all tables in a SQL Server database

How can I find all columns of a certain type (for example NTEXT) in all tables in a SQL Server database? I am looking for a SQL query.
SwissCoder
  • 2,514
  • 4
  • 28
  • 40
100
votes
7 answers

Find records with a date field in the last 24 hours

In my SQL query how do i make it find the records in the last 24 hours? Eg SELECT * FROM news WHERE date < 24 hours I usually do it by setting a variable to date() - 1 day and comparing it to that but I wondered whether the sql query way was…
user1022585
  • 13,061
  • 21
  • 55
  • 75
100
votes
5 answers

Clustered vs Non-Clustered

My lower level knowledge of SQL (Server 2008) is limited, and is now being challanged by our DBAs. Let me explain (I have mentioned obvious statements in the hope that I am right, but if you see something wrong, please tell me) the scenario: We have…
Craig
  • 18,074
  • 38
  • 147
  • 248
100
votes
11 answers

Must declare the scalar variable

@RowFrom int @RowTo int are both Global Input Params for the Stored Procedure, and since I am compiling the SQL query inside the Stored Procedure with T-SQL then using Exec(@sqlstatement) at the end of the stored procedure to show the result, it…
bill
  • 1,091
  • 2
  • 8
  • 9
100
votes
7 answers

Applying the MIN aggregate function to a BIT field

I want to write the following query: SELECT ..., MIN(SomeBitField), ... FROM ... WHERE ... GROUP BY ... The problem is, SQL Server does not like it, when I want to calculate the minimum value of a bit field it returns the error Operand…
isekaijin
  • 19,076
  • 18
  • 85
  • 153
100
votes
23 answers

Get a list of dates between two dates

Using standard mysql functions is there a way to write a query that will return a list of days between two dates. eg given 2009-01-01 and 2009-01-13 it would return a one column table with the values: 2009-01-01 2009-01-02 2009-01-03 …
Gilgad
  • 1,137
  • 4
  • 10
  • 10