Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
My question is trying to find a more elegant way of getting the desired results, maybe by using a `CASE` as I use here. I'm currently getting the results I need with the new requirement, but it's sorta verbose.
This was the previous query, it worked fine since it was a previous requirement. As you can see, the rows wi... | A correlated subquery should do it. Seems like you should be able to replace this:
```
case
when GeneralStatus = 'OK' then 'ENABLED'
when GeneralStatus = 'NOK' then 'DISABLED'
end GeneralStatus
from @table where id = ('P01') and unit in (11,22,33)
```
With this:
```
case
when (SELECT COUNT(*) FROM @tab... | consider
```
select
id,
case
when pgroup = 1 then 'Alpha'
when pgroup = 2 then 'Beta'
when pgroup = 3 then 'Gamma'
END,
case min(unit)
when 11 then 'G1'
when 22 then 'G2'
when 33 then 'G3'
end,
case
when min(GeneralStatus) = 'NOK' then... | Case with multiple values and without using dynamic sql? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
""
] |
If I use NewID in View then it will take 1 ms,
```
ALTER VIEW [dbo].[d]
AS
SELECT
NEWID() AS Id,
p.XX
,p.xx
FROM [view_XXX] as P
GO
select * .view_d where code='xxxx'
```
But If I use ROW\_NUMBER it will too much time to finish,
```
ALTER VIEW [dbo].[d]
AS
SELECT
Row_numb... | I think, `NEWID()` always creates any random number as ID(Doesn't need any calculation) But in case of `ROW_NUMBER()` SQL need to order the columns then provide ID.
As `ROW_NUMBER()` is more complex than `NEWID()` SQL server takes more time to process it. | `ROW_NUMBER()` will have the extra cost of sorting the result but `NEWID()` doesn't have this cost
If you look at the execution plan you can see the same:
> Click on the `Display Estimated Execution Plan` icon on the tool bar `SSMS`
See the below pics.
[](https://i.st... | Why adding ROW_NUMBER in View taking too much time to execute? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to implement a sql query in the following way:
```
INNER JOIN
`Product_has_ProductFeature` t ON `Product`.`id` = t.`productId` AND t.`productFeatureValueId` = 1
INNER JOIN
`Product_has_ProductFeature` t1 ON `Product`.`id` = t1.`productId` AND t1.`productFeatureValueId` = 5
```
How can I do this using `innerJoi... | `innerJoin()` is a [method](http://www.yiiframework.com/doc-2.0/yii-db-query.html#innerJoin()-detail) from the [Query](http://www.yiiframework.com/doc-2.0/yii-db-query.html) class.
You can try something like this.
```
$query = new \yii\db\Query;
$command = $query->innerJoin(
'Product_has_ProductFeature',
... | You can use the below code:
```
$model = Product::find()
->innerJoinWith('t', 'Product.id = T.productId')
->andWhere(['T.productFeatureValueId' => ''])
->innerJoinWith('t1', 'Product.id = T1.productId')
->andWhere(['T1.productFeatureValueId' => '5'])
->all();
``` | Yii2 innerJoin() | [
"",
"sql",
"yii2",
"inner-join",
""
] |
I am trying to get latest record based on date and time , but column contains time is in 12 Hours AM/PM format.
Suppose my records in
2015-09-07 12:50:37.1983315 PM - Coming this record
2015-09-07 03:12:15.1983315 PM - Actually I need to get this record.
The above result came by below query..
```
SELECT top 10 * ... | Try this
```
SELECT top 10 * FROM SHAdminMessageIndex
where Appid='62001308607984608300' and PolicyNumber='0081317'
order by
cast(BeginTime as datetime2) desc
```
OR
```
SELECT top 10 * FROM SHAdminMessageIndex
where Appid='62001308607984608300' and PolicyNumber='0081317'
order by
cast(left(Beg... | Try this
```
SELECT top 10 * FROM SHAdminMessageIndex where Appid='62001308607984608300'
and PolicyNumber='0081317' order by stuff(convert(varchar(19), BeginTime,
126),11,1,' ') desc
``` | How to get latest record based on date and time in Sql server | [
"",
"sql",
"sql-server",
""
] |
Please help me in writing the stored procedure. Here I'm having an input like something given below.
```
{local.txt_concept_id} != "" & {local.txt_ICD_code} != "" &
{local.txt_diagnosis_uniq_id} != "" & {local.txt_ICD_desc} != ""&
{FIND( {local.txt_ICD_code} , "asp", 0 )}!=-1&
{LEN( {local.txt_diagnosis_uniq_id})}
``... | Use this:
**[SqlFiddle](http://sqlfiddle.com/#!6/9eecb7db59d16c80417c72d1/2843/0)**
```
DECLARE @myString NVARCHAR(MAX) = '{local.txt_concept_id} != "" & {local.txt_ICD_code} != "" &
{local.txt_diagnosis_uniq_id} != "" & {local.txt_ICD_desc} != ""&
{FIND( {local.txt_ICD_code} , "asp", 0 )}!=-1&
{LEN( {local.txt_diag... | This should work for you...
```
declare @s VARCHAR(MAX)=
'{local.txt_concept_id} != "" & {local.txt_ICD_code} != "" &
{local.txt_diagnosis_uniq_id} != "" & {local.txt_ICD_desc} != ""&
{FIND( {local.txt_ICD_code} , "asp", 0 )}!=-1&
{LEN( {local.txt_diagnosis_uniq_id})}';
WITH DividedByAmpersand AS
(
SELECT CAST('... | Finding the text enclosed in "{" and "}" and inserting that into a table | [
"",
"sql",
"sql-server",
""
] |
I have this code:
```
SELECT username, first_name, last_name, NVL(salary,0) "salary"
FROM customer
WHERE NVL(salary,0) < AVG(NVL(salary, 0));
```
Trying to find out which users have lower salary than average and one user has no salary ("null" which I must convert to 0).
The last statement "avg(nvl(salary,0))" doesn'... | You can try to pre-select the average:
```
select username,first_name,last_name,nvl(salary,0) "salary"
from customer
where nvl(salary,0) < (select avg(nvl(salary,0)) from customer);
```
You can use `avg` only in `select` and `having` clauses, that is why you have an error.
Also don't use `nvl` but use `coalesce` ins... | Here's a method using an analytic function:
```
select username,
first_name,
last_name,
salary
from (select username,
first_name,
last_name,
nvl(salary,0) salary,
avg(nvl(salary,0)) over () avg_all_salaries
from customer)
wher... | Find value smaller than average in Oracle SQL | [
"",
"sql",
"oracle",
"average",
""
] |
I've been playing around with different queries regarding duplicates but this is not really what I need. I do need a list of duplicates but where the value in another column is different.
I'm trying to do this in SQL Server 2012.
I need to get a list of "duplicate" rows where the DocId is the same but they have a dif... | This approach uses ranking functions and a CTE:
```
WITH CTE AS
(
SELECT AuditId, DocMasterId, PoNumber,
RN_ASC = ROW_NUMBER() OVER (PARTITION BY DocMasterID ORDER BY PoNumber ASC),
RN_DESC = ROW_NUMBER() OVER (PARTITION BY DocMasterID ORDER BY PoNumber DESC),
CNT = COUNT(*) OVER (PARTITION BY D... | ```
select AuditId, DocMasterId, PoNumber
from ( select *, ROW_NUMBER() OVER (PARTITION BY DocMasterId, PoNumber ORDER BY DocMasterId ASC) as a from tablename ) abc
where a =1
```
I created a partition column using DocMasterId and PoNumber which will repeat the Row\_Number for every same value of DocMasterId, PoNum... | How to get a list of rows that have the same Id but different values in the same field | [
"",
"sql",
"sql-server",
""
] |
I've been racking my brain trying to come up with a solution for this, perhaps someone out there will find this an intriguing problem...
I've got a view:
```
[RecordID] [Status] [IsActive] [Company]
25791 NEW Active McDonalds
25792 NEW Terminated Rabble
25792 NEW Active Aetna
... | Perhaps this would work:
```
SELECT
RecordID
,MAX(Status)
,CASE WHEN COUNT(IsActive) > 1
THEN 'Multiple'
ELSE MAX(IsActive)
END
,CASE WHEN COUNT(Company) > 1
THEN 'Multiple'
ELSE MAX(Company)
END
FROM [Table_1]
GROUP BY RecordID
```
[
as(
select RecordId, Status, count(Status)
from #tblTest -- Whatever table name
group by RecordId, Status
)
select distinct... | Reduce a SQL Select based on Duplicates | [
"",
"sql",
"sql-server-2008",
""
] |
I have two tables, Countries and Sums:
```
+------+---------+
| code | country |
+------+---------+
| 01 | France |
| 02 | Germany |
| 02 | Austria |
| 03 | Belgium |
| 04 | Belgium |
| 04 | Spain |
| 05 | Italy |
+------+---------+
+------+-----+
| code | sum |
+------+-----+
| 01 | 500 |
| 02 ... | Try this:
```
DELETE
FROM code_sum_country
WHERE code in
(SELECT code
FROM code_sum_country
GROUP BY code
HAVING COUNT (code) > 1)
AND country NOT IN
(SELECT MIN(country)
FROM code_sum_country
GROUP BY code
HAVING COUNT (code) > 1)
```
This will retain the country whose name is minimum in alphabetical ... | If you want to query `sums` and get one arbitrary country, you can use a correlated subquery:
```
select s.*,
(select top 1 c.country
from countries as c
where s.code = c.code
) as country
from sums as s;
``` | How to delete some similar rows from a table? | [
"",
"sql",
"ms-access",
""
] |
I have string field `NAME` and some rows.
How I can ORDER these rows by `NAME` with DESC direction, but except one value with ID = 3?
So I need to add one value to the end:
```
A
B
C
KU-KU
``` | You can just put the logic in the `order by`:
```
order by (id = 3) desc, name
```
MySQL treats a boolean expression as a number in a numeric context, with true being 1 and false being 0. Hence the `desc` after the comparison. | Create a virtual column that handles the sort rule you require, such as this fairly trivial example:
```
SELECT CASE WHEN id = 3 THEN "~~~~~~~~~" ELSE name END AS sortfield,
name, ...
FROM ...
ORDER BY 1, 2
``` | How to order rows except one row in Mysql? | [
"",
"mysql",
"sql",
""
] |
My query works and is giving me correct results -- but it's ordering the two selects result sets separately and then concatenating the second result set to the end of the first and I don't know why! I want both sets to be ordered together.
```
(SELECT
m.m_name AS 'Merchant',
log.ship_day AS 'Date',
log.nu... | If you want the entire result-set to be `order`ed, you should have another `select` statement.
```
select * from
(your query with union all) t
order by 'Date' ASC , 'Merchant' ASC , '# Orders' DESC
``` | It you want the two subqueries to be ordered, then don't use constants in your `order by` statement. The proper escape character is backtick, but you only need that for that last columns:
```
ORDER BY Date ASC , Merchant ASC , `# Orders` DESC
```
As a general rule, do not use single quotes for column names. *Only* us... | MySQL union sorting select statements separately instead of combining | [
"",
"mysql",
"sql",
"subquery",
"sql-order-by",
"union-all",
""
] |
I am writing below query which divides the two select query and calculate the percentage. But i am getting an error as `not a single-group group function`
```
select CASE WHEN COUNT(*) = 0 THEN 0 ELSE round((r.cnt / o.cnt)*100,3) END from
(Select count(*) as cnt from O2_CDR_HEADER WHERE STATUS NOT IN(0,1) and DAT... | You don't need to use joins. If I were you, I'd do:
```
select case when count(*) = 0 then 0
else round(100 * count(case when status not in (0, 1) then 1 end) / count(*), 3)
end non_0_or_1_status_percentage
from o2_cdr_header
where date_created > sysdate - 1;
```
Here's a simple demo:
```
with ... | You are referencing an aggregate function (`COUNT(*)`) and an individual column expression (`r.cnt` and `o.cnt`) in the same SELECT query. This is not valid SQL unless a GROUP BY clause is added for the relevant individual columns.
It would be easier to provide a valid alternative it you could clarify what you'd like ... | not a single-group group function using select case statement | [
"",
"sql",
"oracle",
"group-by",
"case-when",
""
] |
I have a procedure where user inputs month e.g 'JAN' to extract data for that month. I want to compare the input month with month part in a date. This is what I got so far.
```
CREATE PROCEDURE SavingsAccountsAllDetail
(@Yr INT=NULL,
@Mon CHAR(3)=NULL)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Year INT
DECLARE @... | You're using `DATEPART` but passing it your property called `@Mon` which is a `CHAR(3)`, he cannot convert this `CHAR(3)` to `Date`, hence the error.
Your `@Mon` parameter should be an `Int` like `@Yr` and your query be
```
datepart(year, A.DateOpen)=@Year AND datepart(month, A.DateOpen) = @Month
``` | Your `@Year` and `@Month` variables are not dates. They are string representations of parts of a date.
When you extract the dateparts from `A.DateOpen` you can directly compare that to those variables:
```
datepart(year, A.DateOpen)=@Year AND datepart(month, A.DateOpen)=@Month
```
However, `datepart` will return a n... | Extract month number? | [
"",
"sql",
"sql-server",
""
] |
How can I select ALL ROWS and where A ROW is existent more then once, (based on ID) just take one (doesn't matter which one).
So I have:
```
ID name val
===========
1 | aa | 32
2 | aa | 32
3 | ad | 32
3 | zy | 11
4 | rr | 21
5 | oi | 44
5 | df | 11
```
result should be
```
ID name val
===========
1 | aa | 32
2 | aa... | The most convenient way to do it will be using Proc Sort:
```
PROC SORT DATA=HAVE OUT=WANT NODUPKEY;
BY ID;
RUN;
```
Otherwise if it is presorted, then @Reeza's solution is nice.
If you have to use Proc SQL, then an undomented feature may need to be implemented: monotonic():
```
PROC SQL;
CREATE TABLE WANT AS
SELECT... | A SAS data step answer, using First/Last processing
```
data want;
set have;
by id;
if first.id;
run;
``` | SELECT DISTINCT ON in SAS PROC SQL | [
"",
"sql",
"sas",
"proc-sql",
""
] |
I have 2 Requirements:
1. I want to write a SQL Command to fetch the Column Names from a Participant Table where the Column Name must be matching the word `%Track%`.
2. I want to fetch all the Table Name in the Database where it contains Column Name LIKE `%Track%`
`"USER_TAB_COLUMNS"` Does not run but gives error. `I... | > I want to fetch all the Table Name in the Database where it contains Column Name LIKE %Track%
You can try this
```
SELECT c.name AS ColumnName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%Track%'
```
---
> 1. I want to write a SQL Command to fetch the... | try this
```
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
COLUMN_NAME = 'Your column name'
``` | Fetch Column Name from Table | [
"",
"sql",
"sql-server",
""
] |
I need to connect two tables by two columns.
First table has primary key as integer type id.
Second table has varchar2 type column which contains the same primary key but is located in the middle of a string.
> For example in first table I have column called integer ID with ID
> like 1234. In the second table I have... | use [regexp\_replace](http://docs.oracle.com/cd/B12037_01/server.101/b10759/functions115.htm). try this query
```
select * from table1
where table1.ID in (select regexp_replace(column2, '[A-Za-z]') from table2)
```
syntax of regexp\_replace is
`REGEXP_REPLACE(string, target [, replacement [, position [, occurrence ... | From Oracle 11g you can use a virtual column:
[SQL Fiddle](http://sqlfiddle.com/#!4/30645/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE TableA (
id NUMBER(4,0) PRIMARY KEY
);
INSERT INTO TableA VALUES ( 1234 );
CREATE TABLE TableB (
data VARCHAR2(25) NOT NULL
CHECK ( REGEXP_LIKE( data... | Is there a way to use a part of varchar2 string as a primary key in oracle sql? | [
"",
"sql",
"oracle",
""
] |
I'm learning SQL, and i'm trying to select all the students who has the lowest test score from below:
```
Given TABLE STUDENTS:
id | name | test_score
1 | John | 89
2 | Marry | 0
3 | Lena | 100
4 | Peter | 0
```
I want to select both Marry and Pe... | ```
SELECT name FROM tableName
WHERE test_score = (SELECT MIN(test_score) FROM tableName)
``` | ```
SELECT
*
FROM
STUDENTS
HAVING
min(test_score)
``` | How to select the students who have lowest test scores? | [
"",
"mysql",
"sql",
""
] |
I've got the below statement to return flow id counts for today's date, joined to another table so we can see a little more meta data. With the left join though, it's not showing all the hubs that *dont* have data for today. I'm assuming it may be because of the where clause, but not sure how to fix that. Suggestions?
... | Move the `where` condition to the `join` clause.
```
LEFT JOIN table_o O ON O.FLOWID = R.FLOWID AND O.DATE = CONVERT(date,GETDATE())
``` | Because you are using the filter: `O.DATE = CONVERT(date,GETDATE())`, essentially making it an `INNER JOIN`, since the filter is applied on a column from the outer table. | Why won't NULL values return in a LEFT JOIN? | [
"",
"sql",
"sql-server",
""
] |
I need to reset the AutoIncrement field to 1 for tables in the database. I found that this can be done for a single table using:
```
DBCC CHECKIDENT (mytable, RESEED, 0)
```
How can I run this for all tables except tables with names that start with "\_"? | I'm using the next script for to do that. Maybe using `cursor` is not very performing but it is not take much time.
```
declare @TableName varchar(100)
declare cur_Cursor CURSOR STATIC
FOR
select TABLE_NAME
from information_schema.tables
where TABLE_TYPE = 'BASE TABLE'
and OBJECTPROPERTY(OBJECT_I... | You can try like this:
```
SELECT
IDENT_SEED(TABLE_NAME) AS Seed,
IDENT_INCR(TABLE_NAME) AS Increment,
IDENT_CURRENT(TABLE_NAME) AS Current_Identity,
TABLE_NAME,
'DBCC CHECKIDENT(' + TABLE_NAME + ', RESEED, ' + CAST(IDENT_SEED(TABLE_NAME) AS VARCHAR(10)) + ')'
FROM
INFORMATION_SCHEMA.TABLES
W... | Reset AutoIncrement for all tables not starting with "_" | [
"",
"sql",
"sql-server",
"auto-increment",
""
] |
I have two tables in join. Here i have to get mapped records when the Second table has set of records. But when the Second table has no record i need all records from first table.
```
Create Table #temp1
(Id1 int)
Create Table #temp2
(Id2 int)
Insert into #temp1 Values(1),(2),(3),(4)
Insert into #temp2 Values(1),(2)
... | If you only want columns from the first table:
```
select a.*
from #temp1 a
where exists (select 1 from #temp2 b where b.id2 = a.id1) or
not exists (select 1 from #temp2 b);
```
If you wanted the extra columns from the second table, you could use `union all`:
```
Select a.*, b.*
from #temp1 a Inner Join
#... | Actually you *can* use an `OUTER JOIN`:
```
SELECT Id1 FROM #temp1 t1
LEFT OUTER JOIN #temp2 t2
ON t1.Id1 = t2.Id2
``` | Get all records from Table When no records in Mapping Table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Suppose I have the following table:
```
ID Bag Event Count Driver Time
1 XYZ Pick-up 10 A1 10:30 AM
2 XYZ Trnsfr-out 10 A1 10:40 AM
3 XYZ Trnsfr-in 10 A2 10:40 AM
4 XYZ Drop 10 A2 10:50 AM
5 ABC Pick-up 10 B1 10:30 AM
6 ABC Trnsf... | If you are using Oracle (you tagged this question with both Oracle and SQL Server which are two different databases) you could use:
```
select bag,
count,
min(decode(id, min_bag_id, driver, null)) as initialdriver,
min(decode(id, max_bag_id, driver, null)) as finaldriver,
min(decode(id, max... | You can do it with `aggregate` functions.
[Fiddle with sample data](http://sqlfiddle.com/#!6/970ec/1)
```
select b.bag, max(b.count) as count,
max(case when time = mintime then driver end) as initialdriver,
max(case when time = maxtime then driver end) as finaldriver,
max(x.maxtime) as time
from
(select bag, min(T... | Extract Max and Min values of a column from a table in the same row | [
"",
"sql",
"oracle",
"sql-server-2008-r2",
""
] |
I'm trying to pass a dynamic SQL statement to spool out to a text file using SQL\*Plus, but I can't seem to execute the select statement I'm generating.
```
set linesize 10000 pagesize 0 embedded on
set heading off feedback off verify off trimspool on trimout on termout off
set underline off
COLUMN gen_sql NEW_VAL... | I think this is what you're trying to achieve:
```
set linesize 10000 pagesize 0 embedded on
set heading off feedback off verify off trimspool on trimout on termout off
set underline off
SPOOL myfilename.sql
SELECT 'SELECT table_name||'',''||column_name FROM USER_TAB_COLS WHERE ROWNUM < 10;' gen_sql_ FROM DUAL;
SP... | I believe you'll find `EXECUTE IMMEDIATE` is a PL/SQL command, so cannot be used directly in SQL or SQL\*plus.
<http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems017.htm>
Also, `SPOOL` is a SQL\*Plus command, and cannot be used in PL/SQL ..
So you have a problem there ;)
Can you step back a bit and expl... | Oracle Spool using Dynamic SQL | [
"",
"sql",
"oracle",
""
] |
If I limit my user's input SQL statement so that it starts with SELECT, can any injection attacks be run in that case? Am I leaving a different security hole (beyond getting access to all data that the schema has permission to access)?
**Edit**
What if I also ban semi-colon(;) ? | In short, yes. A SQL injection attack given a simple select:
```
var sqlCommand = "SELECT * FROM Table1 WHERE Field = '" & fieldValue & "';";
```
Could be modified by replacing the value of the variable `fieldValue` with the following:
```
fieldValue = "'; DELETE FROM Table1 WHERE 0 = 0 OR '' <> '";
```
Which when ... | Yes. If you are allowing your users to input SQL into a website (which is the typical case when you are talking about SQL injection attacks) you are opening yourself up to an avenue of attack. It doesn't matter if you restrict individual characters, or limit it to only beginning with a SELECT statement, in the end SQL ... | What are dangers from running SELECT queries supplied by users? | [
"",
"sql",
""
] |
What is the difference between money & numeric data type from point of practical usage. If one table has money as one of the data type (field name say BreakupAmount) & another one of numeric type (field name may or may not be same) then is it possible to post entries from these two fields into a third table where data ... | Never use MONEY; 1) It is proprietary, so porting it is a pain. It is one of the many "Sybase Code Museum" features from decades ago. Remember the early versions of UNIX?
2) Writing code in dialect when you don't need to make you sound like a hillbilly to people that speak the language. You are better off with DECIMAL... | Money doesn't provide any advantages over Decimal. If fractional units up to 5 decimal places are not valid in your currency or database schema, just use Decimal with the appropriate precision and scale.
```
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 Numeric(19,6),
@num2 Numeric(19,6),
@n... | difference between money & numeric data types? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table as follows
```
ID | Status ID | Value
1 | 1 | 100
2 | 1 | 200
3 | 1 | 300
4 | 2 | 100
5 | 2 | 150
6 | 2 | 200
7 | 3 | 500
8 | 3 | 300
9 | 3 | 150
```
I need to get the maximum value within the status. so my resu... | ```
create table #temp(id int, statusid int, value int)
insert #temp(id,statusid,value)
select 1,1,100
union select 2,1,200
union select 3,1,300
union select 4,2,100
union select 5,2,150
union select 6,2,200
union select 7,3,500
union select 8,3,300
union select 9,3,150
-- if you don't need the id
select statusid, ma... | Give this a go:
```
SELECT t.*
FROM TEST t
INNER JOIN (
SELECT STATUS,
MAX(VALUE) AS MAX_VALUE
FROM TEST
GROUP BY STATUS) gt
ON t.STATUS = GT.STATUS
AND t.VALUE = gt.MAX_VALUE;
``` | how to compare rows in the same sql table and get maximum value | [
"",
"sql",
"sql-server",
"oracle",
""
] |
I have a table on a Oracle DB with two columns. I would like to see every row repeated as many times as the number stored in the second column. The table looks like this:
```
col1 col2
a 2
b 3
c 1
```
I want to write a query that returns this:
```
col1 col2
a 2
a 2
b 3
b 3
b ... | [SQL Fiddle](http://sqlfiddle.com/#!4/18761/3)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE test ( col1, col2 ) AS
SELECT 'a', 2 FROM DUAL
UNION ALL SELECT 'b', 3 FROM DUAL
UNION ALL SELECT 'c', 1 FROM DUAL
```
**Query 1**:
```
SELECT col1,
col2
FROM test t,
TABLE(
CAST(
... | Here's an alternative (I've added an extra column just to show that other columns can be present), assuming that col1 is unique:
```
with src (col1, col2, col3) as (
SELECT 'a', 'b', 2 FROM DUAL UNION ALL
SELECT 'b', 'c', 3 FROM DUAL UNION ALL
SELECT 'c', 'd', 1 FROM DUAL
)
select col1, col2, col3
from s... | How to unfold the results of an Oracle query based on the value of a column | [
"",
"sql",
"oracle",
"split",
""
] |
I have a table like this:
```
initial confirmatory confirmatory1 confirmatory2 confirmatory3
3.4 true 3.6 4.9 7.4
2.1 false null null null
```
I want to generate a database view like this:
```
initial confirmatory_n confirmatory_value
3.4 ... | Use `union all`:
```
select initial_value, 1 as confirmatory_n, confirmatory1 as confirmatory
from results t
where confirmatory = 1
union all
select initial_value, 2 as confirmatory_n, confirmatory2 as confirmatory
from results t
where confirmatory = 1
union all
select initial_value, 3 as confirmatory_n, confirmatory3... | Another UNPIVOT solution:
```
WITH src ("INITIAL", confirmatory, confirmatory1, confirmatory2, confirmatory3) as (
SELECT 3.4, 'true', 3.6, 4.9, 7.4 FROM DUAL UNION ALL
SELECT 2.1, 'false', NULL, NULL, NULL FROM DUAL
), dta as (
select "INITIAL"
, case upper(confirmatory) when 'FALSE' then "INITIAL" end c... | Display extra rows (conditionally) separated by column name | [
"",
"sql",
"oracle",
"view",
"oracle11g",
""
] |
[SqlFiddle Demo](http://sqlfiddle.com/#!6/6470e/12)
I need to repeat each barcode of the article based on the quantity of this article in the table Stock.
This is source data:
```
| BarCode | quantity |
|---------|----------|
| 5142589 | 7 |
| 123454 | 5 |
| 1111145 | 3 |
```
I want result tha... | You can get this by a simple recursive **CTE**.
```
WITH cte
AS
(
SELECT IdArticle,1 AS rn FROM TABLE_STOCK
UNION ALL
SELECT t.IdArticle,rn+1 AS rn
FROM cte c
INNER JOIN TABLE_STOCK t ON t.IdArticle = c.IdArticle and rn<t.QUANTITY
)
SELECT t.BarCode,TS.QUANTITY
F... | You can use [table of numbers](http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1). Either permanent, or generated on the fly.
Query below uses `CTE` to generate up to 1000 numbers. Here is [SQL Fiddle](http://sqlfiddle.com/#!6/6470e/14/0).
```
WITH
e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL ... | Repeat row based on the number in a column | [
"",
"sql",
"sql-server",
""
] |
How to retrieve two different country date / time in single query? Whether I need to change any NLS parameters setting?
Sample query:
```
Select sysdate ind, sysdate us from dual;
```
O/p:
```
11/09/2015 3:05 PM 11/09/2015 05:35 AM
``` | Try;
```
select systimestamp ind, systimestamp at time zone 'US/Eastern' us
from dual;
```
If you interested in date then;
```
select
cast(systimestamp as date) ind,
cast(systimestamp at time zone 'US/Eastern' as date) us
from dual;
```
[Reference for all Time Zones](http://docs.oracle.com/cd/B19306_01/server... | I think you can do it with the third `noptions` parameter of the [to\_char](http://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_functions_2113.htm) function.
It also seems that you can use the [AT Timezone](http://docs.oracle.com/cd/B12037_01/server.101/b10749/ch4datet.htm#1007620) clause in your query
Here is an... | How to retrieve two country date/time using single query? | [
"",
"sql",
"oracle",
""
] |
How can I optimize this mysql query? I'm using the `IN()` operator, but I believe it's not the way to do it.
```
select *
from users
where usid NOT in
(
select usid
from images
where status=0
)
and us_status=0
``` | Using a LEFT OUTER JOIN
```
SELECT users.*
FROM users
LEFT OUTER JOIN images ON user.usid = images.usid AND images.status = 0
WHERE images.usid IS NULL
AND us_status = 0
```
This avoids using IN which can perform poorly. | ```
SELECT users.*
FROM users
LEFT JOIN images ON users.usid = images.usid AND images.status=1 AND images.usid IS NOT NULL
WHERE users.us_status = 0
``` | How can i optimize this mysql query ? i use IN() operator | [
"",
"mysql",
"sql",
"optimization",
""
] |
In our application we have a multiline grids which have many records. For inserting or updating we are calling a stored procedure.
As per the current implementation the stored procedure is calling for each line in the grid. For each line it checks the existence in the table. If data is already there, it will update th... | 1) Using TVP is good approach, but send only new or updated rows as TVP, no need to send entire datagrid.
2) For `INSERT/UPDATE` use [MERGE](https://msdn.microsoft.com/en-us/library/bb510625.aspx) example:
```
MERGE [dbo].[Contact] AS [Target]
USING @Contact AS [Source] ON [Target].[Email] = [Source].[Email]
WHEN MA... | 1) TVP is a good approach. And a single stored proc call is more efficient with fewer calls to the Database.
2) You haven't made it clear if each row in the grid has some kind of ID column that determines if the data exists in the Table, however assuming there is, make sure that it is indexed then use INSERT INTO and ... | Calling stored procedure to insert multiple values | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How it is possible to retrieve column headers of a select query as a single column in SQL Server ? (it is preferred to retrieve data type of columns )
Query example:
```
select a.PartId, a.PartName, b.GroupName
from Parts as a
inner join Groups as b on a.GroupRef = b.GroupId
```
Expected result:
```
Columns
----... | One way is to create a temporary table with the schema of resultset and then query `tempdb`'s schema table to get the column names and details. You can get all needed details.
```
select a.PartId , a.PartName , b.GroupName into #yourtable
from Parts as a inner join Groups as b
on a.GroupRef = b.GroupId
... | Starting from `SQL Server 2012+` you can use [sys.dm\_exec\_describe\_first\_result\_set](https://msdn.microsoft.com/en-us/library/ff878258.aspx) to get all metadata about result set:
**[DBFiddle Demo](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=5787cd733f5013fa69d1cc9e50e360b9)**
```
DECLARE @tsql NVARCHAR(MAX)... | How to Retrieve Column Headers of a Select Query? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
Lets say we have the following data sets
tbl\_building:
```
id -- name
1 -- building 1
2 -- building 2
```
tbl\_rooms:
```
id -- building_id -- room_id -- light_status
1 ------ 1 ------------- 1 ----------- 0
2 ------ 1 ------------- 2 ... | ```
Select b.name, case when sum (a.light_status) > 0 then 'YES' else 'NO' end as LightStatus
From tbl_rooms a
Join tbl_buildings b
On a.building_id = b.building_id
Group by b.name
``` | Try this:
```
SELECT DISTINCT B.name
FROM tbl_rooms A
INNER JOIN tbl_builiding B
ON A.building_id = B.id
``` | Finding value when multiple rows by group by | [
"",
"sql",
""
] |
Say I have a table like this called **inventory**, for example:
```
+----+------------+-------+
| id |Product_ID | Count |
+----+------------+-------+
| 1 | 1 | 4 |
| 2 | 2 | 5 |
| 3 | 4 | 3 |
| 4 | 5 | 3 |
| 5 | 5 | -3 |
| 6 | 2 | -5 |... | ```
with GroupedInventory as
(
SELECT Product_id, abs(sum(case when count < 0 then count else 0 end)) Negative, abs(sum(case when count > 0 then count else 0 end)) Positive
FROM inventory
group by Product_id
)
delete from inventory
where Product_id in (select Product_id from GroupedInventory where positive = negat... | Try this one
```
DELETE inventory
FROM inventory
INNER JOIN (
SELECT Product_ID FROM inventory group by Product_ID HAVING SUM(Count)=0
) as t ON inventory.Product_ID = t.Product_ID
``` | SQL: Grouped table; delete reciprocal pairs? | [
"",
"sql",
"sql-server",
""
] |
I want to make a daily dump of all the databases in MySQL using
> Event Scheduler
, by now I have this query to create the event:
```
DELIMITER $$
CREATE EVENT `DailyBackup`
ON SCHEDULE EVERY 1 DAY STARTS '2015-11-09 00:00:01'
ON COMPLETION NOT PRESERVE ENABLE
DO
BEGIN
mysqldump -user=MYUSER -password=MYPASS all-da... | For Windows, create a .bat file with the needed command, and then create a scheduled task that runs that .bat file according to a schedule.
Create a .bat file in this fashion, replacing your username, password, and database name as appropriate:
```
mysqldump --opt --host=localhost --user=root --password=yourpassword ... | @Drew means to use a cronjob. to add a cronjon just start the crontab using this command:
```
crontab -e
```
the add a new entry at the end like this:
```
0 0 * * * mysqldump -u username -ppassword databasename > /path/to/file.sql
```
this will perform a database dump every day at 00:00 | How to create a daily dump in MySQL? | [
"",
"sql",
"cron",
"mysql",
"mysql-event",
""
] |
I have a database table that has a Vendor\_ID column and a Vendor\_Item column.
```
Vendor_id Vendor_item
101 111
101 111
101 123
```
I need a way to show when vendor\_id and vendor\_item are combined, show if having count greater than 1. The vendor\_item number can be in there multiple t... | Not sure about the `UPC` column as from where and how you are getting it but you can change your existing query a bit like below to get the desired data
```
SELECT * FROM Inventory_master WHERE vendor_item IN (
SELECT vendor_item
From Inventory_master
group by vendor_item
having count(vendor_item) >1);
``` | You can use a subquery and then JOIN back to the inventory\_master table:
```
SELECT im.*
FROM
Inventory_master im INNER JOIN (
SELECT vendor_id, vendor_item
From Inventory_master
group by vendor_id,vendor_item
having count(*) >1) s
ON im.vendor_id = s.vendor_id AND im.vendor_item = s.vendor_item
... | SQL - Looking to show when 2 columns combined have the same data | [
"",
"sql",
"duplicates",
"sybase",
""
] |
I have two tables. Table 1 has about 750,000 rows and table 2 has 4 million rows. Table two has an extra ID field in which I am interested, so I want to write a query that will check if the 750,000 table 1 records exist in table 2. For all those rows in table 1 that exist in table 2, I want the respective ID based on s... | You're requesting all the rows in your select if b.UID is a unique field in column two.
Also if SSN is not unique in table one you can get the higher row count than the total row count for table 2.
You need to consider what you want from table 2 again.
EDIT
You can try this to return distinct combinations of ssn an... | Since the order detail table is in a one-many relationship to the order table, that is the expected result of any join. If you want something different, you need to define for us the business rule that will tell us how to select only one record from the Order detail table. You cannot effectively write SQL code without ... | SQL Query to fetch information based on one or more condition. Getting combinations instead of exact number | [
"",
"sql",
"sql-server",
"select",
"where-clause",
""
] |
I have this trigger to avoid similar names inserted in a table. But isn't working at all and not let me insert any row (as if the condition is true everytime). I tried with IF EXISTS and happen the same. Even deleting everything in the "Actor" table (leaving with no rows) and when I insert a new one the trigger fires.
... | Not trying to help you with the trigger because i don't think is your best option.
Why not create a unique constraint on those 2 fields?
```
ALTER TABLE dbo.Actor ADD CONSTRAINT UQ_ACTOR_NAME UNIQUE (firstname,lastname)
``` | I think your trigger always fires because, since you've inserted, you're always going to get a @@rowcount of at least 1. Try setting it to > 1 and see. | Trigger to avoid similar names inserted in tables isnt working and not let me insert any row | [
"",
"sql",
"sql-server",
"triggers",
""
] |
I am using mysql and pma. I have a table `mytable` and a column `time`, storing ~17K individual values, i.e. timestamps (integers).
I need to update each by adding `962758` to each timestamp. What does the SQL command for that look like?
```
SELECT (*) FROM `mytable` t1
UPDATE `mytable` SET time = + 962758
PROFIT? :)... | Considering that it's `TIMESTAMP` datatype, you can say
```
UPDATE `mytable` SET time = time + INTERVAL 962758 seconds;
```
Per your comment, since it's of `INT` type; you can just do the addition likewise you are already doing.
```
UPDATE `mytable` SET `time` = `time` + 962758;
``` | If the data is stored as a `datetime` value, then you simply can use:
```
select timestampadd(second, 962758, time)
```
If the value is a unix timestamp, then it is already in seconds, and you can just add 962758. | How to update timestamp values in column by adding a specific time (seconds) to the existing timestamp using mysql? | [
"",
"mysql",
"sql",
"date",
"phpmyadmin",
""
] |
I have a simple query like:
```
SELECT name FROM people;
```
The `people` table does not a have unique id column. I want to add to the query result a column `id` with incremental `int` starting from 0 or 1 (it doesn't matter). How can one achieve this? (postgresql DB) | Use `ROW_NUMBER()`:
[SQLFiddle](http://sqlfiddle.com/#!15/b5bb81/2/0)
```
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
```
**EDIT:**
Difference between `ORDER BY 1` vs `ORDER BY column_name`
[SQLFiddleDemo](http://sqlfiddle.com/#!15/a227e/4/1)
```
SELECT
name,
ROW_NUMBER() OVER ... | Check out the `row_number()` function at <https://www.postgresql.org/docs/current/static/functions-window.html> | SQL: Add column with incremental id to SELECT | [
"",
"sql",
"postgresql",
"select",
""
] |
I am using this query
```
select id, name, parent_id
from table_p
group by parent_id
having count(parent_id) > 1
```
So the problem with this is I need to put id and name in an aggregate function. Sorry for asking such basic question, but is there a way in which I can avoid this and print ids with duplicate parent\_i... | You can use a window function that counts the number of siblings:
```
SELECT id, name, COUNT(*) OVER (PARTITION BY parent_id) cnt
FROM table_p
```
then you can just use a subquery:
```
SELECT id, name
FROM (
SELECT id, name, COUNT(*) OVER (PARTITION BY parent_id) cnt
FROM table_p
) s
WHERE cnt>1
```
Please see ... | hope you can use this SQL
```
select id, name, parent_id
from table_p
where parent_id in (select parent_id
from table_p
group by parent_id
having count(parent_id) >1)
order by parent_id
``` | Group by with normal fields | [
"",
"sql",
"postgresql",
""
] |
This seems easy, but I can't get it. Assume this dataset:
```
ID SID AddDate
1 123 1/1/2014
2 123 2/3/2015
3 123 1/4/2010
4 124
5 124
6 125 2/3/2012
7 126 2/2/2012
8 126 2/2/2011
9 126 2/2/2011
```
What I need is the most recent AddDate and the associated ID for each SID.
So, my dataset should r... | You can use a subquery that returns the Maximum add date for each Sid, then you can join back this subquery to the dataset table:
```
SELECT
MAX(id)
FROM
ds INNER JOIN (
SELECT Sid, Max(AddDate) AS MaxAddDate
FROM ds
GROUP BY ds.Sid) mx
ON ds.Sid = mx.Sid AND (ds.AddDate=mx.MaxAddDate or MaxAddDate I... | You can change your query to get the grouping first and then perform a `JOIN` like
```
SELECT First(Table1.ID) AS FirstOfID,
Table1.SID, xx.MaxOfAddDate
FROM Table1 JOIN (
SELECT ID, Max(AddDate) AS MaxOfAddDate
FROM Table1
GROUP BY SID) xx ON Table1.ID = xx.ID;
``` | Getting the most recent data from a dataset based on a date field | [
"",
"sql",
"vba",
"ms-access",
"ms-access-2010",
""
] |
I am developing a Java application using MySQL. I need to know which is the week of each month, of the stored dates. Is there any MySQL function for that ? Basically , if i was to use this for the current date (13.09) it would show me its in week number 2 and tomorrow it will be week number 3. | You can play with the [WEEK()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week) function, and see if it suits your needs. Here I'm using `WEEK(date, 3)` that will return the week of the year from 1 to 53, starting from Mondays:
```
set @my_date = '2015-09-13';
SELECT
WEEK(@my_date... | Unfortunately, there isn't a "weekofmonth" function, but you could use [`dayofmonth`](https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_dayofmonth), and manipulate the result a bit:
```
SELECT CURRENT_DATE(),
FLOOR((DAYOFMONTH(CURRENT_DATE()) - 1) / 7) + 1 AS week_of_month
``` | Get the week of the month in MYSQL | [
"",
"mysql",
"sql",
"select",
""
] |
I have a column that contains numbers and other string values (like "?", "???", etc.)
Is it possible to add an "is number" condition to the where clause in SQLite? Something like:
```
select * from mytable where isnumber(mycolumn)
``` | From the [documentation](https://sqlite.org/lang_corefunc.html#typeof),
> The typeof(X) function returns a string that indicates the datatype of the expression X: "null", "integer", "real", "text", or "blob".
You can use `where typeof(mycolumn) = "integer"` | You could try something like this also:
```
select * from mytable where printf("%d", field1) = field1;
```
In case your column is text and contains numeric and string, this might be somewhat helpful in extracting integer data.
Example:
```
CREATE TABLE mytable (field1 text);
insert into mytable values (1);
insert i... | How to check if a value is a number in SQLite | [
"",
"sql",
"sqlite",
""
] |
I had following Table
```
CREATE TABLE Customer
( `Name` varchar(7), `Address` varchar(55), `City` varchar(15),`Contact` int,`timestamp` int)
;
INSERT INTO Customer
(`Name`,`Address`, `City`, `Contact`,`timestamp`)
VALUES
('Jack','New City','LA',79878458,456125),
('Joseph','New Lane23','LA',87458458,7... | > I want to get all customer record with highest timestamp without
> duplication.
Use `DISTINCT` operator and `ORDER BY` clause like
```
select distinct `Name`,`Address`, `City`, `Contact`,`timestamp`
from customer
order by `timestamp` desc;
```
In that case you can use `JOIN` query like
```
select t1.*
from custom... | Try the following.
```
select name,max(timestamp),Address,City,Contact from Customer group by name
``` | SQL Query for timestamp | [
"",
"android",
"sql",
"sqlite",
"android-sql",
""
] |
I'm trying to write a query for Select from 2 tables.
Tables are the following:
```
Table_1:
id (int)
name (varchar)
status int (0,1)
Table_2:
id (int)
table_1_id (int)
name (varchar)
time (datetime)
```
I need to select all the rows from Table\_2 which are no older than 1 day and that are associated with table\_... | No need of looping, you can do a `JOIN` between the tables like
```
select t2.*
from Table_2 t2 join Table_1 t1 on t2.table_1_id = t1.id
where t1.status = 1
and date(t2.`time`) = date(now() - interval 1 day);
``` | ```
SELECT table_2.* FROM table_1 t1 INNER JOIN table_2 t2 ON t2.table_1_id=t1.id
WHERE t1.status=1 AND time < (NOW() - INTERVAL 1 DAY);
```
You have to use `ON` to join tables since the fields in question do not have the same name. Otherwise you could have joined with `USING(id_field)`. In your case inner join is pr... | Join 2 tables SQL query | [
"",
"mysql",
"sql",
"join",
""
] |
I have a query that groups by (column\_a, column\_b) and selects an aggregated value. I would like to then group by column\_a and take an aggregate sum of the previously aggregated values.
Probably clearer with an example:
We have 3 tables: projects, devs, and contributors. Each project has many contributors, and eac... | Just use a subquery:
```
select project_name, sum(dedication)
from (<your query here>) q
group by project_name;
``` | Ivan,
You asked "Is there a way I can do this without having to do a sub-select" ... is there a reason you cannot sub-select?
Unfortunately, you'll need to use a sub-select, because you cannot combine aggregate functions (which would be the only way you'd be able to accomplish this). See: [How to combine aggregate fu... | SQL: how can I use GROUP BY to take an aggregate of an aggregate? | [
"",
"mysql",
"sql",
"group-by",
""
] |
I'm having some problems optimizing a certain query in SQL(using MariaDB), to give you some context: I have a system with "events"(see them as log entries) that can occur on tickets, but also on some other objects besides tickets(which I why I seperated the event and ticket\_event tables). I want to get all ticket\_eve... | OK what if you try to force the index?
```
SELECT * FROM ticket_event
INNER JOIN event
FORCE INDEX (index_for_display_time)
ON event.id = ticket_event.id
ORDER BY display_time DESC
LIMIT 25;
``` | Your query selects every column from every row, even if you use a LIMIT. Have you tried to select one specific row by id? | Relatively simple SQL query with join refuses to be efficient | [
"",
"mysql",
"sql",
"query-optimization",
"mariadb",
""
] |
I need to run multiple select count queries to count how many people are available at certain times through the day to plot into a table from ms sql server.
I have the below sql which works, but is returning each count as a new table, I would like them to all in one table on different columns.
```
DECLARE @Day varcha... | Option 1, put it in 2 rows with `UNION ALL`:
```
SELECT COUNT(*) as Counts, 'Available0700' AvailableTime
FROM ...
UNION all
SELECT COUNT(*) as Counts, 'Available0800' AvailableTime
FROM ...
```
Option 2, in 2 columns with subqueries:
```
SELECT (SELECT COUNT(*) FROM ...) as Available0700,
(SELECT COUNT(*) FR... | I think you can store these values in variables and finally select these variables in your select query.
Below is an example code in which i have used a table variable to execute the dynamic queries and store the records and finally used a PIVOT query to fetch the require output.
```
DECLARE @tablevar TABLE
(
Que... | Multiple Dynamic Selects queries in one return | [
"",
"sql",
"sql-server",
"select",
""
] |
I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible. | You need to create a VBA function that returns the username, and then use the function in the query.
```
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
```
and
```
SELEC... | My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The `CHR(34)` puts quotes around the name as it is now a string inside the SQLSTR and needs to be wi... | How to use system username directly in MS Access query? | [
"",
"sql",
"vba",
"ms-access",
""
] |
I will have a relatively large growing dataset with 250M+ rows with a very basic table structure:
`id (unsigned int primary)`, `age (tinyint)`, `email (some type of string)`
where I will be performing `count(*)` queries based on `age` grouped by `email`. For example:
```
select count(*) as count from table
where ag... | Here is how I moved forward. As I mentioned I don't need the very precise results and I will be fine with approximate results as long as the queries run as fast as possible.
So I defined email field as `bigint` (8 bytes, small size, fast operations) and saved the emails using the function `hex( substr( md5( email), 4,... | It seems like your table is poorly designed (denormalized in a way that's going to hurt performance instead of help it), and should be refactored into two or more tables. While denormalization might make some things easier, it's going to make this query that you need to refresh every two minutes very expensive - no mat... | How to achieve absolute fastest way when doing COUNT(*) GROUP BY string | [
"",
"mysql",
"sql",
""
] |
Hi im obtaining data from a table through a query.. i need to omit some of the data types, currently i cant write the query for that
```
+--------+----------------------+-----------+----------------+
| aut_id | aut_name | country | home_city |
+--------+----------------------+-----------+-----------... | Use `NOT IN`:
```
SELECT d.country, COUNT(*) AS number FROM ..............
AND d.country NOT IN ('brazil', 'Austria', 'Chillie')
GROUP BY d.country
``` | Do this...
[edit]
```
SELECT d.country, COUNT(*) AS number FROM ..............
AND d.country NOT LIKE 'brazil' AND d.country NOT LIKE 'Austria' AND d.country NOT LIKE 'Chillie'
GROUP BY d.country;
```
Above works but other people answers are best...! | Writing the filtering query to ignore some strings | [
"",
"mysql",
"sql",
""
] |
I have the below table with 2 columns
```
ID | Dept
1 | A
2 | A
3 | B
4 | B
5 | B
6 | A
```
I want to do a count such that the output should look as the table below.
```
Dept | Count
A | 2
B | 3
A | 1
```
Thanks for you... | Slightly different to Michael's, same result:
```
with cte1 as (
select id,
dept,
row_number() over (partition by dept order by id) -
row_number() over (order by id) group_num
from test),
cte2 as (
select dept,
group_num,
count(*) c_star,
... | From your example, it looks like you're wanting to count sequential records for each department.
You can do this by combining the row number and the ordering Id.
```
create table tblDept (
id int not null,
dept varchar(50)
);
insert into tblDept values (1, 'A');
insert into tblDept values (2, 'A');
insert i... | SQL Grouping by sequential occurrences of a value | [
"",
"sql",
"database",
"oracle",
"gaps-and-islands",
""
] |
I'm creating a web app that displays a pie chart. In order to get all the data for the chart from a **PostgreSQL 9.3** database in a single HTTP request, I'm combining multiple `SELECT` statements with `UNION ALL` — here's a portion:
```
SELECT 'spf' as type, COUNT(*)
FROM (SELECT cai.id
FROM common_acti... | You can bundle most of the cost in a single main query in a [CTE](http://www.postgresql.org/docs/current/interactive/queries-with.html) and reuse the result several times.
This returns a **single row with three columns** named after each `type` ([as requested in the comment](https://stackoverflow.com/questions/325443... | This is only a sketch of a completely different approach: construct a boolean "hypercube" for all conditions that you need
in your "crosstabulation". the logic of selecting or aggregating subsets can be done later (such as suppressing the exit\_tickets, for which the business logic is not clear to me)
---
```
SELECT ... | Better way than multiple SELECT statements? | [
"",
"sql",
"postgresql",
"select",
"common-table-expression",
"postgresql-performance",
""
] |
I am trying to fetch data between two dates. My query is:
```
select *
from TABLE
where CREATED_DATE >= '11-MAY-2015'
and CREATED_DATE <= '11-MAY-2015'
```
It doesn't return any value. Though the data is present for 11th May and can be fetched if I give the dates as
```
CREATED_DATE >= '11-MAY-2015' and CRE... | DateType `Date` do have time part also.
When you say `'11-MAY-2015'` its actually `'11-MAY-2015 00:00:00'`
> Date
> This datatype contains the datetime fields YEAR, MONTH, DAY,
> HOUR, MINUTE, and SECOND. It does not have fractional seconds or a
> time zone.
Try this query
```
select *
from TABLE
where
CREATED... | Depending on the CREATED\_DATE datatype You may need to use the [TO\_DATE](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm) function. Try this:
```
select * from TABLE where
CREATED_DATE >= TO_DATE('2015-05-11 00:00:00', 'YYYY-MM-DD HH24:Mi:SS')
and CREATED_DATE <= TO_DATE('2015-05-12 23:59:59... | Getting data between dates is not accurate | [
"",
"sql",
"oracle",
""
] |
I have two tables :
PEOPLE
```
ID |NAME
|A2112 |John
|B3200 |Mary
|C2454 |Bob
|F2256 |Joe
```
JOBS
```
|ID |NAME |PEOPLE
|56565 |Taxi Driver |A2112
|23232 |Herborist |A2112
|12125 |Jumper |B3200
|25425 |Taxi Driver |... | Not quite sure if I got you right. This will return people who have job 56565 and/or 23232:
```
select distinct p.name
from people p
join jobs j on p.id = j.peopleid
where j.id in (56565, 23232)
```
If BOTH jobs are required:
```
select p.name
from people p
join jobs j on p.id = j.peopleid
where j.id in (56565, ... | The [INNER JOIN](https://dev.mysql.com/doc/refman/5.7/en/join.html) keyword selects all rows from both tables as long as there is a match between the columns in both tables.
```
SELECT
p.NAME, COUNT(*) as tot
FROM
PEOPLE p
INNER JOIN JOBS j ON (p.ID = j.PEOPLE)
WHERE
j.ID IN (56565, 23232)
GROUP B... | SELECT records from two table | [
"",
"mysql",
"sql",
""
] |
I have following SQL for Microsoft SQL Server
```
SELECT *
FROM tblA
WHERE CREATION_DATE BETWEEN DATE'2015-09-12' AND DATE'2015-09-15'
```
But this throws a syntax error:
> Error: Incorrect syntax near '2015-09-12'. SQLState: S0001 ErrorCode:
> 102
What is wrong? I want to use ANSI literal code. | This is not how you cast in MS SQL Server. Instead, you should try the `cast` syntax:
```
SELECT *
FROM tblA
WHERE creation_date BETWEEN CAST('2015-09-12' AS DATE) AND
CAST('2015-09-15' AS DATE)
``` | You can simply use this query, without adding date:
```
SELECT *
FROM tblA
WHERE CREATION_DATE BETWEEN '2015-09-12' AND '2015-09-15'
``` | SQL Server gives syntax error | [
"",
"sql",
"sql-server",
"date",
"select",
""
] |
I have a table that contains the following columns:
1. ID
2. Master ID
The Master ID can be shared between different rows with different IDs.
E.g.:
```
ID | Master ID
1 | 1
2 | 1
3 | 1
4 | 2
```
Knowing the ID I want to retrieve all the rows that share the same master ID
I managed to do it using this quer... | The queries are doing different things, the first you are saying:
```
1. give me all rows from `table` where `id = 1`
2. Also give me rows from t2 with a matching master ID
```
In the second you are saying
```
1. Give me all rows from `table`
2. Return rows from `t2` with a matching master ID and where `t1.ID = 1`
`... | If the `t.ID = '1'` condition is in the WHERE clause the `t.ID='1'` condition only has to be evaluated for the number of rows in t. If the `t.ID='1'` condition is put into the ON clause for the join it must be evaluated for all rows in t2. If there are a lot of rows in t2 this can significantly increase the run time of... | Why is my SQL request much slower when the condition is in the join? | [
"",
"sql",
"oracle",
"join",
"left-join",
""
] |
Good afternoon,
I am trying to put together a query that will select data from 2 tables when using the MAX() function to return the user's most recent login time.
The tables are as follows:
USERS:
```
USERNAME CREATED
JOHNSMITH 01/01/2015
MATTTYLER 12/12/2013
DAVIDCROSS 09/07/2014
SA... | Do a `LEFT JOIN` to also get users never logged in. `GROUP BY` with `MAX` to get each user's latest `TIMESTAMP`.
```
select u.username, u.created, max(s."TIMESTAMP")
from users u
left join sessions s on u.username = s.username
group by u.username, u.created
```
SQL-92 (join used. `Timestamp` is a reserved word in S... | Another way to do this is via analytic functions:
```
select username,
created,
"TIMESTAMP"
from (select u.*,
s."TIMESTAMP",
row_number() over( partition by u.username
order by s."TIMESTAMP" desc ) as rnk
from users u
l... | Oracle SQL Query - Join when using MAX() function | [
"",
"sql",
"oracle",
""
] |
Code:
```
ALTER TABLE tblUser
DROP COLUMN Mobile
```
Error:
> ALTER TABLE DROP COLUMN Mobile failed because one or more objects access this column.
This column had values in Table. How can I delete all objects that access this column?
How can I `DROP COLUMN` with values?
how can do it with code? How can I delete ... | ```
ALTER TABLE DROP COLUMN Mobile failed because one or more objects access this column.
```
Your column won't be deleted. Because one column or multiple columns are getting reference from this column that you want to delete.
So first, you will have to find in which table your column is being referenced by below que... | Use below query to find the constraints name for particular tablename
```
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'TABLENAME'
```
Noe you can see the constraints name under constraint\_name column, drop all constraint using below syntax
```
ALTER TABLE TABLENAME DROP CONSTRAINT CONS... | How can I DROP COLUMN in Microsoft SQL Server with a value? | [
"",
"sql",
"sql-server",
"alter",
""
] |
I have two tables in a database: **Events** and **Dates**, with a one-to-many relationship between them (*1 event can take place along many dates*).
I want to query the database to get the future and past events like this:
* Query to get **future events** should return every event with a date >= CURDATE() **and event... | First off, as you laid them out, your queries don't need a `GROUP BY` clause, as there is no aggregation being done (no `count`, `max`, etc).
You have to separate "join logic" and "condition logic", so I suggest:
Past events:
```
SELECT dates.*, events.*
FROM events
JOIN dates on (events.eventID = dates.eventID)
WHE... | If a record in events table will always have a record in the dates table, then you could use
```
SELECT dates.*, events.*,
FROM events
JOIN dates on (events.eventID = dates.eventID AND NVL(dates.date, CURDATE()) >= CURDATE())
GROUP BY events.eventID
ORDER BY events.eventID ASC
```
I guess I don't follow why past even... | Join + date condition in SQL query | [
"",
"mysql",
"sql",
"join",
"left-join",
""
] |
```
Select *
from tableA
inner join tableB on tableA.id = tableB.aid
and cast(a.date AS DATETIME) = CAST('2015-08-24' AS DATETIME)
```
Values that stored in `tableA.date` are '2015-08-24' meaning data has no issue.
When I execute the above statement, I get
> The conversion of a date data type to... | The **root cause** of the problem is this:
* the data type `DATE` has a range of accepted values from `01-01-0001` through `12-31-9999`
* the data type `DATETIME` has a range of accepted values from `01-01-1753` through `12-31-9999`
So if you happen to have a `DATE` from before 1753, or an empty / NULL value - this w... | Use the format yyyymmdd which is universal in SQL Server,
```
Select * from tableA inner join tableB
on tableA.id = tableB.aid
and cast(a.date AS DATETIME) = CAST('20150824' AS DATETIME)
```
I did not see the problem with the '0001-01-01' value in `a.Date`. You could do a bit dirty trick like this:
```
Select * fr... | SQL doesn't allow to cast date column to datetime? | [
"",
"sql",
"sql-server",
"date",
"datetime",
""
] |
I've the following tables with some data:
```
Collector:
dcid name hostid userid
123 test host1 234
567 hello host2 345
CollectorConfiguration:
ID propertyname propertyvalue collector_id(foreign key)
id1 c_source local 123
id2 c_createdby admin 123
id3 c_pattern JBoss ... | With the EAV model you should have a bunch of helper views to overcome the problems like this. The views will act as tables, such as collector\_patterns, collector\_sources, etc.
```
SELECT c.*
FROM Collector c LEFT JOIN
CollectorConfiguration cc on c.dcid = cc.collector_id
where cc.propertyname = 'c_pattern'
ORDER BY... | ```
SELECT a.* FROM Collector a
LEFT JOIN CollectorConfiguration b ON b.collector_id=a.dcid
WHERE b.propertyname="c_pattern"
```
Rather the question is not so clear to me, but I guess you are looking for so. | SQl sorting based on certain property value of joined table | [
"",
"sql",
"hsqldb",
""
] |
Is there any way to get *all* records matching these conditions:
* (`userid = 1 AND (status < 2 OR time > INTERVAL '1 day')`)
And if there are less than 10 records and more (if available) for:
* `userid = 1`
Get up to 10 (last, by `time`)? | You want to `get all records matching`. A hard `LIMIT 10` would be wrong for the purpose. You only want to add rows up to a maximum of 10 according to *secondary* conditions ***if*** there are not enough rows for your *primary* conditions. But there can be more than 10 rows already for the primary condition alone.
###... | You can do this by prioritization using `order by`. If you want 10 records:
```
select t.*
from table t
where userid = 1
order by (case when status < 2 OR time > INTERVAL '1 day' then 1 else 2 end),
time desc
limit 10;
``` | Get all records matchung some conditions OR at least 10 by adding some others | [
"",
"sql",
"postgresql",
""
] |
I have a hash-table:
```
CREATE TABLE hash_table ( hash_id bigserial,
user_name varchar(80),
hash varchar(80),
exp_time bigint,
PRIMARY KEY (hash_id));
INSERT INTO hash_table (hash_id, user_name, exp_time) VALUES
(1, 'one', 10),
(2, 'two', 20),
(3, 'three', 31),
(4, 'three', 32),
(5, 'three', 33),
(6, 'three... | You can use `row_number` to number rows of a user based on `exp_time` in the descending order. And then delete user rows from the table who have more than 10 entries.
[Fiddle with sample data](http://sqlfiddle.com/#!15/ad4ea/1)
```
delete from hash_table as h
using
(
SELECT user_name, exp_time,
row_number() ove... | This will keep 3 newest records for each user\_name:
```
DELETE FROM hash_table h
USING
(
SELECT
user_name,
exp_time,
row_number() OVER (PARTITION BY user_name ORDER BY exp_time DESC) AS r
FROM
hash_table
) AS s
WHERE
h.user_name = s.user_name
AND h.exp_time<s.exp_time
AND s.r=3
``` | Delete all rows with specified parameters but newest in Postgresql | [
"",
"sql",
"postgresql",
"sql-delete",
""
] |
```
CREATE PROCEDURE [dbo].[AdminCheck] (@Name nvarchar, @Password int)
AS
Select * from Admin
where AdminName = @Name AND AdminPassword = @Password
Go
```
Above is my `stored procedure`
I got `Admin` as `AdminName` and `123` as `AdminPassword` in `Admin` table.
When I run it it does not work. | When you say
```
@Name nvarchar
```
The size of the variable will be 1 by default:
Hence your query will be compared to the first character of `@Name` variable:
Provide proper size for your variable;
```
@Name nvarchar(150)
``` | You defined your parameter as a NVARCHAR - it means ONE symbol.
```
CREATE PROCEDURE [dbo].[AdminCheck] (@Name nvarchar, @Password int)
```
So when you call it `AdminCheck('Admin',123)` then `@Name` is actually `'A'` not `'Admin'`
It should be for example:
```
CREATE PROCEDURE [dbo].[AdminCheck] (@Name nvarchar(100... | stored procedure does not work | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have got a table with 3 columns: (int) `test1`, (int) `test2` and (int) `test3`. The content is an integer or `NULL`.
For example:
```
╔═══╦════════════╦═════════════╦═════════════╗
║ ║ test1 ║ test2 ║ test3 ║
╠═══╬════════════╬═════════════╬═════════════╣
║ 1 ║ 123 ║ 456 ║ NULL ... | `null` is not a value - it's the lack thereof. It returns "unknown" when used in any context expecting a value, even the `!=` operator. In order to handle `null`s, you should do so explicitly with the `is` operator:
```
SELECT *
FROM mytable
WHERE (test1 IS NULL OR test1 != 123) AND
(test2 IS NULL OR test2... | Use `ifnull()` to convert nulls to an included number:
```
SELECT * FROM table
WHERE ifnull(test1, 0) != "123"
AND ifnull(test2, 0) != "123"
AND ifnull(test3, 0) != "123";
``` | SQL SELECT is not a number but can be NULL | [
"",
"mysql",
"sql",
"select",
"null",
""
] |
Wondering how to write a SQL function to find the N-th largest element in a table, and if no N-th largest element, return Null.
Using MySQL/MySQL workbench.
BTW, my question is different from the N-th highest salary question since I have one additional requirement, which is return Null if N-th largest element does no... | You could do this:
```
SELECT t1.*
FROM (
SELECT *
FROM my_table
ORDER BY value DESC
LIMIT 1
OFFSET N -- Set your value for N here, N being 0-based
) t1
RIGHT OUTER JOIN (
SELECT null -- This will guarantee that you have at least one row
) t2
ON TRUE
``` | I can think of no instance where I would want to do this...
```
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT CASE WHEN COUNT(*) = 9 THEN x.i ELSE NULL END i
FROM ints x
JOIN ints y
ON y.i <= x.i
GROUP
BY x.i
ORDER
BY i DESC
L... | find the N-th largest element in SQL | [
"",
"mysql",
"sql",
""
] |
I have two queries that return a single value, from different tables (and not joined via a relationship in any way), and I'm trying to combine both queries' outputs onto a single row, however I'm getting a syntax error. This is what I'm trying:
```
SELECT
(SELECT Timestamp As StartDate
FROM Events
WHER... | SQL CE does not support nesting SELECT statments like this, so you have to use two SELECT statements and use UNION or call ExecuteNonQuery twice. | The first query might return 2 or more values unlike the second query.
Try putting a `TOP (1)` also in the first query since I think you're just gunning for the top results.
```
SELECT
(SELECT TOP (1) Timestamp As StartDate FROM Events WHERE Description = 'Inserted') AS StartDate,
(SELECT TOP (1) Timestamp As EndDate ... | SQL Server CE : how can I combine results of two queries into one row? | [
"",
"sql",
"sql-server",
"sql-server-ce",
""
] |
I have a `users` table with fields user\_id and username and I am querying it like so:
```
SELECT user_id, username FROM users WHERE user_id=$1
```
I also have a `votes` table that has fields post\_id and user\_id.
user\_id is a foreign key referencing the user\_id field in the users table.
I would like to add to my... | Okay this finally worked for me...
```
SELECT u.user_id
,u.username
,ARRAY(SELECT v.post_id FROM votes v WHERE v.user_id=u.user_id) AS votes
FROM users u
WHERE u.user_id=$1
```
it returned:
```
user_id | username | votes
---------+----------+-------
6 | dbot77 | {3,5}
``` | Try this:
```
SELECT users.user_id, users.username, votes.column_name
FROM votes
INNER JOIN users
ON votes.user_id = users.user_id
WHERE votes.user_id = $1;
```
Refer to:
<http://www.tutorialspoint.com/postgresql/postgresql_using_joins.htm> | select user and all votes SQL | [
"",
"sql",
"postgresql",
""
] |
Here's a sample of my PostgreSQL in CSV format.
```
row,latitude,longitude
1,42.082513,-72.621498
2,42.058588,-72.633386
3,42.061118,-72.631541
4,42.06035,-72.634145
```
I have thousands more rows like these spanning coordinates across the world.
I want to query the table only for coordinates within a certain radius... | I did a combo of Erwin's and Patrick's answers.
```
-- Add geography column
ALTER TABLE googleplaces ADD COLUMN gps geography;
UPDATE googleplaces SET gps = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326);
CREATE INDEX googleplaces_gps ON googleplaces USING gist(gps);
SELECT *
FROM my_table
WHERE ST_DWithin(gps, ... | You want *"all rows within a 5-mile radius of a coordinate"*, so this is *not* exactly a [K-nearest-neighbour (KNN) problem](http://boundlessgeo.com/2011/09/indexed-nearest-neighbour-search-in-postgis/). Related, but your case is simpler. *"Find the 10 rows closest to my coordinates"* would be a KNN problem.
Convert y... | How do I query all rows within a 5-mile radius of my coordinates? | [
"",
"sql",
"postgresql",
"indexing",
"postgis",
""
] |
I have a table with two columns; `EVENT_DATE` date and `RANG` number the first column holds a date for an event while the second column is for the period of that event. here is a sample of data
```
| EVENT_DATE | RANG |
|------------|------|
| 03/01/2015 | 1 |
| 09/04/2015 | 3 |
| 15/10/2015 | 2 |
```
is the... | Here you go.
```
select to_char(event_date + (l - 1),'dd/mm/yyyy') from tab1 t
left outer join (
select level l from dual
connect by level <= (select max(rang) + 1 from tab1)
) on l <= rang + 1
order by event_date, 1;
```
[SQL Fiddle](http://sqlfiddle.com/#!4/27fef0/15) | This should work:
```
select (t.event_date + t2.value) as event_date
from t, (select rownum -1 as value from all_objects) t2
where t2.value <= t.rang
order by 1 asc;
``` | Expand table rows based on column value | [
"",
"sql",
"database",
"oracle",
""
] |
I have the sample data [See the SQL Fiddle](http://sqlfiddle.com/#!6/5d6e6/1). I want to find the lowest value from the value column and the date of lowest value from the uploaded-date column. I tried the following query and it is not properly working and showing all values.
```
SELECT
username,
MIN(Value1) AS... | You could use the [`RANK`](https://msdn.microsoft.com/en-us/library/ms176102.aspx) window function to find the minimal value for each username:
```
SELECT username, value1, uploaded_date
FROM (SELECT username, value1, uploaded_date,
RANK() OVER (PARTITION BY username ORDER BY value1 ASC) AS rk
... | ```
SELECT test. username,value1,MIN(uploaded_date )FROM
(Select MIN(value1) MinValue1,username from test group by username ) A
INNER JOIN
test
ON A.MinValue1 = test.Value1
AND A.username = test.username
GROUP BY
test. username,value1
```
Your query did not work because you were using the columns in the select list ... | How to find the lowest value and the corresponding date SQL-Server 2014 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
""
] |
I'm using MySQL 5.6.23-enterprise-commercial-advanced. I have a table called `FILE` as:
```
+---------+
| file_id |
+---------+
| 11 |
| 12 |
| 13 |
| 14 |
+---------+
```
I try to run a query of `SELECT A.FILE_ID FROM FILE A;` under **root@localhost**, and it is successfully executed. But there i... | Because you're giving the table an alias of `A` so you're essentially temporarily renaming the table during the select statement.
See link for more information - [MYSQL ALIAS](http://www.mysqltutorial.org/mysql-alias/) | In your case `A` as alias of table. So you must need to write `as` between `FILE` and `A`. So now your query is like this
```
SELECT A.FILE_ID FROM FILE as A;
``` | Why does such statement work in MySQL? | [
"",
"mysql",
"sql",
"select",
""
] |
Sorry for the confusing title; however a description and illustration should hopefully clear it up.
Essentially, I have the table `A` representing instances of a transfer of an 'amount' between rows of table `B.` I wish to join `A` with `B` so that I can display the details of the transfer:
```
================= A ==... | You can join `a` on `b` twice:
```
SELECT aid, from_b.name, to_b.name, amount
FROM a
JOIN b from_b ON from_b.bid = a.fromid
JOIN b to_b ON to_b.bid = a.toid
``` | You can do this with out `join`.
[Fiddle with sample data](http://www.sqlfiddle.com/#!6/c15af/1)
```
select aid,
(select name from b where a.fromid = bid) as "from",
(select name from b where a.toid = bid) as "to",
amount
from a
``` | Join a table representing a "transfer" between two rows of another table | [
"",
"sql",
"sql-server",
"select",
"join",
""
] |
I am using a SQLLite Database and I want to copy values from one table to another. So I found this:
```
INSERT INTO `table1` (`row_id`, `daystamp`, `column1`, `column2`) SELECT `position`, 2015813, `column1`, `column2` FROM `table2`
```
The problem is that the "table1" has more columns than the four.
As result the ot... | Define a `Default value` for those columns while creating your table (or) perform a `ALTER` and provide a default value like
```
colum3 varchar(10) default ''
```
You can as well change your `INSERT` statement to insert some default values for those columns like
```
INSERT INTO `table1` (`row_id`, `daystamp`, `colum... | You need to specify the columns and the values in the `insert`:
```
INSERT INTO `table1` (`row_id`, `daystamp`, `column1`, `column2`, column3, column4)
SELECT `position`, 2015813, `column1`, `column2`, <some value>, <some value>
FROM `table2`;
```
Alternatively, when you define the table, you need to specify ... | Insert empty data not null | [
"",
"sql",
"sqlite",
""
] |
I have a sql query where I have to get records count, I am getting counts correctly with the current query but I want to only get counts for records where 'Unchecked Count' is not zero.
```
SELECT
dbo.Customer.AccountNo AS Cust_Acc_No,
dbo.Customer.Name AS [Customer Name],
dbo.Customer.Adrs1 A... | You can query the result of the other query.
`SELECT * FROM ( <your query> ) AS T WHERE [Unchecked Count] > 0` | Try `Having` clause after your `group by` clause
```
having [Unchecked Count] > 0
```
Full query
```
SELECT dbo.Customer.AccountNo AS Cust_Acc_No, dbo.Customer.Name AS [Customer Name], dbo.Customer.Adrs1 AS Cust_Address_1, dbo.Customer.Adrs2 AS Cust_Address_2, dbo.Customer.City AS Cust_City,
... | SQL QUERY case with a condition | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
The sql tables are as follows: likes with columns drinker and beer, sells with columns bar and beer and frequents with columns drinker and bar.
I have previously answered the following statement:
```
"Drinkers who frequent bars which serve some beer they like"
```
with the SQL Query:
```
SELECT DISTINCT y.drinker
F... | Drinkers who frequently exactly the number of bars as those they frequent which sell their favorites:
```
select drinker
from frequents
group by drinker
having count(bar) = (
select count(distinct f.bar)
from
sells s
inner join likes l on l.beer = s.beer
inner join frequents f on f.bar ... | I think this is a valid solution...
The subquery is used to filter out drinkers who frequent a bar that has a 0 count of beers they like.
```
select distinct drinker
from frequents
where drinker not in (
select f.drinker
from frequents f
join sells s on f.bar = s.bar
left join likes l on l.drinker ... | SQL Beginner Query Logic With 3 Tables | [
"",
"mysql",
"sql",
"querying",
""
] |
all. My question is easy, but I can't solve it by myselft.
I have 2 tables: et\_pics.ob\_no where ob\_no is user id and et\_thanks\_2014 where thnk.e\_to is a link to et\_pics.ob\_no.
I need to find out ob\_no in et\_pics who absent in e\_to in et\_thanks\_2014.
```
SELECT pics.ob_no, thnk.e_to FROM et_pics pics
left... | You need correlation. For instance:
```
SELECT ob_no
from et_pics
WHERE not exists (SELECT 1 FROM et_thanks_2014 thnk WHERE thnk.e_to = pics.ob_no);
```
Without correlation, your subquery (presumably) always returns at least one row, assuming the table is not empty. Hence, `not exists` always returns false.
The equi... | I believe you should be using `NOT IN` rather like below since you are trying to get the uncommon values
```
SELECT pics.ob_no FROM et_pics pics
WHERE pics.ob_no NOT IN (SELECT e_to FROM et_thanks_2014);
```
Moreover, I am not sure why you think that your `LEFT JOIN` solution is not the best solution.
```
SELECT p... | Not in and Exists not working as i expect | [
"",
"sql",
"sql-server-2005",
""
] |
I need to trim leading zeros in a column using MS Access SQL.
I've found the topic
[Better techniques for trimming leading zeros in SQL Server?](https://stackoverflow.com/questions/662383/better-techniques-for-trimming-leading-zeros-in-sql-server)
but
```
SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col... | Check that the zeros really exist, they may if the field is text, in which case you can use:
```
Val(NameOfField)
```
Result
```
Field1 ValField1
ab 0
0000123 123
```
If the field is numeric, you probably have a format added to the table, which is a very bad idea. | If all of the records in the varchar column are numeric, then you can simply multiply the string by 1.
Be wary though. Sooner or later something non-numeric will sneak in and break things by causing an invalid cast. If possible, convert the column to an integer type and leave the formatting up to the client. | Trimming leading zeros in MS Access SQL | [
"",
"sql",
"ms-access",
""
] |
I have a table contains the following Data
```
id student class
1 English 3-B
2 null null
3 null null
4 Jack OuMe
5 Richard DSA
6 Jhon Ross
7 French 5-B
8 null null
9... | I fixed the problem I improved the response answered by Gordon Linoff
```
SELECT ID, STUDENT, CLASS,
NVL(CASE WHEN CLASS LIKE '%-%' THEN CLASS END, LAG(CASE WHEN CLASS LIKE '%-%' THEN CLASS END) IGNORE NULLS OVER
(ORDER BY ID)) as CLASSSTUD
FROM MYTABLE
ORDER BY ID;
``` | There appears to be a serious flaw in your database design. You need two tables to make this work properly. You are mixing two different categories of data in the same column which is why you are having an issue. You have classes and students in the same column.
Create a separate table for classes and one for students... | Get a value of a row in a column | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have the data in the following format:
```
Tran No Date Store ID Register ID Tender
01 23-10-2015 1000 001 CASH
01 23-10-2015 1000 001 CRDT
02 23-10-2015 1000 001 CASH
02 23-10-2015 1000 001 GIFT
```
A new co... | You could use **ROW\_NUMBER()** analytic function:
For example,
**Setup**
```
CREATE TABLE t
(tran_no NUMBER,
"DATE" VARCHAR2(10),
store_id NUMBER,
Register_ID NUMBER,
Tender varchar2(4));
INSERT ALL
INTO t (tran_no, "DATE", store_id, Register_ID, Tender)
VALUES (01, '23-10-2... | You can use row\_number with partition by clause
```
select tran_no,date,store_id,register_id,tender, row_number() over(partition
by tran_no,date,store_id,register_id order by tran_no)-1 tran_seq
from table_name
``` | Column Update Oracle SQL | [
"",
"sql",
"oracle",
""
] |
I have a table [see the Fiddle](http://sqlfiddle.com/#!6/a63c3/1). It contains details of user's size on 3 different visits. My question is how can I select the minimum size between the three size columns for each user and the respective date from the 3 dates column of the minimum size? I can get minimum size from the ... | Try like this.
```
CREATE TABLE test
(
username VARCHAR(50),
visit1 DATETIME,
visit2 DATETIME,
visit3 DATETIME,
size1 INT,
size2 INT,
size3 INT
);
INSERT INTO test
VALUES ( 'ABC',
'2014-01-01',
'2014-02-01',
'2014-03-01',
... | You can unpivot your 3 visits into 3 rows using a [table value constructor](https://msdn.microsoft.com/en-GB/library/dd776382.aspx), then select the top 1 in order of size:
```
SELECT t.username,
ms.Visit,
MinSize = ms.Size
FROM Test AS t
CROSS APPLY
( SELECT TOP 1 m.visit, m.siz... | How can I select two columns data on one condition in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I would like to filter my table by `MIN()` function but still keep columns which cant be grouped.
I have table:
```
+----+----------+----------------------+
| ID | distance | geom |
+----+----------+----------------------+
| 1 | 2 | DSDGSAsd23423DSFF |
| 2 | 11.2 | SXSADVERG678BNDVS4 ... | You need a window function to do this:
```
SELECT "ID", distance, geom
FROM (
SELECT "ID", distance, geom, rank() OVER (PARTITION BY "ID" ORDER BY distance) AS rnk
FROM somefile) sub
WHERE rnk = 1;
```
This effectively orders the entire set of rows first by the `"ID"` value, then by the distance and returns the r... | One common approach to this is to find the minimum values in a derived table that you join with:
```
SELECT somefile."ID", somefile.distance, somefile.geom
FROM somefile
JOIN (
SELECT "ID", MIN(distance) AS distance FROM somefile GROUP BY "ID"
) t ON t.distance = somefile.distance AND t.ID = somefile.ID;
```
[... | Filtering using aggregation functions | [
"",
"sql",
"postgresql",
"postgis",
""
] |
Example:
```
select c_id,'VIP Customer' [Customer Level] from customer where ...
```
union
```
select c_id,'Regular Customer' [Customer Level] from customer where ...
```
if `c_id` is part of first level (VIP) can't be 2nd level(Regular). I am using Union it's not working because second column data is different.
C... | this is the error Client query.
```
select A.RC_id
from (
select c_id RC_id
from customer
where 'Regular Customer' criteria) A
inner join (
select c_id VIP_id
from customer
where 'VIP Customer' criteria) B
on A.RC_id=B.VIP_id
```
or you can apply both criteria on the Client, i thin... | CASE seems to be a nice solution here, you can add more Customer Levels if needed also.
```
select c_id, [Customer Level] =
CASE
WHEN ... THEN 'VIP Customer'
ELSE 'Regular Customer'
END
from customer
```
More about CASE on MSDN: <https://msdn.microsoft.com/en-us/library/ms181765.aspx> | Compare query result on the basis of single column | [
"",
"mysql",
"sql",
""
] |
Every thread I've seen so far has been to check for duplicate rows and avoiding them. I'm trying to get a query to only return the duplicate rows. I thought it would be as simple as a subquery, but I was wrong. Then I tried the following:
```
SELECT * FROM a
WHERE EXISTS
(
SELECT * FROM b
WHERE b.id = a.id
... | I am sure your posted code would work too like
```
SELECT * FROM a
WHERE EXISTS
(
SELECT 1 FROM b WHERE id = a.id
)
```
You can as well do a `INNER JOIN` like
```
SELECT a.* FROM a
JOIN b on a.id = b.id;
```
You can as well use a `IN` operator saying
```
SELECT * FROM a where id in (select id from b);
```
I... | use this query, maybe is better if you check the relevant column.
```
SELECT * FROM a
INTERSECT
SELECT * FROM b
``` | Returning only duplicate rows from two tables | [
"",
"sql",
"sql-server",
""
] |
I have a query where I need to search the numerical part of a string in SQL Server.
[](https://i.stack.imgur.com/X74TV.png)
In the number column above needs to be searchable as a variable in the query.
Wildcards does not work:
```
SELECT PK_Story
... | What about `LIKE '%-' + @numberParam`? | You can use `substring` and `charindex` combination to get the result.
```
SELECT PK_Story
FROM Story
WHERE ProductId = @productParam
AND @numberParam like
'%' + case when charindex('-', Number) > 0
then substring(Number, charindex('-', Number) +1, len(Number)) + '%'
else Number
end + '%'
`... | WHERE clause based on part of a VARCHAR column | [
"",
"sql",
"sql-server",
""
] |
**[UPDATED]: I have updated the question with the `WHERE` clause.**
I have the following SQL Fiddle. The result is:
```
| User | Name | Time |
|--------|---------------|--------|
| 00001 | Mary Jane | 12 |
| 00002 | Joana Smith | 7 |
| 00003 | George Andrz | 2 |
| 00004 | Julia R... | try this:
```
SELECT
u.UserID AS 'User',
u.FullName AS Name,
isnull(SUM(Minutes) / 60,0) AS [Time]
FROM
MainUsers u left OUTER JOIN
TimeSheet t ON
u.UserID = t.UserID
GROUP BY
u.UserID,
u.FullName
ORDER BY
u.UserID
```
[SQL Fiddle](http://sqlfiddle.com/#!3/8cfee/15)
if you want... | I think you want a `left join`. Presumably, everyone with a timesheet is a valid user. And you seem to want to keep all the users.
In general, when you use `full outer join` you have to be very careful about `NULL` values. `COALESCE()` ends up being used extensively. So, your query can be written as:
```
SELECT u.Use... | Full Outer Join with Group By | [
"",
"sql",
"sql-server-2008-r2",
"group-by",
""
] |
Can you please advise on this?
```
CREATE TABLE TEST2 (
JOB_NAME VARCHAR2(50) NULL,
RUNTIME NUMBER(22) NULL,
STARTTIME1 VARCHAR2(50) NULL,
ENDTIME1 VARCHAR2(50) NULL,
STARTTIME_READ DATE NULL,
ENDTIME_READ DATE NULL
)
GO
insert into TEST2 values ('TEST JOB',37,'08/18/2015 20:12:24','08/18/2015 20:13:01',null... | Try this. You had several problems. Format mask for to\_number should be '99999' not 'SSSSS' and result of avg function was not a whole number, so to\_date was not working. Rounded the value.
```
SELECT job_name,
TO_CHAR(to_date(ROUND(AVG(to_number(TO_CHAR(to_date(starttime1,'mm/dd/yyyy hh24:mi:ss'),
'SSSSS'... | I think this is what you are looking for
```
select job_name,to_char(
to_date(
TRUNC(avg(
to_number(
to_char(
to_date(starttime1,'mm/dd/yyyy hh24:mi:ss'),
'SSSSS')
)
)),'SSSSS'),'HH24:MI:SS')AVG_STARTIME
from TEST2 group by job_name
```
That average is returning numb... | ORA-01830: date format picture ends before converting entire input string | [
"",
"sql",
"oracle",
"oracle8i",
""
] |
I'd like to query the database as to whether or not one or more rows exist that satisfy a given predicate. However, I am not interested in the distinction between there being one such row, two rows or a million - just if there are 'zero' or 'one or more'. And I do not want Postgres to waste time producing an exact coun... | PostgreSQL doesn't have a dummy table because you don't need one.
```
SELECT 1 WHERE EXISTS
(SELECT 1 FROM REAL_TABLE WHERE COLUMN = 'VALUE')
```
Alternatively if you want a true/false answer:
```
SELECT EXISTS(SELECT 1 FROM REAL_TABLE WHERE COLUMN = 'VALUE')
``` | How about just doing this?
```
SELECT (CASE WHEN EXISTS (SELECT 1 FROM REAL_TABLE WHERE COLUMN = 'VALUE') THEN 1 ELSE 0 END)
```
`1` means there is a value. `0` means no value.
This will always return one row. | Efficiently determine if any rows satisfy a predicate in Postgres | [
"",
"sql",
"postgresql",
"exists",
""
] |
I'm Using Oracle where,
I have a Table(`FE_IMPORT_LC` Table) with data from where i give in following few column with data
```
TRANSMIT_LC_NO LIAB_AMT_LCY REM_LC_AMT_LCY IMP_AMEND_NO
108615020048 10022000 10022112 00
108615020048 10022000 10022112 01
108615020048 10022... | Try;
```
select liab_amt_lcy
from (
SELECT l1.liab_amt_lcy, imp_amend_no
FROM fe_import_lc l1
WHERE l1.transmit_lc_no = '108615020048'
order by imp_amend_no desc
)
where rownum < 2
``` | Try something like below, where l1 would be your FE\_IMPORT\_LC table. Better to create a view with the logic of l2 table given below and then select.
```
with l1(TRANSMIT_LC_NO, LIAB_AMT_LCY, REM_LC_AMT_LCY, IMP_AMEND_NO) as(
select 108615020048,10022000,10022112,00 from dual union
... | In oracle How can I Find out one/two Columns data which corresponding other columns have maximum value | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
I have a table `test` with the following columns: `id`, `startDate`, `stopDate`, `startOvertime`, `stopOvertime`.
`startDate` and `stopDate` are of type datetime and `startOvertime`, `stopOvertime` are of type `time(7)`.
I want to create a new column with the date portion from `stopDate` and the time portion from `st... | If you always want the new column with this information, then you can use a computed column:
```
alter table test add test-fill as
(cast(cast(startDate as date) as datetime) + cast(overtime as datetime));
```
This doesn't actually add a new column. It just computes the values when you need them. | This should do it:
```
alter table [table-name] add [test-fill] datetime
update [table-name]
set [test-fill] = cast(startDate as date) + cast(stopOvertime as datetime)
```
First we add column to the table, then we update created cells with data. | T-SQL Add new column in existing table and fill with value from two another existing column | [
"",
"sql",
"sql-server",
""
] |
If i have Vacation table with the following structure :
```
emp_num start_date end_date
234 8-2-2015 8-5-2015
234 6-28-2015 7-1-2015
234 8-29-2015 9-2-2015
115 6-7-2015 6-7-2015
115 8-7-2015 8-10-2015
```
considering date format is: `m/dd/yyyy`
How could i get the summation of... | This will work for sqlserver 2012+
```
DECLARE @t table
(emp_num int, start_date date, end_date date)
INSERT @t values
( 234, '8-2-2015' , '8-5-2015'),
( 234, '6-28-2015', '7-1-2015'),
( 234, '8-29-2015', '9-2-2015'),
( 115, '6-7-2015' , '6-7-2015'),
( 115, '8-7-2015' , '8-10-2015')
DECLARE @date date = '2015-08-01'... | i hope this will help you
```
declare @temp table
(emp_num int, startdate date, enddate date)
insert into @temp values (234,'8-2-2015','8-5-2015')
insert into @temp values (234,'6-28-2015','7-1-2015')
insert into @temp values (234,'8-29-2015','9-2-2015')
insert into @temp values (115,'6-7-2015','6-7-2015')
inse... | How to get the summation of days in specific month of year in range | [
"",
"sql",
"sql-server",
"date",
"informix",
""
] |
I have procedure like:
```
create or replace procedure smth
is
some_variable varchar(2;
begin
insert into **table**(col1,col2) (Select id,'text' from TABLE2),
insert into table(col1,col2) (Select id,'text' from TABLE3)
```
What I want to do is put some if-else (or smoething else) statement for the case when eg. Tabl... | In order to get waht you want you need two things
1. Find if the table exists: you can query the `user_tables` against the
`table_name` column if the procedure is reading form the table in the
same schema
2. you need to use dynamic sql because if the table does not exists
with static pl/sql you get the error ... | You could query the **USER\_TABLES** view to see whether the table actually exists or not. And, you must (ab)use **EXECUTE IMMEDIATE** to execute the dynamic sql.
For example,
```
SELECT COUNT(*)
INTO v_cnt
FROM USER_TABLES
WHERE TABLE_NAME = '<TABLE_1>';
v_sql := INSERT INTO TABLE(col1,col2).. SELECT id,'te... | If table doesn't exists then insert into other table | [
"",
"sql",
"oracle",
"plsql",
""
] |
I am trying to update a column with a value of a different column under certain circumstances. It's complicated. I've tried to figure this out on my own for a weeks now. (on and off)
Here is how it currently looks:
[](https://i.stack.imgur.com/BpIDf.p... | You can use a join in your update statement to make this easier.
```
update t
set CastLotNo = t2.LotNo
from yourTable t
inner join yourTable t2 on t2.CastTID = t.CastTID and t2.OperationCode = 1280
``` | ```
UPDATE `myTable` SET `CastLotNo` = (SELECT `LotNo` FROM `MyTable` WHERE `OperationCode` = '1280' LIMIT 1) WHERE `CastTID` = (SELECT `CastTID` FROM `MyTable` WHERE `OperationCode` = '1280' LIMIT 1)
```
It seems like you could use something like that. I can't test this at the moment, so let me know if it needs tweak... | UPDATE SQL column based on values of another column. (It's not that simple) | [
"",
"sql",
"sql-server",
""
] |
I have a stored procedure which takes in five parameters of which two can be null - we will call these parameters A and B
What I would like to do is select records based on the following logic.
If Parameter A is NULL then only return records that match Parameter B
I know that I can do something similar to the follow... | Functionally, something like this should work. If either parameter is `NULL`, the condition becomes a self-identity (assuming neither `groupID` nor `deliveryID` is NULL).
```
SELECT *
FROM table_name
WHERE groupID = coalesce(@groupIDParameter, groupID)
AND deliveryID = coalesce(@deliveryIDParameter, deliveryI... | Try
```
SELECT * FROM my_table WHERE Param = COALESCE(A,B)
```
`COALESCE` will give you `A` if it's not null. Otherwise `B`. | SQL - Retrieve records based on parameters where either parameter can be null | [
"",
"sql",
"sql-server",
"stored-procedures",
"where-clause",
""
] |
I am trying to show my `int` variables in raiserror `@MaxAmount` and `@MinAmount`
```
Raiserror('Total Amount should be less than %s and Greater than %s',16,1,@MaxAmount,@MinAmount)
```
But Im getting error:
> Must declare the scalar variable "@MaxAmount". | `%s` is used for `varchar` and your variable is of type `int` hence you need to try to use correct format specifier ie, `%d`
```
DECLARE @MaxAmount int = 16;
DECLARE @minAmount int = 1;
Raiserror('Total Amount should be less than %d and Greater than %d',@MaxAmount,@MinAmount)
```
Check [RAISEERROR](https://msdn.micro... | You need to use %I for integers and as mentioned, declare the variables before use.
```
declare @MaxAmount int, @MinAmount int
select @MaxAmount = 50, @MinAmount = 5
Raiserror('Total Amount should be less than %i and Greater than %i',16,1,@MaxAmount,@MinAmount)
``` | How to use variables in SQL raiserror | [
"",
"sql",
"sql-server",
"raiserror",
""
] |
I am trying to use a subquery / join to compare a set of rows in a table to other rows in the same table.
Excerpt data set:
```
Guid MonitorsetID groupName
26464009405210800000000000 2162 ~templates.root
26464009405210800000000000 2161 ~templates.root
2646400940521080... | This query will extract missing ids for both guids 129478194721498 and 500311571061532.
```
with createddata as (
select *
from
(
select distinct guid, groupname from vMonitorsetAgentAssignment
where guid <> '26464009405210800000000000'
) a
cross join
(
select monitorsetid from vMonitorsetA... | Get all possible combinations of the GUIDs in the groupName you are filtering over along with the MonitorsetID's of the GUID you are filtering on (by cross-joining from the base table to a distinct set of MonitorsetIDs for the GUID you are filtering on).
Once you have that data-set, it becomes a simple left-join from ... | SQL subquery / join | [
"",
"sql",
"sql-server",
""
] |
I want to use a `FULL OUTER JOIN` between two tables on several columns, but when both columns are null, they are not considered as equal during the join, so I obtain two different rows. How can I write my join, so null columns are considered as equal ?
I have set up a simplified example :
```
create table t1 (
id n... | Use [NVL()](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions105.htm) and a Unique String to substitute NULL:
```
select t1.id,t1.field1,t1.field2,t2.extra_field
from t1
full outer join t2 ON
t1.id=t2.id
AND NVL(t1.field1,'UID_INSTEAD_OF_NULL')=NVL(t2.field1,'UID_INSTEAD_OF_NULL')
AND NVL(t1.field2,'UID... | NVL can be applied on the result so no function is needed in the join condition
```
select
nvl(t1.id, t2.id) id,
nvl(t1.field1, t2.field1) field1,
nvl(t1.field2, t2.field2) field2,
extra_field
from t1
full outer join t2 on t1.id = t2.id AND t1.field1 = t2.field1 AND (t1.field2 = t2.field2 OR (t1.field2... | SQL : FULL OUTER JOIN on null columns | [
"",
"sql",
"oracle",
"join",
"outer-join",
""
] |
I need to insert data in my table variable to a temp table but it gives me the following error.
> Msg 208, Level 16, State 0, Procedure sp\_CreateScenario\_q2, Line 70
> Invalid object name '#tmpp1'.
Here is the code
```
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
INSERT INTO #tmpp1
SELECT... | Error 'Invalid object name '#tmpp1' occurs because you delete temp table and then try to insert in it.
Try to use:
```
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
... | you are dropping table. Either create one with `CREATE` or use `select * into` instead of `insert into`
```
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
... | SQL Server Insert Into Temp table from a table variable | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.