Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need to check whether `mytable` table is containing `mycolumn` column? Here is my query:
```
SELECT CASE WHEN EXISTS (SHOW COLUMNS FROM mytable LIKE mycolumn) THEN 1 ELSE 0 END;
```
But it doesn't work and throws this error-message:
> **#1064** - You have an error in your SQL syntax; check the manual that correspo... | You can use the following as an if
```
IF EXISTS(
select * from
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='SOMETABLE' AND
COLUMN_NAME = 'SOMECOLUMN')
)
BEGIN
-- do stuff
END
GO
```
Alternatively as a case
```
SELECT CASE WHEN EXISTS(
select * from
INFORMATION_SCHEMA.COLUMNS
W... | Try this instead
```
SELECT CASE WHEN EXISTS (
SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name')
then 1
else 0
end;
``` | How do I check whether column exists in the table? | [
"",
"mysql",
"sql",
""
] |
I am new to SQL and I'm having difficulties writing the following query.
**Scenario**
A user has two addresses, home address (`App\User`) and listing address (`App\Listing`). When a visitor searches for listings for a Suburb or postcode or state, if the user's listing address does not match - but if home address does... | Try this. You can check it [here](http://sqlfiddle.com/#!9/54a0376/6).
```
SELECT l.*
FROM listings l
LEFT JOIN addresses a_l ON a_l.addressable_id = l.id
AND a_l.addressable_type = "App\\Listing"
AND a_l.suburb = "Melbourne"
LEFT JOIN addresses a_u ON a_u.addressable_id = l.user_id
AND a_u.addressable_type = "A... | As per my understanding of your question, for any suburb - supplied by a visitor, you want to include all the listings where either User's address is the same as the suburb supplied or the Listing's address is the same as the suburb supplied.
Assuming addressable\_id column is related to Id of Users table and Listings... | Select locations from two tables | [
"",
"mysql",
"sql",
""
] |
I have a relatively large table (currently 3 million records). Which has columns:
```
[id] INT IDENTITY(1,1) NOT NULL,
[runId] INT NOT NULL,
[request] VARCHAR(MAX) NULL,
[response] VARCHAR(MAX) NULL
```
And an Index as : `CONSTRAINT [Id_Indexed] PRIMARY KEY CLUSTERED`
I have view on this table.
when I do query as:
... | As people already mentioned use add an index to the column run id.
Depending on how the table is used, you can think about using "with (nolock)"-hint. In some cases it can improve the performance a lot. Read here for further information:
<https://www.mssqltips.com/sqlservertip/2470/understanding-the-sql-server-nolock... | ok,
```
CREATE NONCLUSTERED INDEX [IX_Table_RunId] ON [Table]([RunId]);
```
and run the queries again. | How to improve performance of relatively large table | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
Is there a relationship between the `JOIN` clauses used in in a `SELECT` statement and how the two tables are related to one another, i.e. one to many, many to one, one to one? If not, can/should those type of table relationships be defined in SQL code? | Defining these relationships is done by using Foreign Keys. These keys ensure referential integrity, by enforcing constraints on either side.
Example:
`table-one: id, name
table-many: id, name, table-one_id`
Here, `table-one_id` is a foreign key (referencing the id of table-one), ensuring you can only enter valid id... | There are a couple of questions here:
> Is there a relationship between the JOIN clauses used in in a SELECT statement and how the two tables are related to one another?
In the vast majority of cases, yes, a `JOIN` clause will illustrate one of the ways two tables are related to each other. But this is not always the... | Are JOINs and one to many type relationships related? | [
"",
"sql",
""
] |
If I have the table
[](https://i.stack.imgur.com/nwx03.png)
```
SELECT (Firstname || '-' || Middlename || '-' || Surname) AS example_column
FROM example_table
```
This will display Firstname-Middlename-Surname e.g.
```
John--Smith
Jane-Anne-Smith
... | Here would be my suggestions:
PostgreSQL and other SQL databases where `'a' || NULL IS NULL`, then use [COALESCE](https://www.postgresql.org/docs/current/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL):
```
SELECT firstname || COALESCE('-' || middlename, '') || '-' || surname ...
```
Oracle and other SQL d... | If you use Postgres, `concat_ws()` is what you are looking for:
```
SELECT concat_ws('-', Firstname, Middlename, Surname) AS example_column
FROM example_table
```
SQLFiddle: <http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8812>
To treat empty strings or strings that only contain spaces like `NULL` use `... | SQL using If Not Null on a Concatenation | [
"",
"sql",
"null",
"concatenation",
""
] |
I have the following two tables T1 and T2.
Table T1
```
Id Value1
1 2
2 1
3 2
```
Table T2
```
Id Value2
1 3
2 1
4 1
```
I need a SQL SERVER query to return the following
```
Id Value1 Value2
1 2 3
2 1 1
3 2 0
4 0 1
```
Thanks in advance!! | You can achieve this by **FULL OUTER JOIN** with **ISNULL**
Execution with given sample data:
```
DECLARE @Table1 TABLE (Id INT, Value1 INT)
INSERT INTO @Table1 VALUES (1, 2), (2, 1), (3, 2)
DECLARE @Table2 TABLE (Id INT, Value2 INT)
INSERT INTO @Table2 VALUES (1, 3), (2, 1), (4, 1)
SELECT ISNULL(T1.Id, T2.Id) AS I... | FYI - `Merge` means something different in SQL Server.
I would suggest if you have a table which contains a list of all possible Id values, I would select everything from that and have two left outer joins to T1 and T2.
Assuming there isn't one, with only what is provided, it sounds like you want a full outer join.
... | How to merge two tables in SQL SERVER? | [
"",
"sql",
"sql-server",
""
] |
[SQL FIDDLE DEMO HERE](http://sqlfiddle.com/#!6/2a7c5/1)
I have this table structure for SheduleWorkers table:
```
CREATE TABLE SheduleWorkers
(
[Name] varchar(250),
[IdWorker] varchar(250),
[IdDepartment] int,
[IdDay] int,
[Day] varchar(250)
);
INSERT IN... | You can use pivot for this. Please use below query for your problem. And use Partition.
```
SELECT [Monday] , [Tuesday] , [Wednesday] , [Thursday] , [Friday], [SATURDAY]
FROM
(SELECT [Day],[Name],RANK() OVER (PARTITION BY [Day] ORDER BY [Day],[Name]) as rnk
FROM SheduleWorkers) p
PIVOT(
Min([Name])
FOR [Day] IN
( ... | ```
DECLARE @SheduleWorkers TABLE
(
[Name] VARCHAR(250) ,
[IdWorker] VARCHAR(250) ,
[IdDepartment] INT ,
[IdDay] INT ,
[Day] VARCHAR(250)
);
INSERT INTO @SheduleWorkers
( [Name], [IdWorker], [IdDepartment], [IdDay], [Day] )
VALUES ( 'Sam', '001', 5, 1, 'Monday' ),
... | How can I display rows values in columns sql server? | [
"",
"sql",
"sql-server",
"group-by",
"union-all",
"weekday",
""
] |
I'm supposed to write a query for this statement:
> List the names of customers, and album titles, for cases where the customer has bought the entire album (i.e. all tracks in the album)
I know that I should use division.
Here is my answer but I get some weird syntax errors that I can't resolve.
```
SELECT
R1... | You cannot alias a table list such as `(Album Al, Track T)` which is an out-dated syntax for `(Album Al CROSS JOIN Track T)`. You can either alias a table, e.g. `Album Al` or a subquery, e.g. `(SELECT * FROM Album CROSS JOIN Track) AS R2`.
So first of all you should get your joins straight. I don't assume that you are... | Seems you are using count in the wrong place
use having for aggregate function
```
SELECT R3.Title
FROM (Album Al, Track T) AS R3
HAVING COUNT(R1.TrackId)=COUNT(R3.TrackId))
```
but be sure of alias because in some database the alias in not available in subquery .. | relational division | [
"",
"mysql",
"sql",
"sql-server",
"sqlite",
"relational-division",
""
] |
I've been tasked to develop a query that behaves essentially like the following one:
```
SELECT * FROM tblTestData WHERE *.TestConditions LIKE '*textToSearch*'
```
The *textToSearch* is a string which contains information about the condition in which a given device is tested (Voltage, Current, Frequency, etc) in the ... | One choice is to look for *any* character between the "V" and the "127":
```
WHERE TestConditions LIKE '%V_127%'
```
Note that `%` is the wildcard for a string of any length and `_` is the wildcard for a single character.
You can also use regular expressions:
```
WHERE regexp_like(TestConditions, 'V[.:]127')
```
N... | You could check for both cases (although this will decrease performance)
```
SELECT *
FROM tblTestData
WHERE (TestConditions LIKE '%V:127%' OR TestConditions LIKE '%V.127%')
```
It is better to clean the data in your database if only old records have this problem. | SQL Like condition fails to run | [
"",
"sql",
"oracle",
""
] |
How can I list the names of all countries whose surface Area is greater than that of all other countries in the same region from the country Table below:
```
+----------------------------------------------+---------------------------+-------------+
| name | region ... | Could be you can use an inner join whit a temp table
```
select name from
country as a
inner join
( select region, max(surfacearea) as maxarea
from country
group by region ) as t on a.region = t.region
where a.surfacearea = t.maxarea;
``` | It looks like the query you have identifies the "largest" value of surfacearea for each region. To get the country, you can join the result from your query back to the country table again, to get the country that matches on region and surfacearea.
```
SELECT c.*
FROM ( -- largest surfacearea for each region
... | Listing based on a particular SQL Group | [
"",
"mysql",
"sql",
""
] |
I have a query (`SQL Server`) that returns a decimal. I only need 2 decimals without rounding:
[](https://i.stack.imgur.com/TEdzA.png)
In the example above I would need to get: **3381.57**
Any clue? | You could accomplish this via the [`ROUND()`](https://msdn.microsoft.com/en-us/library/ms175003.aspx?) function using the length and precision parameters to truncate your value instead of actually rounding it :
```
SELECT ROUND(3381.5786, 2, 1)
```
The second parameter of `2` indicates that the value will be rounded ... | Another possibility is to use `TRUNCATE`:
```
SELECT 3381.5786, {fn TRUNCATE(3381.5786,2)};
```
`LiveDemo` | SQL get decimal with only 2 places with no round | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've been leveraging information gleaned from other thread and what not and have gotten really close but am missing something here to do what I need to do. Here is my code that as I have it up right now in a SQL query window:
```
WITH n AS (
SELECT sub_idx AS current_id,
ROW_NUMBER() OVER (PARTITION BY EID OR... | ```
DECLARE @GETT_DOCUMENTS TABLE
(DID INT, EID VARCHAR(1), SUB_IDX INT, ALT_SUB_IDX INT)
INSERT INTO @GETT_DOCUMENTS
VALUES
(1,'A',0,10),
(2,'A',0,20),
(3,'A',0,30),
(4,'A',0,40),
(5,'A',0,50),
(6,'A',0,60),
(7,'A',0,70),
(8,'A',0,80),
(9,'A',0,90),
(10,'A',0,100),
(11,'A',0,110),
(12,'A',0,120)
;WITH n AS
(
... | Your UPDATE isn't correlated, so it is just grabbing the first row from the cte everytime. It needs to be like this:
```
...
UPDATE d
SET sub_idx = n.new_id
FROM n
INNER JOIN GETT_Documents d
ON d.sub_idx=n.sub_idx
WHERE d.EID = 'AC-1.1.i';
``` | ROW_NUMBER() OVER with sub set | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query with multiple joins for which `DOC_TYPE` column is coming NULL even if it has some values in it. The query is below
```
SELECT
a.mkey,
c.type_desc DOC_TYPE,
a.doc_no INWARD_NO,
CONVERT(VARCHAR, a.doc_date, 103) date,
a.to_user,
a.No_of_pages,
Ref_No,
c.type_desc DEPT_REC... | Following the discussion current version is
```
SELECT
a.mkey, c.type_desc DOC_TYPE, a.doc_no INWARD_NO,
convert(varchar, a.doc_date,103) date, a.to_user, a.No_of_pages, Ref_No, d.type_desc DEPT_RECEIVED,
b.first_name + ' ' + b.last_name SENDER, b.first_name + ' ' + b.last_name NAME, b.email
FROM inward_doc... | **Instead of Left join you have to use inner join in order to get records having doc\_type. This query will help you :**
```
SELECT a.mkey,
c.type_desc DOC_TYPE,
a.doc_no INWARD_NO,
CONVERT(VARCHAR, a.doc_date, 103)date,
a.to_user,
a.No_of... | SQL query not returning correct result | [
"",
"sql",
"sql-server-2005",
""
] |
I know of a couple of different ways to find all primary keys in the db, but is it possible to filter the results, so that it only show primary keys that have system generated names? None of the attributes returned by these queries seem relevant, so I am guessing I'll have to join another table or call a function, but ... | The cleanest way would be this:
```
SELECT *
FROM sys.key_constraints
WHERE type = 'PK'
AND is_system_named = 1
```
Just check the `is_system_named` property in the `sys.key_constraints` view | ***An auto-generated PK seems to contain 16 hexadecimal digits in its name***.
So I would use this query and then still manually check the results from it. Why check them manually? Because maybe the above statement may be just something undocumented, and may not apply in future versions of SQL Server.
```
SELECT *
... | Is it possible to find all primary keys that have system generated names in a database? | [
"",
"sql",
"sql-server",
""
] |
I have rather simple question: is exception handling possible at the package level? And if yes, how to implement it?
My package has procedures and functions in it, and in case of, let's say, a `NO_DATA_FOUND` exception I want to do the same thing in all of my procedures and functions.
So my question is: can I write
... | No, it's not possible. I expect that that's not in the language because it's not consistent with proper and intended use of exception handlers.
The general rule of thumb that I apply is: "if you don't have something specific and helpful to do in response to an exception, don't catch it".
If `NO_DATA_FOUND` is expecte... | No, you can't handle an exception globally across all procedure/functions in a package.
[The exception handler documentation](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/exception_handler.htm#LNPLS01316) says:
> An exception handler processes a raised exception. Exception handlers appear in the exception-ha... | PL/SQL Package level exception handling | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have following Spark sql and I want to pass variable to it. How to do that? I tried following way.
```
sqlContext.sql("SELECT count from mytable WHERE id=$id")
``` | You are almost there just missed `s` :)
```
sqlContext.sql(s"SELECT count from mytable WHERE id=$id")
``` | You can pass a string into sql statement like below
```
id = "1"
query = "SELECT count from mytable WHERE id='{}'".format(id)
sqlContext.sql(query)
``` | Spark SQL passing a variable | [
"",
"sql",
"select",
""
] |
I need to get all the `Room_IDs` where the `Status` are reported vacant, and then occupied at a later date, only.
This is a simplified table I am using as an example:
```
**Room_Id Status Inspection_Date**
1 vacant 5/15/2015
2 occupied 5/21/2015
2 vacant 1/19/2016
1 ... | Here's one option using `exists` with a `correlated subquery`:
```
select * from yourtable t
where exists (
select 1
from yourtable c
where c.room_id = t.room_id
group by c.room_id
having min(case when status = 'vacant' then inspection_date end) <
max(case when status = 'occupied' then inspection_d... | Try this
```
;WITH cte
AS (SELECT *,
Row_number()OVER(partition BY [room_id] ORDER BY [inspection_date])rn, FROM YOurtable)
SELECT room_id,
status,
[inspection_date]
FROM cte a
WHERE EXISTS (SELECT 1
FROM cte b
WHERE a.roo... | TSQL: conditional group by query | [
"",
"sql",
"sql-server",
"t-sql",
"group-by",
""
] |
I have a table structure like:
```
Table = contact
Name Emailaddress ID
Bill bill@abc.com 1
James james@abc.com 2
Gill gill@abc.com 3
Table = contactrole
ContactID Role
1 11
1 12
1 13
2 11
2 12
3 12
```
I want to select the Name an... | Use conditional aggregation in `Having` clause to filter the records
Try this
```
SELECT c.NAME,
c.emailaddress
FROM contact c
WHERE id IN (SELECT contactid
FROM contactrole
GROUP BY contactid
HAVING Count(CASE WHEN role = 12 THEN 1 END) > 1
... | You can use a combination of `EXISTS` and `NOT EXISTS`
```
SELECT *
FROM contact c
WHERE
EXISTS(SELECT 1 FROM contactrole cr WHERE cr.ContactID = c.ID AND cr.Role = 12)
AND NOT EXISTS(SELECT 1 FROM contactrole cr WHERE cr.ContactID = c.ID AND cr.Role IN(11, 13))
```
---
Another option is to use `GROUP BY` an... | Nested Oracle SQL - Multiple Values | [
"",
"sql",
"oracle",
"select",
"nested",
""
] |
I'm creating a database that has a `users` table, but there are three types of users (admin, teachers and students) and some types has its own properties. Here are my solutions:
1 - Three different tables:
```
table_admin
id
name
email
password
table_teachers
id
name
email
password
teacher_only... | Why not
```
table_users
id
name
email
password
is_admin
table_teachers
user_id
teacher_only_a
teacher_only_b
table_students
user_id
student_only_a
student_only_b
```
That would abstract out the user information so there isn't any redundancy. | I would opt for having two tables, one called `user` which will store user name, role, and other metadata, and a second table called `user_relation` which will store relationships between users.
**user**
```
id
name
email
password
role (admin, teacher, or student)
```
**user\_relation**
```
id1
id2
```
I am making... | Issues on designing SQL users table | [
"",
"mysql",
"sql",
""
] |
I wrote a script in oracle. But it does not give me the result that i want.
I need this one, imagine i have two table. Order\_table and book table.
My order table is like this
ORDER\_TABLE Table
```
ID TYPE_ID VALUE_ID
1 11 null
2 11 null
3 11 null
4 12 null
5 11 null
... | First, do not use implicit `JOIN` syntax(comma separated), that's one of the reason this mistakes are hard to catch! Use the proper `JOIN` syntax.
Second, your problem is that you need a `left join`, not an `inner join` , so try this:
```
Select *
From (Select coalesce(Newtable.Counter,0) As Value_id,
... | You could also do this with a scalar subquery, which may or may not be more performant than the left join versions described in the other answers. (Quite possibly, the optimizer may rewrite it to be a left join anyway!):
```
with order_table ( id, type_id, value_id ) as (select 1, 11, cast( null as int ) from dual uni... | Counting one field of table in other table | [
"",
"sql",
"oracle",
""
] |
I have a table `tab`, which contains columns `a,b,c,d`. But the following query will not work since the `c` is not in the group by clause or in a reduction function.
```
SELECT a, b, c FROM tab GROUP BY a, b;
```
But what i want is to select `c` based on maximum value of `d`. How can I do this query in PostgreSQL ?.
... | Classic `top-n-per-group`. One way to do it using `ROW_NUMBER`:
```
WITH
CTE
AS
(
SELECT
a, b, c
,ROW_NUMBER() OVER(PARTITION BY a, b ORDER by d DESC) AS rn
FROM tab
)
SELECT
a, b, c
FROM CTE
WHERE rn = 1;
```
Index on `(a, b, d, c)` should help.
Approach with `ROW_NUMBER` works well when... | In Postgres, you can use `distinct on`:
```
SELECT DISTINCT ON (a, b) a, b, c
FROM tab
ORDER BY a, b, d DESC;
```
This syntax is specific to Postgres. It is often the most efficient way to do this type of operation. | How to add aggregation function to non grouped column which is not in select | [
"",
"sql",
"postgresql",
"group-by",
"greatest-n-per-group",
""
] |
I would like to select some rows multiple-times, depending on the column's value.
**Source table**
```
Article | Count
===============
A | 1
B | 4
C | 2
```
**Wanted result**
```
Article
===============
A
B
B
B
B
C
C
```
Any hints or samples, please? | You could also use a recursive CTE which works with numbers > 10 (here up to 1000):
```
With NumberSequence( Number ) as
(
Select 0 as Number
union all
Select Number + 1
from NumberSequence
where Number BETWEEN 0 AND 1000
)
SELECT Article
FROM ArticleCounts
CROSS APPLY NumberSequence
WHERE ... | You could use:
```
SELECT m.Article
FROM mytable m
CROSS APPLY (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS s(n)
WHERE s.n <= m.[Count];
```
`LiveDemo`
Note: `CROSS APLLY` with any tally table. Here values up to 10.
Related: [What is the best way to create and populate a numbers table?](https://stackoverflo... | SQL multiplying rows in select | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Is it possible to use a WHERE statement to find the oldest or the newest date ?
I mean something like
```
SELECT *
FROM employees
WHERE birth_date = MIN(birth_date);
```
I know this doesn't work, but I am asking if there is a syntax error or the whole idea is wrong. | This is possible(`ANSI SQL`)
```
SELECT * FROM employees
WHERE birth_date = (select MIN(birth_date) from employees)
```
or You can use `TOP 1 with Ties`(`SQL SERVER`)
```
Select TOP 1 with TIES *
FROM employees
Order by birth_date ASC
``` | You can use a simple subselect for getting the value you need
```
SELECT * FROM employees WHERE birth_date = (select MIN(birth_date) from employess)
``` | how to select the oldest or newest date using where? | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a `stored procedure` which accepts one parameter as `@ReportDate`.
but when I execute it with parameter it gives me error as
> Error converting data type varchar to datetime.
Here is the SP.
```
ALTER PROCEDURE [dbo].[GET_EMP_REPORT]
@ReportDate Datetime
AS
BEGIN
DECLARE @Count INT
DECLARE @Count_closed I... | ```
EXEC GET_EMP_REPORT '20160516'
```
Pass date in generic format 'yyyyMMdd' | ```
DECLARE @ReportDate DATETIME
SET @ReportDate ='31/12/2016' -- DD/MM/YYYY Format you cant insert . It will give the below error
```
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
If you really need to insert the same in DD/MM/YYYY Format. Declare @ReportDate as Var... | Adding datetime as a parameter is giving Error converting data type varchar to datetime (Error) in stored procedure | [
"",
"sql",
"datetime",
"stored-procedures",
"sql-server-2005",
""
] |
My query is:
```
SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
LEFT JOIN Rate ON Pics.ID = Rate.PicID
WHERE Gender = 'female'
ORDER BY Pics.ID
```
And results are:
```
ID ProfileID Position R... | You should probably get rid of "magical numbers", like 32. That said, I think that this will give you what you need.
```
SELECT
P.ID,
P.ProfileID,
P.Position,
R.ID as RateID,
R.Rating,
R.ProfileID,
PR.Gender
FROM
Pics P
INNER JOIN Profiles PR ON PR.ID = P.ProfileID
LEFT JOIN Rate R ON R... | > @Shadow Because the 2nd row contains the Rate.ProfileID = 32, and that
> Pic.ID = 24, therefore it must remove ALL Pic.ID = 24, which removes
> the bottom row also.
```
SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileI... | SQL Help Inner JOIN LEFT JOIN | [
"",
"mysql",
"sql",
"join",
"left-join",
"inner-join",
""
] |
I have two tables t1 containg 3million records and t2 containing 11000 records. I execute the query
```
Select Count(*) FROM
t1 LEFT JOIN t2
ON t1.id = t2.id
```
I execute this query on a sql workbench, it returns 3million which is correct because it is a left join. But when I upload this data to Hive and run the s... | The data is not the same. I would suggest a "histogram of histogram" query to figure out what the issue is:
```
select cnt, count(*), min(id), max(id)
from (select id, count(t2.id) as cnt
from t1 left join
t2
on t1.id = t2.id
group by id
) t
group by cnt
order by cnt;
```
This w... | use hive
```
select count(*) from tb1
```
see data number is 3million
tb2 id one-to-many
hive insert date select? | Do joins in Hive behave differently? | [
"",
"sql",
"hadoop",
"join",
"hive",
"left-join",
""
] |
So with the case statement is there a way to get last entry which satisfies the When condition.
Consider this
```
Case when hireDate > getDate() THEN hireDate END;
ID HireDate
101 '07-28-2016'
101 '08-02-2016'
101 '08-04-2016'
```
Now with the above made up data, sql serv... | Here's one option using `conditional aggregation`:
```
alter view XYZ as
select id, max(case when hireDate > getDate() then hireDate end) maxdate
from abc
group by id
``` | > So with the case statement is there a way to get last entry which satisfies the When condition.
you can do some thing like ,getting max per group and querying against it.
```
;with cte
as
(
select id,max(date) as hiredate
from yourtable
group by id
)
select
id,
case when hiredate>getdate() then hiredate else nul... | ordered result with case when multiple enteries satisfies condition | [
"",
"sql",
"sql-server",
"sqlite",
"case",
""
] |
I am new to Postgresql, and I am trying to change the data type of a column from `Integer to Varchar(20)`, but I get strange error:
```
ERROR: operator does not exist: character varying <> integer :
No operator matches the given name and argument type(s).
You might need to add explicit type casts.******... | The cause of the error is the useless additional check constraint (`<> null`) that you have:
> operator does not exist: character varying <> integer :
refers to the condition `USERNAME != NULL` in both of your check constraints.
(the "not equals" operator in SQL is `<>` and `!=` gets re-written into that)
So you fi... | Use `USING expression`. It allows you to define value conversion:
```
ALTER TABLE LOGIN ALTER COLUMN USERNAME TYPE varchar(20) USING ...expression...;
```
From [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/sql-altertable.html):
> The optional USING clause specifies how to compute the new c... | Postgresql unable to change the data type of a column | [
"",
"sql",
"database",
"postgresql",
""
] |
I want to get records with duplicated values and their count from them as shown below.
I am trying following query but it shows wrong count. Please suggest me.
The query that I used:
```
SELECT msisdn, waiver_reason, COUNT(msisdn) AS cnt
FROM ECONSOLE_NEW
WHERE msisdn
IN
(
SELECT [CUSTOMER CELL NUMBER]... | There seems to be exactly 1 record for each `msisdn, waiver_reason` pair. You seem to want the count per `msisdn` and also, at the same time, return all `msisdn, waiver_reason` pairs.
If this is the case, then you can use window version of [**`COUNT`**](https://msdn.microsoft.com/en-us/library/ms175997.aspx) to get th... | `cnt` column is related to `msisdn` column.
Try following query:
```
SELECT msisdn,
waiver_reason,
(
SELECT SUM(cnt)
FROM ECONSOLE_NEW
WHERE msisdn = e.msisdn
) AS cnt
FROM ECONSOLE_NEW AS e
WHERE msisdn IN
(
SELECT [CUST... | Want records with count and duplicate values in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have list of datetime value. How to select previous year just for december only.
For example:
```
Current month = May 2016
Previous year of december = Dec 2015
(it will display data from dec 2015 to may 2016)
if Current month = May 2017
Previous year of december = Dec 2016 and so on.
(it will display data from dec... | ```
SELECT
*
FROM
TableName
WHERE
TableName.Date BETWEEN CONVERT(DATE,CONVERT(VARCHAR,DATEPART(YYYY,GETDATE())-1)+'-12-'+'01') AND GETDATE()
``` | Below query will give the required output :-
```
declare @val as date='2016-05-19'
select concat(datename(MM,DATEADD(yy, DATEDIFF(yy,0,@val), -1)),' ',datepart(YYYY,DATEADD(yy, DATEDIFF(yy,0,@val), -1)))
```
output : december 2015 | how to get previous year (month december) and month showing current month in sql | [
"",
"sql",
"sql-server",
""
] |
I have two tables.
```
tblEmployee tblExtraOrMissingInfo
id nvarchar(10) id nvarchar(10)
Name nvarchar(50) Name nvarchar(50)
PreferredName nvarchar(50)
UsePreferredName bit
```
The data (brief example)
```
tblEmploye... | It is slightly faster to use a left join and coalesce than to use the case statement (most servers are optimized for coalesce).
Like this:
```
SELECT E.ID, COALESCE(P.PreferredName,E.Name,'Unknown') as Name
FROM tblemployee E
LEFT JOIN tblExtraOrMissingInfo P ON E.ID = P.ID AND P.UsePreferredName = 1
```
> The `,... | `left join` on the employee table and use a `case` expression for name.
```
select e.id
,case when i.UsePreferredName = 1 then i.PreferredName else e.name end as name
from tblemployee e
left join tblExtraOrMissingInfo i on i.id=e.id
``` | select results from two tables but choose one field over another | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a request which returns something like this:
```
--------------------------
Tool | Week | Value
--------------------------
Test | 20 | 3
Sense | 20 | 2
Test | 19 | 2
```
And I want my input to look like this:
```
-------------------------
Tool | W20 | W19
-------------------------
Te... | Try this
```
CREATE table #tst (
Tool varchar(50), [Week] int, Value int
)
insert #tst
values
('Test', 20, 3),
('Sense', 20,2),
('Test', 19, 2)
```
Here is the Dynamic Query:
```
DECLARE @col nvarchar(max), @query NVARCHAR(MAX)
SELECT @col = STUFF((SELECT DISTINCT ',' + QUOTENAME('W' + CAST([Week] as VARCHAR))
... | ```
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
( Tool varchar(5), Week int, Value int)
;
INSERT INTO #temp
( Tool , Week , Value )
VALUES
('Test', 20, 3),
('Sense', 20, 2),
('Test', 19, 2)
;
DECLARE @stat... | How to pivot rows into colums dynamically SQL Server | [
"",
"sql",
"sql-server",
""
] |
Scenario: I have table with single column (string). I want to retrieve data which are stored in particular order.
table Tbl\_EmployeeName having only one column 'Name'
I inserted records through this below query
```
Insert Into Tbl_EmployeeName
select 'Z'
union
select 'y'
union
select 'x'
union
select 'w'
union
sel... | You can sort it in your own order with **FIND\_IN\_SET**
```
SELECT *
FROM Tbl_EmployeeName
ORDER BY FIND_IN_SET(Name,'Z,y,x,w,v,u,t,s');
```
If you dont know the insert order use this, then there is direct a AUTOINCREMENT field.
```
CREATE TABLE `Tbl_EmployeeName` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT... | > I inserted records through this below query
>
> `...query using union...`
>
> Now I want these records in the same order in which it is inserted.
Surprisingly, you *are* retrieving the records in the order in which they were inserted. Using `UNION` between each of the `SELECT` statements on your `INSERT` is causing ... | Sorting of string as per its insertion | [
"",
"mysql",
"sql",
"sql-server",
""
] |
Need some help structuring my query. I think I need a subquery, but I am not quite sure how to use them in my context. I have the following tables and data,
```
people
ID, Name
1, David
2, Victoria
3, Brooklyn
4, Tom
5, Katie
6, Suri
7, Kim
8, North
9, Kanye
10,James
11,Grace
relationship
peopleID, Relationship, rel... | Sorry I have no possibility to check a query right now. Does this work?
```
SELECT DISTINCT p.ID, p.name, f.ID, f.name, m.ID, m.name
FROM people AS p
LEFT JOIN relationship AS fr
ON p.ID = fr.peopleID
AND fr.relationship IN ('Father','Stepfather')
LEFT JOIN people AS f
ON fr.relatedID = f.ID
LEF... | Even though you've already accepted an answer, but I still want to provide the mine :
```
WITH familly AS
(
SELECT
child.ID AS childID
,child.Name AS childName
,Relationship AS relationship
,parent.ID AS parentID
,parent.Name AS parentName
FROM relationship
LEFT JOI... | Output from my query not quite right, possibly subquery for this? | [
"",
"sql",
""
] |
I have a accountNo column varchar(50)
sample data
```
000qw33356
034453534u
a56465470h
00000000a1
```
I need output like..
```
qw33356
34453534u
a56465470h
a1
```
I have limitation that i can not use while loop in side UDF as this is creating performance issue . | If your data doesn't contains spaces you can use:
```
select replace(ltrim(replace(data, '0', ' ')),' ', '0')
```
If there are spaces, you could replace them first to something else that doesn't exist and then replace back at the end. | Here's a somewhat cute variant that doesn't need a replacement character (although that's the one I'd usually use):
```
declare @t table (Val varchar(20))
insert into @t(Val) values
('000qw33356'),
('034453534u'),
('a56465470h'),
('00000000a1')
select SUBSTRING(Val,PATINDEX('%[^0]%',Val),9000)
from @t
```
Results:
... | remove leading zero from column with out any while loop in sql | [
"",
"sql",
"sql-server",
"database",
""
] |
Sample table below. I recently added the column 'is\_last\_child' and want to update it to have a value 1 if the row is the last child (or is not a parent). I had a query of
```
update node set is_last_child=1 where id not in (select parent_id from node);
```
I get the following error when I run it. "You can't specif... | You want `UPDATE FROM`:
```
UPDATE N1
SET N1.is_last_child = 1
FROM Node N1
LEFT OUTER JOIN Node N2
ON N1.ID = N2.Parent_ID
WHERE N2.ID IS NULL
```
The left outer join is conceptually the same as using `NOT IN` only it's easier to read and you don't need a bunch of nested queries. | While you can't update a table you are selecting from, I think you can update a table joined to itself:
```
UPDATE `node` AS n1 LEFT JOIN `node` AS n2 ON n1.id = n2.parent_id
SET n1.is_last_child = 1
WHERE n2.id IS NULL
;
``` | Update a column using a select subquery to the same table | [
"",
"mysql",
"sql",
"sql-update",
""
] |
I'm not really good when it comes to database...
I'm wondering if it is possible to get the weeks of a certain month and year..
For example: `1 (January)` = `month` and `2016` = `year`
Desired result will be:
```
week 1
week 2
week 3
week 4
week 5
```
This is what I have tried so far...
```
declare @date datetime... | ```
declare @MonthStart datetime
-- Find first day of current month
set @MonthStart = dateadd(mm,datediff(mm,0,getdate()),0)
select
Week,
WeekStart = dateadd(dd,(Week-1)*7,@MonthStart)
from
( -- Week numbers
select Week = 1 union all select 2 union all
select 3 union all select 4 union all select 5... | Here is one way to approach this:
A month has a minimum of 29 or more days, and a max of 31 or less. Meaning there are almost always 5 weeks a month, with the exception of a non-leap year's feburary, and in those cases, 4 weeks a month.
You can refer to this to find out which years are "leap".
[Check for leap year](h... | SQL Server : is there a way for me to get weeks per month using Month and Year? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to compare assembly versions using SQL Server, however there can be more than one version returned and I need it be in a six digit format.
For example, the assembly version `2.00.0001` and I need that to be returned as `2.0.1`.
There could be versions like `1.01.0031` that I would need to be `1.1.31`.
Thi... | Using `ParseName` function, you can achieve this. Try this -
```
DECLARE @val VARCHAR(100) = '01.10.0031'
SELECT CONVERT(VARCHAR, CONVERT(INT, PARSENAME(@val, 3))) + '.' +
CONVERT(VARCHAR, CONVERT(INT, PARSENAME(@val, 2))) + '.' +
CONVERT(VARCHAR, CONVERT(INT, PARSENAME(@val, 1)))
```
**Result**
```
1.1... | For limited numbers of zeros, you can replace `.0` with `.`:
```
select replace(replace(replace([output], '.00', '.'), '.0', '.'), '..', '.0.')
```
This is a bit of a hack, but it is relatively simple. | Trim first zero after dot twice sql query | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
**table**
```
id | term
---+-----
1 | 2015
2 | 2015
3 | 2016
```
I have this table and want to select all 2015 results:
```
select * from table where term = 2015
```
HOWEVER, I only want it to to return 2015 results IF 2015 is the only term that shows up in the table. If it has anything else, it should not ret... | You can use `NOT EXISTS` for this:
```
SELECT *
FROM table
WHERE term = 2015
AND NOT EXISTS (SELECT 1
FROM table
WHERE term <> 2015
)
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!9/40627/4/0)
`NOT EXISTS` evaluates to true if any records are returned by t... | I think what you are saying is: IF there are at least two different values in the term column, return nothing. If there is exactly one value, then return the entire table.
You didn't say if term is nullable (if it may contain nulls). Assuming it isn't, you can get your result very quickly this way:
```
select * from ... | Select results if table doesn't contain criteria | [
"",
"sql",
"oracle",
""
] |
I wonder how can I check if two users (**user\_id**) are in the same thread (**thread\_id**) without passing the (**thread\_id**) using SQL, through the structure of the table below.
[](https://i.stack.imgur.com/zXE6m.png) | To get all threads where those 2 users are in you can do
```
select thread_id
from your_table
where user_id in (1,2)
group by thread_id
having count(distinct user_id) = 2
```
To get all threads that have more than one user do
```
select thread_id
from your_table
group by thread_id
having count(distinct user_id) ... | I didn't understand very well what you wanted but as I understand it , I assume that this is.
```
select thread_id, COUNT(thread_id) AS dup_count from participant_thread as participant
GROUP BY thread_id
HAVING (COUNT(thread_id) > 1)
```
[result scrypt](https://i.stack.imgur.com/towu3.png) | SQL - Check if IDs contains same ID's value | [
"",
"mysql",
"sql",
""
] |
me trying to make distinct data in temporary table, trying to simple it with create table #tabletemp still got wrong, it says unrecognize data type near distinct and comma or closing bracket was expected near ponumber
here's the code :
```
CREATE TEMPORARY TABLE t1(
SELECT DISTINCT
PONumber varchar(10),
POdate va... | You don't need to create a temporary table to get the result that you want. Here is my revised query based on your query:
```
SELECT DISTINCT
p.PONumber,
p.POdate,
p.customername,
p.[description],
SUM(q.deliveryqty)
FROM tb_po p
INNER JOIN tb_spb q
ON p.PONumber = q.PONumber
AND p.descr... | If you really need it to be in a temporary table, another approach is using "SELECT INTO" wherein you wont need to declare the creation of a temporary table. (Although creating a table then inserting records is the more preferred method <https://stackoverflow.com/a/6948850/6344844>)
```
SELECT DISTINCT
p.PONumbe... | Select distinct in temp table | [
"",
"mysql",
"sql",
""
] |
I'm trying to make a prepared SQL statement using Doctrine.
If I hard code the value in the SQL query it's working:
```
public function search()
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = "myfile.exe"';
$query = $this->conn->prepare($sql);
$status = $query->execute();
$searchR... | After 2 days stuck on this problem I finally find the solution.
I just remove the line:
```
$searchResult = $this->conn->fetchAll($sql);
```
So the code below is working fine:
```
public function search($service)
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = ":service"';
$query = $this... | Looking at the docs <http://doctrine-orm.readthedocs.io/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html>
It should be:
```
public function search(){
$sql = 'SELECT `name` FROM `files` WHERE `name` = ?';
$query = $this->conn->prepare($sql);
$query->bindValue(1, "... | Why do I get a PDOException: SQLSTATE[42000] | [
"",
"sql",
"doctrine",
""
] |
* Table 1 has Id with random date and the corresponding value.
* Table 2 has id with sequence date (it’s not necessarily to be sequence).
Matching the Table2.Id and Table2.SequenceDate with Table1.Id and Table.RandomDate and then need to apply theTable1. value to the Table2 till the next Random Date occurs.
You can s... | Finally I got that logic, thanks everyone for all your inputs.
```
SELECT
t2.Id,
t2.SequenceDate,
t1.RandomDate,
t1.Value,
ISNULL(LEAD(RandomDate,1,NULL) OVER (PARTITION BY Id ORDER BY Id,RandomDate),DATEADD(YEAR,99,RandomDate)) AS nextRandomDte,
ISNULL(LAG(Rand... | I would use a subquery to get the expected value.
```
select
Table2.SequenceDate,
Table2.ID,
( select top 1 Table1.Value
from Table1
where Table1.RandomDate <= Table2.SequenceDate
and Table1.ID = Table2.ID
order by Table1.RandomDate desc
... | SQL Logic to merge two tables based on the given scenario | [
"",
"sql",
"sql-server",
""
] |
Suppose I have two `tables` with parent-child relationship in `sql server` as below,
parent table:
```
Parentid value
1 demo
2 demo2
```
child table:
```
childid parchildid subvalue
1 1 demo1
2 1 demo2
```
here `parchildid` from `child table` is a... | It is equivalent to writing:
```
select *
from child c
where c.parchildid in
(
select c.parchildid
from parent p
)
```
If you notice, `child` has an alias of `c` which is accessible inside the subquery.
It is also like writing:
```
select *
from child c
where Exists
(
... | From [MSDN](https://technet.microsoft.com/en-us/library/ms178050(v=sql.105).aspx):
> If a column does not exist in the table referenced in the FROM clause of a subquery, it is implicitly qualified by the table referenced in the FROM clause of the outer query.
In your case, since `parchildid` is a column from the tabl... | Issue with Parent-Child Relationship in Sql-Server | [
"",
"sql",
"sql-server",
"t-sql",
"parent-child",
""
] |
I Have following table.
[](https://i.stack.imgur.com/ZAgay.jpg)
Simply i want to make order by `meta_key` where value is `LoginTS`. its a bit distracting.
`ORDER BY meta_value( where meta_key is LoginTS ) DESC` .
Im sorry if its not clear enough..
... | ```
SELECT *
FROM mytable
WHERE `meta_key`= 'LoginTS'
ORDER BY `meta_value` DESC
```
**[SQL FIDDLE DEMO 1](http://sqlfiddle.com/#!9/4c7a5/5)**
If you want to get back all the Table but to ORDER BY specific column try this:
```
SELECT
*
FROM
myTable
ORDER BY CASE WHEN `meta_key`='LoginTS' THEN 0 ELSE 1 END... | WHERE should be placed before ORDER BY, try this:
```
WHERE meta_key = 'LoginTS' ORDER BY meta_value DESC
``` | SQL Ordering by field value | [
"",
"mysql",
"sql",
""
] |
I would like to make a report that will show the average grade for different tasks.
I am having trouble with how to get the averages. I need to figure out how to convert the grades to floats so that I can take the averages. The grades sometimes have non-numeric or null values, although most values look like "2.0" or "... | You could try using [IsNumeric](https://msdn.microsoft.com/en-us/library/ms186272.aspx)
```
Select
GradingScores.task As task,
Avg(Cast(GradingScores.score as float) As averages
From
GradingScores where IsNumeric(GradingScores.score) = 1
``` | Just simply convert() and use isnumeric() function in T-SQL
```
select avg(convert(float,score))
from GradingScores
where isnumeric(score)=1
``` | SQL: select average of varchar | [
"",
"sql",
"sql-server",
"casting",
"average",
"varchar",
""
] |
I executed the following query and it worked. I want to understand how it works.
```
select 50+2 from employees
```
This works only when the 'employees' table exists. If I mention a non existent table, then it throws an error.
How can such expressions be evaluated for user-defined tables? | What MySQL does first is it uses its parser to read the SQL statement and separate it into it's logical parts. A parser (used not only by MySQL but very often in programming) is just a block of code that retrieves raw information, and turns it into something that the program can use.
In the case of MySQL, it will sepa... | If you want to give expression then just use `SELECT .. Dual`
```
select 50+2 from dual
```
This will also result `52`
Why `select 50+2 from employees` because it is a just a constant value which will be displayed in all the rows of your table, Example the below query will also result constant value 'A' for all the ... | How SQL select statements work | [
"",
"sql",
"select",
"oracle11g",
""
] |
In the following query I get syntax error:
```
SELECT <property1>, <property2>
FROM <table1>
ORDER BY <condition> LIMIT 1
UNION ALL
SELECT <property1>, <property2>
FROM <table2>
WHERE <condition> ORDER BY <condition> LIMIT 1;
```
> syntax error at or near "UNION"
> LINE 4: UNION ALL
Each of the `SELECT` stand alo... | Wrap each query with `()`:
```
(SELECT <property1>, <property2>
FROM <table1>
ORDER BY <condition> LIMIT 1)
UNION ALL
(SELECT <property1>, <property2>
FROM <table2>
WHERE <condition> ORDER BY <condition> LIMIT 1);
```
`SqlFiddleDemo`
You could also order final query:
```
(SELECT 'a' AS col
ORDER BY col LIMIT 1)
... | The first answer of @lad2025 is correct,
but the generalization just under is not correct because must be the whole condition, desc clause included.
This is the correct code :
```
(SELECT 'a' AS col
ORDER BY col DESC LIMIT 1)
UNION ALL
(SELECT 'b' AS col
ORDER BY col DESC LIMIT 1)
ORDER BY col DESC LIMIT 1
```
oth... | SQL Union All with order by and limit (Postgresql) | [
"",
"sql",
"postgresql",
"union",
"union-all",
""
] |
I have a table in a db in SQL Server. Example of the data
```
ID StartDate EndDate Notes
0 2016-01-24 02:50:23 2016-01-25 08:00:05 somethingoranother
2 2016-01-30 22:00:00 2016-02-05 08:00:05 somethingoranother
```
On the front end (vb code) I am tak... | As it seems, you only want the records from a specific date untill a given date. The part of code that does the addition in your frontend would have to check if the row should be counted in your sum:
```
Dim fromthis As Date = #01/01/2016#
Dim tothis AS Date = #01/02/2016#
For i As Integer = 1 To XXX
If(table.Row... | Assuming row 0 should be treated similarly to row 2, I think this does what you want:
```
declare @t table (ID int not null,StartDate datetime not null,EndDate datetime not null,
Notes varchar(217) not null)
insert into @t(ID,StartDate,EndDate,Notes) values
(0,'2016-01-24T02:50:23','2016-02-05T08:00:... | How to get specific month end in VB.NET and SQL Server | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
```
select user_id, max(perception_score) as max, min(perception_score) as min from temp_user_notes group by user_id as t1;
```
I am trying to convert this sql query in rails active record but having a hard time to create aliases | You can alias the table to another name in the `from` method of ActiveRecord.
For example, part of your query could be:
```
TempUserNote.
select("t1.user_id, (t1.max - t1.min) as std_deviation").
from(
TempUserNote.
select("user_id, max(perception_score) as max, min(perception_score) as min").
gro... | Just use the SQL alias feature inside a `select` method call:
```
TempUserNote.select('user_id, max(perception_score) as max, min(perception_score) as min').group(:user_id)
``` | how to create alias of table name in Rails ActiveRecords | [
"",
"sql",
"ruby-on-rails",
"ruby",
"activerecord",
""
] |
I have a table like
```
ID | Name | ProdID | Model | StudID
-----------------------------------
1 | A | 3 | hey | 6
2 | B | 4 | he | 7
2 | C | 5 | hi | 8
```
I need to make just `Model` and `StudID` values to `N/A` when `ProdID` is 4 and 5
```
ID | Name | ProdID | Model | Stu... | Try this
```
SELECT
ID,
Name,
ProdID,
CASE
WHEN ProdID IN( 4,5) THEN 'N/A'
ELSE CONVERT(VARCHAR, Model)
END AS 'Model',
CASE
WHEN ProdID IN( 4,5) THEN 'N/A'
ELSE CONVERT(VARCHAR, StudID)
END AS 'StudID'
``` | First, you need to be quite careful about types.
* Don't convert values to strings unless you have to.
* When using `convert()` or `cast()` *always* include a length for `varchar()`.
So:
```
SELECT ID, Name, ProdId,
(CASE WHEN ProdId IN (4, 5) THEN Model ELSE 'N/A' END) as Model,
(CASE WHEN ProdId IN (... | Convert column to a different value based on another columns value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How I can skip the duplicate record when list sorted, for example,
I have table:
```
EmpID Date Dept OtherField
1 2017.02.03 11 1
1 2016.02.03 11 2
1 2015.02.03 13 7
1 2014.02.03 21 6
1 2013.02.03 21 12
1 2012.02.03 13 ... | Thanks for the clarification. [Tabibitosan](http://rwijk.blogspot.co.uk/2014/01/tabibitosan.html) would suit your needs, I believe:
```
with sample_data as (select 1 empid, to_date('03/02/2017', 'dd/mm/yyyy') dt, 11 dept, 1 otherfield from dual union all
select 1 empid, to_date('03/02/2016', 'dd/m... | Idea: `Partition by` duplicated fields to get first row using `row_number()`
Implementation:
```
select EmpID, Date, Dept, OtherField
from ( select EmpID, Date, Dept, OtherField,
row_number() over (partition by empid, dept order by date asc) rwn
from table_name) t
where rwn = 1;
```
Accordin... | Oracle, skip duplicate rows on specific key by sort | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
A coworker and myself stumbled upon a newly acquired database schema with multiple tables that seem to only have one column. One table seems to be some sort of type, and the another for some sort of frequency, etc. We are only dealing with a schema here so there's no actual data to go by.
We were thinking it over, and... | Almost every table that I create has the following columns:
* Primary key (generally a number and named after the table is `Id` after it).
* CreatedAt
* CreatedBy
* CreatedOn (the server where the row was created)
One use for a single column table is to effectively implement a check constraint where the code can dyna... | As I see it, that depends on the use of this tables.
If you have a lot of them, its probably wrong. I can think of a few uses of a single column table , they can be used as `derived tables` to generate ID's, sequences , dates(which probably be more useful with more then 1 column to specify month,year..) ETC but I beli... | Is having a single column table in SQL Server considered a bad practice? | [
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I want to select all the planes that aren't belong to a certain company. I have three tables in this case: `Planes`, `Companies`, and `CompanyPlanes`.
Here is my query:
```
SELECT *
FROM planes p,
companyplanes cp,
companies c
WHERE c.id = ?
AND cp.idCompany != c.id
AND (cp.idPlane = p.id OR p.id NOT IN... | **Update Answer**
We can get the result in following way
1. Get all planes of the unexpected company
`SELECT idplane from CompanyPlanes
WHERE idCompany = ?`
2. Get all planes without those planes of the unexpected company
`SELECT * FROM Planes
WHERE id NOT IN
(
SELECT idplane from CompanyPlanes
... | The inner join requires that the query return rows from planes which have a corresponding row in companyplanes but the subselect excludes any rows which have corresponding records in companyplanes.
Assuming that you want the records from planes which don't have a record in companyplanes, then why are you also selectin... | Select from table where id is not in another | [
"",
"mysql",
"sql",
""
] |
I have a table with a locale field like this:
```
Id, locale
1, "en-US"
2, "en-BR"
3, "en-SK"
4, "fr-FR"
5, "fr-FS"
```
I want to do a select on this table, and group based on "en" or "fr" (part of the locale field string), what should i write to accomplish this? | Alternatively, you may also use the LEFT() function
```
SELECT left(locale, 2), count(id) FROM table group by left(locale, 2)
```
At the end of the day, the important part is to make use of a `group by` statement which contains a function.
Note that this works in MySQL very well. Other DBMS might not like this. | You can use a combination of `substring` and `instr`.
```
select substring(locale,1,instr(locale,'-')-1), count(*)
from tablename
group by substring(locale,1,instr(locale,'-')-1)
``` | GROUP BY based on String value | [
"",
"mysql",
"sql",
""
] |
I have to create a dynamic sql query in SP. the dynamic query is 5000 chars, and I used NVARCHAR(MAX),VARCHAR(MAX), NVARCHAR(6000), VARCHAR(6000) but they all truncate to 4000 chars
```
DECLARE @SCRIPT VARCHAR(8000)
set @SCRIPT =' ASDADASD ASDA DSADAD AD AS D......' +@VAR1+ ' AWDAWd' -- 6000 CHARS
PRINT LEN(@SCRIP... | Use the `nvarchar(max)` data type instead.
Be sure to prefix string literals with the N designator (`N' ASDADASD...'`). Cast explicitely so the default limitation will not apply:
```
set @script=convert(nvarchar(max),N'very-long-literal')
```
(reference: [The weird length of varchar and nvarchar in T-SQL](https://sta... | NVARCHAR(n) is limited to 4000, VARCHAR + NVARCHAR = NVARCHAR. Look at
```
DECLARE @SCRIPT VARCHAR(8000)
set @SCRIPT = replicate('A',6000)+'A'
select len(@SCRIPT)
set @SCRIPT = replicate('A',6000)+N'A'
select len(@SCRIPT), 'mind NVARCHAR'
```
Cast everything NVARCHAR(MAX) to be sure.
```
DECLARE @SCRIPT NVARCHAR(M... | cannot store 5000 chars in NVARCHAR and VARCHAR | [
"",
"sql",
"sql-server",
"stored-procedures",
"varchar",
"nvarchar",
""
] |
I have a problem when displaying several coloumns with counting, this is my table "Empo" :
```
idEmp DeptA DeptB
---- ---- ----
1 23 7
2 42 23
3 23 11
4 23 17
```
And I want to count number of idEmp , and the number of times where '23' is in every Dep... | The method I have used in the past is to use a combination of Count and Sum.
```
select count(idEmp),
sum(Case when DeptA = 23 Then 1 else 0 End),
sum(Case when DeptB = 23 Then 1 else 0 End)
from tableX
```
Edit for question.
I would use a subselect for the new case to prevent duplicates being added to the original... | Try below query :-
```
select (select count(id) from test) as countID,
(select count(DeptA) from test where DeptA=23) as CountDeptA,
(select count(DeptB) from test where DeptB=23) as CountDeptB
``` | SQL select multiple coloumns each one count somthing | [
"",
"mysql",
"sql",
"count",
""
] |
## select value = Hemraj and value = pal, where field\_id = 3 and where field\_id = 4;
```
how to solve this query?
table structure :
field_id = 3 value = Hemraj
field_id = 4 value = Pal
field_id = 3 value = Subhankar
field_id = 4 value = Chaole
field_id = 3 value = Suman
field_id = 4 value = Pal
field_id ... | What about this?
```
SELECT value FROM engine4_user_fields_values
where field_id=3
or field_id=4
or field_id=5
or field_id=6 ....
``` | You can also use IN operator
```
SELECT value FROM engine4_user_fields_values
where field_id IN (3,4,5,6)
``` | How to solve this multiple where conditions(field_ids and values)? | [
"",
"mysql",
"sql",
""
] |
I've been trying to use code which finds the count of elements in a table and stores it in a local variable. I basically just want to check the existence of a record, so if there is any easier way to do this.
Here is an example I found of storing the result of a query in a variable ([link](https://www.ibm.com/support/... | The position of the `INTO` clause is wrong in both functions. The INTO clause goes after the *select-list* (the list of expressions after the keyword SELECT) and before the FROM clause (see the Informix "Guide to SQL: Syntax" manual on the [SELECT](https://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqls.... | The could be related to the fact the insert dont have the columns name
adapt your\_column1, your\_column2 to your table schema
```
INSERT INTO t_queued_calls (your_column1, your_column2) VALUES (123456, '5555555555');
SELECT COUNT(*) FROM t_queued_calls INTO l_count WHERE session_id = 123456;
```
And/Or the number... | Informix SELECT INTO syntax error | [
"",
"sql",
"syntax",
"informix",
""
] |
I have two tables with many to many relationship. I need to join them and get the matched records.
```
Table 1
Column1 | column 2| column 3|
1|p1|1.0
1|p1|1.1
1|p1|1.2
Table 2
Column1 | column 2| column 3|
1|p1|2.0
1|p1|2.1
1|p1|2.2
```
Now I want the result as
```
1|p1|1.0|2.0
1|p1|1.1|2.1
1|p1|1.2|2.2
```
I me... | If you have unequal numbers of rows for each partition then you can do:
**Oracle Setup**:
```
CREATE TABLE table1 ( col1, col2, col3 ) AS
SELECT 1, 'P1', '1.0' FROM DUAL UNION ALL
SELECT 1, 'P1', '1.1' FROM DUAL UNION ALL
SELECT 1, 'P1', '1.2' FROM DUAL UNION ALL
SELECT 1, 'P2', '1.0' FROM DUAL UNION ALL
SELECT 1, 'P... | Please try below.
```
create table tab1(Col1 int,col2 varchar(10), col3 varchar(10))
insert into tab1
values(1,'p1','1.0'),
(1,'p1','1.1'),
(1,'p1','1.2')
create table tab2(Col1 int,col2 varchar(10), col3 varchar(10))
insert into tab2
values(1,'p1','2.0'),
(1,'p1','2.1'),
(1,'p1','2.2')
SELECT a.col1,a.col2,a.col3... | Joining two tables with many to many relationship in sql | [
"",
"sql",
"sql-server",
"oracle",
""
] |
I answered that tables had only one primary key but could have many unique constraints.
But what else? | Primary column can never be null, a unique column can be. | Some differences I could think of:
1. Primary Key can't be null whereas unique will allow one null value.
2. You can have multiple unique keys on a table but only one Primary Key.
Some taken from WikiPedia - [Unique key - Differences from primary key constraints](https://en.wikipedia.org/wiki/Unique_key#Differences_f... | What are the main differences between a primary key and a unique constraint? | [
"",
"sql",
"primary-key",
"unique-constraint",
""
] |
I have a table with 2 columns (id, name) with following values:
```
id name
--- ---
1 John
2 John
3 Mary
4 Mary
```
For values that are repeated in 'name', I only want to select those rows which have maximum value in 'id'. So my desired output is:
```
id name
--- ---
2 John
4 Mary
... | If you alias your subquery you will avoid the syntax error... try putting "AS MyTable" after your closing parenthesis
```
select name, id
FROM ( select name, max(id) over (partition by name) max_ID from sometable ) AS MyTable
where id = max_ID
```
This might be simpler though:
```
SELECT name, MAX(id) FROM tablena... | Your subquery has no mandatory alias
```
..
FROM ( select name, max(id) over (partition by name) max_ID from sometable ) t -- alias missing
..
``` | TSQL: Get a row which has a max value for a column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table with step id and resident id. I wanted to write a query find the second largest step id for a particular resident.
The query using max in the google examples doesn't have the where clause.
Tried this:
```
SELECT DISTINCT(step_action_id)
FROM step_table where resident_id =219
ORDER BY step_action_id D... | If the step ids are distinct, you can just use `OFFSET` and `FIRST FIRST 1 ROW ONLY`:
```
SELECT step_action_id
FROM step_table
WHERE resident_id = 219
ORDER BY step_action_id DESC
OFFSET 1 ROWS
FETCH FIRST 1 ROW ONLY;
```
If they are not distinct, just add a `GROUP BY` or `SELECT DISTINCT`:
```
SELECT step_action... | You could use `ROW_NUMBER()`:
```
SELECT step_action_id
FROM (
SELECT step_action_id, ROW_NUMBER() OVER(ORDER BY step_action_id DESC) AS rn
FROM (SELECT DISTINCT step_action_id
FROM step_table
WHERE resident_id = 219
) AS s
) AS s2
WHERE rn = 2;
```
`LiveDemo` | SQL query for second largest value with a where condition | [
"",
"sql",
"db2",
"greatest-n-per-group",
""
] |
I wrote a query to compare 2 columns in different tables (`TRELAY` VS `TUSERDEF8`). The query works great, except that it retrieves the top record in the `TUSERDEF8` table which has a many to one relationship to the `TRELAY` table.
The tables are linked by `TRELAY.ID = TUSERDEF8.N01`. I would like to retrieve the late... | Using an ID column to determine which row is "last" is a bad idea
Using cryptic table names like "TUSERDEF8" (how is it different from TUSERDEF7) is a very bad idea, along with completely cryptic column names like "S04".
Using prefixes like "T" for table is a bad idea - it should already be clear that it's a table.
... | I believe that your expected output is still a little ambiguous.
It sounds to me like you want only the record from the output where TUSERDEF8.ID is at its max. If that's correct, then try this:
```
SELECT TRELAY.ID, TRELAY.S15, TUSERDEF8.S04, TUSERDEF8.N01, TUSERDEF8.S06
FROM TRELAY
INNER JOIN TUSERDEF8 ON TRELAY.... | SQL query to retrieve last record from a linked table | [
"",
"sql",
"sql-server",
"greatest-n-per-group",
""
] |
I have a stored procedure in SQL Server which takes 3 parameters and returns a list of Orders like this:
```
@fieldToFilter VARCHAR(100), --Will only be 1 of these values 'Order Date', 'Delivery Date' or 'Dispatch Date'
@StartDate DATE,
@EndDate DATE
SELECT
o.Number, o.Customer
FROM
Order o
WHERE
(o.Or... | I'm not sure if I got the syntax right but something like this should work
```
SELECT o.Number, o.Customer
FROM Order o
WHERE (@StartDate < case when @fieldToFilter = 'Order Date' then o.OrderDate
when @fieldToFilter = 'Delivery Date' then o.DeliveryDate
... | This should get you started. Just replace the other two SELECT statements with the appropriate filters.
```
IF @fieldToFilter = 'Order Date'
BEGIN
SELECT o.Number, o.Customer
FROM Order o
WHERE (o.OrderDate > @StartDate) and (o.OrderDate < @EndDate) and SoftDeleted=0)
END
ELSE IF @fieldToFilter = 'Delivery... | SQL Query on Field Name passed into stored procedure | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I just started in a new project, in a new company.
I was given a big and complex SQL, with about 1000 lines and MANY subqueries, joins, sums, group by, etc.
This SQL is used for report generation (it has no inserts nor updates).
The SQL has some flaws, and my first job in the company is to identify and correct these... | The solution was to simplify the query using COMMON TABLE EXPRESSIONS.
This allowed me to break the big and complex SQL query into many small and easy to understand queries.
**COMMON TABLE EXPRESSIONS:**
* Can be used to break up complex queries, especially complex joins and sub-queries
* Is a way of encapsulating a... | I deal with code like this every day as we do a lot of reporting and exporting of complex data here.
**Step one is to understand the meaning of what you are doing.** If you don't understand the meaning, you can't evaluate if you got the correct results. So understand exactly what you are trying to accomplish and see i... | Best way to understand big and complex SQL queries with many subqueries | [
"",
"sql",
"db2",
"subquery",
""
] |
Using SQL server, I have a table that looks something like the following:
```
id | time | measurement
---+---------------------+-------------
1 | 2014-01-01T05:00:00 | 1.0
1 | 2014-01-01T06:45:00 | 2.0
1 | 2014-01-01T09:30:00 | 3.0
1 | 2014-01-01T11:00:00 | NULL
1 | 2014-02-05T03:00:00 | 1.0
1 | 2... | Its complex, but working (for dataset you provided)
```
;WITH cte AS (
SELECT *
FROM (VALUES
(1, '2014-01-01T05:00:00', '1.0'),(1, '2014-01-01T06:45:00', '2.0'),
(1, '2014-01-01T09:30:00', '3.0'),(1, '2014-01-01T11:00:00', NULL),
(1, '2014-02-05T03:00:00', '1.0'),(1, '2014-02-05T05:00:00', NULL)
) as t (id, [time], me... | ```
DECLARE @t TABLE
(
id INT ,
t DATETIME ,
m MONEY
)
INSERT INTO @t
VALUES ( 1, '2014-01-01T05:00:00', 1.0 ),
( 1, '2014-01-01T06:45:00', 2.0 ),
( 1, '2014-01-01T09:30:00', 3.0 ),
( 1, '2014-01-01T11:00:00', NULL ),
( 1, '2014-02-05T03:00:00', 1.0 ),
... | Synthesizing SQL rows within a range | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.